././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9964476 dulwich-0.22.7/0000755000175100002000000000000014731042565012640 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/.testr.conf0000644000175100002000000000023214731042555014722 0ustar00runnerdocker[DEFAULT] test_command=PYTHONPATH=. python3 -m subunit.run $IDOPTION $LISTOPT tests.test_suite test_id_option=--load-list $IDFILE test_list_option=--list ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/AUTHORS0000644000175100002000000001335114731042555013712 0ustar00runnerdockerJelmer Vernooij Dave Borowitz John Carr Gary van der Merwe milki Augie Fackler Tay Ray Chuan Risto Kankkunen Jonas Haag Fabien Boucher James Westby Mike Edgar Koen Martens Abderrahim Kitouni William Grant Marcin Kuzminski Ryan Faulkner Julian Berman Mark Mikofski Michael K Ali Sabil Damien Tournoud Hannu Valtonen Mika Mäenpää Paul Hummer Lele Gaifax Lukasz Balcerzak Tommy Yu anatoly techtonik bmcorser Brendan Cully Chow Loong Jin Chris Eberle Dmitriy Hervé Cauwelier Hugo Osvaldo Barrera Jameson Nash Marc Brinkmann Nicolas Dandrimont Robert Brown Siddharth Agarwal Stefan Zimmermann Takeshi Kanemoto Yifan Zhang Aaron O'Mullan Adam "Cezar" Jenkins Alberto Ruiz Alexander Belchenko Andreas Kloeckner André Roth Benjamin Pollack Benoit HERVIER Dan Callaghan David Keijser David Ostrovsky David Pursehouse Dmitrij D. Czarkoff Doug Hellmann Dov Feldstern Félix Mattrat Hwee Miin Koh Jason R. Coombs Jeremy Whitlock John Arbash Meinel Laurent Rineau Martin Packman Max Shawabkeh Michael Hudson Nick Stenning Nick Ward Paul Chen Roland Mas Ronald Blaschke Ronny Pfannschmidt Ross Light Ryan McKern Ted Horst Thomas Liebetraut Timo Schmid Víðir Valberg Guðmundsson dak180 Akbar Gumbira Alex Holmes Andi McClure Andres Lowrie Artem Tikhomirov Brian Visel Bruce Duncan Bruno Renié Chaiwat Suttipongsakul Chris Bunney Chris Reid Daniele Sluijters David Bennett David Blewett David Carr Dirk Elan Ruusamäe Forrest Hopkins Hal Wine Hans Kolek Jakub Wilk JonChu Kostis Anagnostopoulos Kyle Kelly Lionel Flandrin Max Bowsher <_@maxb.eu> Mike Williams Mikhail Terekhov Nix OnMaster Pascal Quantin Ricardo Salveti Rod Cloutier Sam Vilain Stefano Rivera Steven Myint Søren Løvborg Travis Cline Victor Stinner Volodymyr Holovko Yuval Langer codingtony jon bain kwatters max Segev Finer fviolette dzhuang Antoine Pietri Taras Postument Earl Chew Daniel Andersson Fabian Grünbichler Kenneth Lareau Antoine R. Dumont (@ardumont) Alistair Broomhead Marcel Schnirring Adam Bradley Filipp Frizzy Romain Keramitas semyon-slepov Daniel M. Capella grun Sylvia van Os Boris Feld KS Chan egor Antoine Lambert Lane Barlow Manuel Jacob Brecht Machiels Peter Rowlands If you contributed but are missing from this list, please send me an e-mail. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/CONTRIBUTING.rst0000644000175100002000000000401414731042555015277 0ustar00runnerdockerAll functionality should be available in pure Python. Optional Rust implementations may be written for performance reasons, but should never replace the Python implementation. Where possible include updates to NEWS along with your improvements. New functionality and bug fixes should be accompanied by matching unit tests. Coding style ------------ Where possible, please follow PEP8 with regard to coding style. Run ruff. Furthermore, triple-quotes should always be """, single quotes are ' unless using " would result in less escaping within the string. Public methods, functions and classes should all have doc strings. Please use Google style docstrings to document parameters and return values. You can generate the documentation by running "make doc". Running the tests ----------------- To run the testsuite, you should be able to simply run "make check". This will run the tests using unittest. :: $ make check Tox configuration is also present. String Types ------------ Like Linux, Git treats filenames as arbitrary bytestrings. There is no prescribed encoding for these strings, and although it is fairly common to use UTF-8, any raw byte strings are supported. For this reason, the lower levels in Dulwich treat git-based filenames as bytestrings. It is up to the Dulwich API user to encode and decode them if necessary. The porcelain may accept unicode strings and convert them to bytestrings as necessary on the fly (using 'utf-8'). * on-disk filenames: regular strings, or ideally, pathlib.Path instances * git-repository related filenames: bytes * object sha1 digests (20 bytes long): bytes * object sha1 hexdigests (40 bytes long): str (bytestrings on python2, strings on python3) Merge requests -------------- Please either send pull requests to the maintainer (jelmer@jelmer.uk) or create new pull requests on GitHub. Licensing --------- All contributions should be made under the same license that Dulwich itself comes under: both Apache License, version 2.0 or later and GNU General Public License, version 2.0 or later. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/COPYING0000644000175100002000000007160514731042555013703 0ustar00runnerdockerDulwich may be used under the conditions of either of two licenses, the Apache License (version 2.0 or later) or the GNU General Public License, version 2.0 or later. SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This 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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/Cargo.lock0000644000175100002000000001133214731042555014544 0ustar00runnerdocker# This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "autocfg" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "diff-tree-py" version = "0.22.7" dependencies = [ "pyo3", ] [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "indoc" version = "2.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5" [[package]] name = "libc" version = "0.2.164" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "433bfe06b8c75da9b2e3fbea6e5329ff87748f0b144ef75306e674c3f6f7c13f" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "memoffset" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" dependencies = [ "autocfg", ] [[package]] name = "objects-py" version = "0.22.7" dependencies = [ "memchr", "pyo3", ] [[package]] name = "once_cell" version = "1.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" [[package]] name = "pack-py" version = "0.22.7" dependencies = [ "memchr", "pyo3", ] [[package]] name = "portable-atomic" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc9c68a3f6da06753e9335d63e27f6b9754dd1920d941135b7ea8224f141adb2" [[package]] name = "proc-macro2" version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" dependencies = [ "unicode-ident", ] [[package]] name = "pyo3" version = "0.23.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e484fd2c8b4cb67ab05a318f1fd6fa8f199fcc30819f08f07d200809dba26c15" dependencies = [ "cfg-if", "indoc", "libc", "memoffset", "once_cell", "portable-atomic", "pyo3-build-config", "pyo3-ffi", "pyo3-macros", "unindent", ] [[package]] name = "pyo3-build-config" version = "0.23.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc0e0469a84f208e20044b98965e1561028180219e35352a2afaf2b942beff3b" dependencies = [ "once_cell", "target-lexicon", ] [[package]] name = "pyo3-ffi" version = "0.23.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eb1547a7f9966f6f1a0f0227564a9945fe36b90da5a93b3933fc3dc03fae372d" dependencies = [ "libc", "pyo3-build-config", ] [[package]] name = "pyo3-macros" version = "0.23.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb6da8ec6fa5cedd1626c886fc8749bdcbb09424a86461eb8cdf096b7c33257" dependencies = [ "proc-macro2", "pyo3-macros-backend", "quote", "syn", ] [[package]] name = "pyo3-macros-backend" version = "0.23.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38a385202ff5a92791168b1136afae5059d3ac118457bb7bc304c197c2d33e7d" dependencies = [ "heck", "proc-macro2", "pyo3-build-config", "quote", "syn", ] [[package]] name = "quote" version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" dependencies = [ "proc-macro2", ] [[package]] name = "syn" version = "2.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "target-lexicon" version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" [[package]] name = "unicode-ident" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" [[package]] name = "unindent" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7de7d73e1754487cb58364ee906a499937a0dfabd86bcb980fa99ec8c8fa2ce" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/Cargo.toml0000644000175100002000000000020214731042555014561 0ustar00runnerdocker[workspace] members = ["crates/*"] resolver = "2" [workspace.dependencies] pyo3 = "0.23" [workspace.package] version = "0.22.7" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/MANIFEST.in0000644000175100002000000000071714731042555014402 0ustar00runnerdockerinclude NEWS include AUTHORS include README.rst include README.swift.rst include Makefile include COPYING include CONTRIBUTING.rst include TODO include setup.cfg include dulwich/stdint.h include dulwich/py.typed recursive-include docs conf.py *.txt Makefile make.bat recursive-include examples *.py recursive-include crates *.rs Cargo.toml graft tests/ graft testdata/ include tox.ini include dulwich.cfg include .testr.conf include Cargo.toml include Cargo.lock ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/Makefile0000644000175100002000000000270614731042555014304 0ustar00runnerdockerPYTHON = python3 RUFF ?= $(PYTHON) -m ruff SETUP = $(PYTHON) setup.py TESTRUNNER ?= unittest RUNTEST = PYTHONHASHSEED=random PYTHONPATH=$(shell pwd)$(if $(PYTHONPATH),:$(PYTHONPATH),) $(PYTHON) -m $(TESTRUNNER) $(TEST_OPTIONS) COVERAGE = python3-coverage DESTDIR=/ all: build doc:: sphinx sphinx:: $(MAKE) -C docs html build:: $(SETUP) build $(SETUP) build_ext -i install:: $(SETUP) install --root="$(DESTDIR)" check:: build $(RUNTEST) tests.test_suite check-tutorial:: build $(RUNTEST) tests.tutorial_test_suite check-nocompat:: build $(RUNTEST) tests.nocompat_test_suite check-compat:: build $(RUNTEST) tests.compat_test_suite check-pypy:: clean $(MAKE) check-noextensions PYTHON=pypy check-noextensions:: clean $(RUNTEST) tests.test_suite check-contrib:: clean $(RUNTEST) -v dulwich.contrib.test_suite check-all: check check-pypy check-noextensions typing: $(PYTHON) -m mypy dulwich clean:: $(SETUP) clean --all rm -f dulwich/*.so style: $(RUFF) check . coverage: $(COVERAGE) run -m unittest tests.test_suite dulwich.contrib.test_suite coverage-html: coverage $(COVERAGE) html .PHONY: apidocs apidocs: pydoctor --intersphinx http://urllib3.readthedocs.org/en/latest/objects.inv --intersphinx http://docs.python.org/3/objects.inv --docformat=google dulwich --project-url=https://www.dulwich.io/ --project-name=dulwich fix: ruff check --fix . reformat: ruff format . .PHONY: codespell codespell: codespell --config .codespellrc . ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/NEWS0000644000175100002000000021466114731042555013350 0ustar00runnerdocker0.22.7 2024-12-19 * Fix serializing of commits with empty commit messages. (Castedo Ellerman, #1429) 0.22.6 2024-11-16 * ``ObjectStore.iter_prefix``: fix handling of missing loose object directories. (Jelmer Vernooij) * Reject invalid refcontainer values (not 40 characters or symref). (Arun Babu Neelicattu) * Add type hints to various functions. (Castedo Ellerman) 0.22.5 2024-11-07 * Drop support for Python 3.8. (Jelmer Vernooij) * Fix refspec handling in porcelain.pull. (Jelmer Vernooij) * Drop broken refspec support in porcelain.clone. (Jelmer Vernooij) * Provide ``ref_prefix`` functionality client-side if the server does not support it. (Jelmer Vernooij) * Consistently honor ``ref_prefix`` and ``protocol_version`` arguments in client. (Jelmer Vernooij) * Strip pkt-line when negotiating protocol v2. Fixes compatibility with gerrit. (Rémy Pecqueur, #1423) * Don't pull in ``setuptools_rust`` when building pure package. (Eli Schwartz) * Return peeled refs from ``GitClient.get_refs`` if protocol-v2 is used. (Stefan Sperling, #1410) * Drop outdated performance file. (Jelmer Vernooij, #1411) 0.22.4 2024-11-01 * Fix handling of symrefs with protocol v2. (Jelmer Vernooij, #1389) * Add ``ObjectStore.iter_prefix``. (Jelmer Vernooij) * Revert back to version 3 of ``Cargo.lock``, to allow building with older Cargo versions. (Jelmer Vernooij) * Use a default ref-prefix when fetching with git protocol v2 (Stefan Sperling, #1389) * Add `ObjectStore.iter_prefix`. (Jelmer Vernooij) 0.22.3 2024-10-15 * Improve wheel building in CI, so we can upload wheels for the next release. (Jelmer Vernooij) 0.22.2 2024-10-09 * Ship ``Cargo.lock``. (Jelmer Vernooij, #1287) * Ship ``tests/`` and ``testdata/`` in sdist. (Jelmer Vernooij, #1292) * Add initial integration with OSS-Fuzz for continuous fuzz testing and first fuzzing test (David Lakin, #1302) * Drop Python 3.7 support. (Jelmer Vernooij) * Improve fuzzing coverage (David Lakin) * Support Python 3.13. (Edgar Ramírez-Mondragón, #1352) * Initial support for smart protocol v2. (Stefan Sperling) 0.22.1 2024-04-23 * Handle alternate case for worktreeconfig setting (Will Shanks, #1285) * Ship rust files. (Jelmer Vernooij, #1287) 0.22.0 2024-04-22 * Stop installing docs/ as part of package code. (Jelmer Vernooij, #1248) * Move tests to root. (Jelmer Vernooij, #1024) * Convert the optional C implementations to Rust. (Jelmer Vernooij) 0.21.7 2023-12-05 * Fix NameError when encountering errors during HTTP operation. (Jelmer Vernooij, #1208) * Raise exception when default identity can't be found. (Jelmer Vernooij) * Add a dedicated exception class for unresolved deltas. (Jelmer Vernooij, #1221) * Support credentials in proxy URL. (Jelmer Vernooij, #1227) * Add ``dulwich.porcelain.for_each_ref``. (Daniele Trifirò) 0.21.6 2023-09-02 * Convert _objects.c to rust. (Jelmer Vernooij) * index: Handle different stages of conflicted paths. (Kevin Hendricks, Jelmer Vernooij) * Improve LCA finding performance. (Kevin Hendricks) * client: Handle Content-Type with encoding set. (Antoine Lambert) * Only import _hashlib for type checking. (David Hotham) * Update docs regarding building dulwich without c bindings (#103) (Adam Plaice) * objects: Define a stricter return type for _parse_message (Vincent Lorentz) * Raise GitProtocolError when encountering HTTP Errors in HTTPGitClient. (Jelmer Vernooij, #1199) 0.21.5 2023-05-04 * Be more tolerant to non-3-length tuple versions. (Jelmer Vernooij) 0.21.4.1 2023-05-04 * Support ``core.symlinks=false``. (Jelmer Vernooij, #1169) * Deprecate ``dulwich.objects.parse_commit``. * Fix fetching into MemoryRepo. (Jelmer Vernooij, #1157) * Support ``init.defaultBranch`` config. (Jelmer Vernooij) * Fix ``ObjectStore.iterobjects_subset()`` when hex shas are passed for objects that live in packs. (Jelmer Vernooij, #1166) * client: Handle absolute path as redirect location in HTTP client. (Antoine Lambert) 0.21.3 2023-02-17 * Add support for ``worktreeconfig`` extension. (Jelmer Vernooij) * Deprecate ``Commit.extra``; the Git project specifically discourages adding custom lines, and the contents of ``Commit.extra`` are unpredictable as contents may be different between different versions of Dulwich with support for different headers. ``Commit._extra`` still exists. (Jelmer Vernooij) 0.21.2 2023-01-18 * Fix early file close bug in ``dulwich.pack.extend_pack``. (Jelmer Vernooij) 0.21.1 2023-01-17 * Factor out ``dulwich.pack.extend_pack``. (Jelmer Vernooij) 0.21.0 2023-01-16 * Pack internals have been significantly refactored, including significant low-level API changes. As a consequence of this, Dulwich now reuses pack deltas when communicating with remote servers, which brings a big boost to network performance. (Jelmer Vernooij) * Add 'pack-refs' command. (Dan Villiom Podlaski Christiansen) * Handle more errors when trying to read a ref (Dan Villiom Podlaski Christiansen) * Allow for reuse of existing deltas while creating pack files (Stefan Sperling) * cli: fix argument parsing for pack-objects --stdout (Stefan Sperling) * cli: open pack-objects output files in binary mode to avoid write() error (Stefan Sperling) * Bump minimum python version to 3.7. (Jelmer Vernooij) * honor no_proxy environment variable (#1098, afaul) * In HTTP Git Client, allow missing Content-Type. (Jelmer Vernooij) * Fix --pure builds (Jelmer Vernooij, #1093) * Allow passing abbrev to describe (#1084, Seppo Yli-Olli) 0.20.50 2022-10-30 * Add --deltify option to ``dulwich pack-objects`` which enables deltification, and add initial support for reusing suitable deltas found in an existing pack file. (Stefan Sperling) * Fix Repo.reset_index. Previously, it instead took the union with the given tree. (Christian Sattler, #1072) * Add -b argument to ``dulwich clone``. (Jelmer Vernooij) * On Windows, provide a hint about developer mode when creating symlinks fails due to a permission error. (Jelmer Vernooij, #1005) * Add new ``ObjectID`` type in ``dulwich.objects``, currently just an alias for ``bytes``. (Jelmer Vernooij) * Support repository format version 1. (Jelmer Vernooij, #1056) * Support \r\n line endings with continuations when parsing configuration files. (Jelmer Vernooij) * Fix handling of SymrefLoop in RefsContainer.__setitem__. (Dominic Davis-Foster, Jelmer Vernooij) 0.20.46 2022-09-06 * Apply insteadOf to rsync-style location strings (previously it was just applied to URLs). (Jelmer Vernooij, python-poetry/poetry#6329) * Drop use of certifi, instead relying on urllib3's default code to find system CAs. (Jelmer Vernooij, #1025) * Implement timezone parsing in porcelain. (springheeledjack0, #1026) * Drop support for running without setuptools. (Jelmer Vernooij) * Ensure configuration is loaded when running "dulwich clone". (Jelmer Vernooij) * Build 32 bit wheels for Windows. (Benjamin Parzella) * tests: Ignore errors when deleting GNUPG home directory. Fixes spurious errors racing gnupg-agent. Thanks, Matěj Cepl. Fixes #1000 * config: Support closing brackets in quotes in section names. (Jelmer Vernooij, #10124) * Various and formatting fixes. (Kian-Meng Ang) * Document basic authentication in dulwich.porcelain.clone. (TuringTux) * Flush before calling fsync, ensuring buffers are filled. (wernha) * Support GPG commit signing. (springheeledjack0) * Add python 3.11 support. (Saugat Pachhai) * Allow missing GPG during tests. (Jakub Kulík) * status: return posix-style untracked paths instead of nt-style paths on win32 (Daniele Trifirò) * Honour PATH environment when running C Git for testing. (Stefan Sperling) * Split out exception for symbolic reference loops. (Jelmer Vernooij) * Move various long-deprecated methods. (Jelmer Vernooij) 0.20.45 2022-07-15 * Add basic ``dulwich.porcelain.submodule_list`` and ``dulwich.porcelain.submodule_add`` (Jelmer Vernooij) 0.20.44 2022-06-30 * Fix reading of chunks in server. (Jelmer Vernooij, #977) * Support applying of URL rewriting using ``insteadOf`` / ``pushInsteadOf``. (Jelmer Vernooij, #706) 0.20.43 2022-06-07 * Lazily import url2pathname. (Jelmer Vernooij) * Drop caching of full HTTP response. Attempt #2. (jelmer Vernooij, Antoine Lambert, #966) 0.20.42 2022-05-24 * Drop ``RefsContainer.watch`` that was always flaky. (Jelmer Vernooij, #886) 0.20.41 2022-05-24 * Fix wheel uploading, properly. (Ruslan Kuprieiev) 0.20.40 2022-05-19 * Fix wheel uploading. (Daniele Trifirò, Jelmer Vernooij) 0.20.39 2022-05-19 0.20.38 2022-05-17 * Disable paramiko tests if paramiko is not available. (Michał Górny) * Set flag to re-enable paramiko server side on gentoo for running paramiko tests. (Michał Górny) * Increase tolerance when comparing time stamps; fixes some spurious test failures on slow CI systems. (Jelmer Vernooij) * Revert removal of caching of full HTTP response. This breaks access to some HTTP servers. (Jelmer Vernooij) 0.20.37 2022-05-16 * Avoid making an extra copy when fetching pack files. (Jelmer Vernooij) * Add ``porcelain.remote_remove``. (Jelmer Vernooij, #923) 0.20.36 2022-05-15 * Add ``walk_untracked`` argument to ``porcelain.status``. (Daniele Trifirò) * Add tests for paramiko SSH Vendor. (Filipp Frizzy) 0.20.35 2022-03-20 * Document the ``path`` attribute for ``Repo``. (Jelmer Vernooij, #854) 0.20.34 2022-03-14 * Add support for multivars in configuration. (Jelmer Vernooij, #718) 0.20.33 2022-03-05 * Fix handling of escaped characters in ignore patterns. (Jelmer Vernooij, #930) * Add ``dulwich.contrib.requests_vendor``. (epopcon) * Ensure git config is available in a linked working tree. (Jesse Cureton, #926) 0.20.32 2022-01-24 * Properly close result repository during test. (Jelmer Vernooij, #928) 0.20.31 2022-01-21 * Add GitClient.clone(). (Jelmer Vernooij, #920) 0.20.30 2022-01-08 0.20.29 2022-01-08 * Support staging submodules. (Jelmer Vernooij) * Drop deprecated Index.iterblobs and iter_fresh_blobs. (Jelmer Vernooij) * Unify clone behaviour of ``Repo.clone`` and ``porcelain.clone``, and add branch parameter for clone. (Peter Rowlands, #851) 0.20.28 2022-01-05 * Fix hook test on Mac OSX / Linux when dulwich is not installed system-wide. (Jelmer Vernooij, #919) * Cope with gecos being unset. (Jelmer Vernooij, #917) 0.20.27 2022-01-04 * Allow adding files to repository in pre-commit hook. (Jelmer Vernooij, #916) * Raise SubmoduleEncountered in ``tree_lookup_path``. (Jelmer Vernooij) 0.20.26 2021-10-29 * Support os.PathLike arguments to Repo.stage(). (Jan Wiśniewski, #907) * Drop support for Python 3.5. (Jelmer Vernooij) * Add ``dulwich.porcelain._reset_file``. (Ded_Secer) * Add ``Repo.unstage``. (Ded_Secer) 0.20.25 2021-08-23 * Fix ``dulwich`` script when installed via setup.py. (Dan Villiom Podlaski Christiansen) * Make default file mask consistent with Git. (Dan Villiom Podlaski Christiansen, #884) 0.20.24 2021-07-18 * config: disregard UTF-8 BOM when reading file. (Dan Villiom Podlaski Christiansen) * Skip lines with spaces only in .gitignore. (Andrey Torsunov, #878) * Add a separate HTTPProxyUnauthorized exception for 407 errors. (Jelmer Vernooij, #822) * Split out a AbstractHTTPGitClient class. (Jelmer Vernooij) 0.20.23 2021-05-24 * Fix installation of GPG during package publishing. (Ruslan Kuprieiev) 0.20.22 2021-05-24 * Prevent removal of refs directory when the last ref is deleted. (Jelmer Vernooij) * Fix filename: MERGE_HEADS => MERGE_HEAD. (Jelmer Vernooij, #861) * For ignored directories, porcelain.add and porcelain.status now only return the path to directory itself in the list of ignored paths. Previously, paths for all files within the directory would also be included in the list. (Peter Rowlands, #853) * Provide depth argument to ``determine_wants``. (Peter Rowlands) * Various tag signature handling improvements. (Daniel Murphy) * Add separate Tag.verify(). (Peter Rowlands) * Add support for version 3 index files. (Jelmer Vernooij) * Fix autocrlf=input handling. (Peter Rowlands, Boris Feld) * Attempt to find C Git global config on Windows. (Peter Rowlands) API CHANGES * The APIs for writing and reading individual index entries have changed to handle lists of (name, entry) tuples rather than tuples. 0.20.21 2021-03-20 * Add basic support for a GcsObjectStore that stores pack files in gcs. (Jelmer Vernooij) * In porcelain.push, default to local active branch. (Jelmer Vernooij, #846) * Support fetching symrefs. (Jelmer Vernooij, #485, #847) * Add aarch64 wheel building. (odidev, Jelmer Vernooij) 0.20.20 2021-03-03 * Implement ``Stash.drop``. (Peter Rowlands) * Support untracked symlinks to paths outside the repository. (Peter Rowlands, #842) 0.20.19 2021-02-11 * Fix handling of negative matches in nested gitignores. (Corentin Hembise, #836) 0.20.18 2021-02-04 * Fix formatting in setup.py. (Jelmer Vernooij) * Add release configuration. (Jelmer Vernooij) 0.20.17 2021-02-04 * credentials: ignore end-of-line character. (Georges Racinet) * Fix failure in get_untracked_paths when the repository contains symlinks. (#830, #793, mattseddon) * docs: Clarify that Git objects are created on `git add`. (Utku Gultopu) 0.20.16 2021-01-16 * Add flag to only attempt to fetch ignored untracked files when specifically requested. (Matt Seddon) 0.20.15 2020-12-23 * Add some functions for parsing and writing bundles. (Jelmer Vernooij) * Add ``no_verify`` flag to ``porcelain.commit`` and ``Repo.do_commit``. (Peter Rowlands) * Remove dependency on external mock module. (Matěj Cepl, #820) 0.20.14 2020-11-26 * Fix some stash functions on Python 3. (Peter Rowlands) * Fix handling of relative paths in alternates files on Python 3. (Georges Racinet) 0.20.13 2020-11-22 * Add py.typed to allow type checking. (David Caro) * Add tests demonstrating a bug in the walker code. (Doug Hellman) 0.20.11 2020-10-30 * Fix wheels build on Linux. (Ruslan Kuprieiev) * Enable wheels build for Python 3.9 on Linux. (Jelmer Vernooij) 0.20.8 2020-10-29 * Build wheels on Mac OS X / Windows for Python 3.9. (Jelmer Vernooij) 0.20.7 2020-10-29 * Check core.repositoryformatversion. (Jelmer Vernooij, #803) * Fix ACK/NACK handling in archive command handling in dulwich.client. (DzmitrySudnik, #805) 0.20.6 2020-08-29 * Add a ``RefsContainer.watch`` interface. (Jelmer Vernooij, #751) * Fix pushing of new branches from porcelain.push. (Jelmer Vernooij, #788) * Honor shallows when pushing from a shallow clone. (Jelmer Vernooij, #794) * Fix porcelain.path_to_tree_path for Python 3.5. (Boris Feld, #777) * Add support for honor proxy environment variables for HTTP. (Aurélien Campéas, #797) 0.20.5 2020-06-22 * Print a clearer exception when setup.py is executed on Python < 3.5. (Jelmer Vernooij, #783) * Send an empty pack to clients if they requested objects, even if they already have those objects. Thanks to Martijn Pieters for the detailed bug report. (Jelmer Vernooij, #781) * porcelain.pull: Don't ask for objects that we already have. (Jelmer Vernooij, #782) * Add LCA implementation. (Kevin Hendricks) * Add functionality for finding the merge base. (Kevin Hendricks) * Check for diverged branches during push. (Jelmer Vernooij, #494) * Check for fast-forward during pull. (Jelmer Vernooij, #666) * Return a SendPackResult object from GitClient.send_pack(). (Jelmer Vernooij) * ``GitClient.send_pack`` now sets the ``ref_status`` attribute on its return value to a dictionary mapping ref names to error messages. Previously, it raised UpdateRefsError if any of the refs failed to update. (Jelmer Vernooij, #780) * Add a ``porcelain.Error`` object that most errors in porcelain derive from. (Jelmer Vernooij) * Fix argument parsing in dulwich command-line app. (Jelmer Vernooij, #784) 0.20.3 2020-06-14 * Add support for remembering remote refs after push/pull. (Jelmer Vernooij, #752) * Support passing tree and output encoding to dulwich.patch.unified_diff. (Jelmer Vernooij, #763) * Fix pushing of new refs over HTTP(S) when there are no new objects to be sent. (Jelmer Vernooij, #739) * Raise new error HTTPUnauthorized when the server sends back a 401. The client can then retry with credentials. (Jelmer Vernooij, #691) * Move the guts of bin/dulwich to dulwich.cli, so it is easier to test or import. (Jelmer Vernooij) * Install dulwich script from entry_points when setuptools is available, making it slightly easier to use on Windows. (Jelmer Vernooij, #540) * Set python_requires>=3.5 in setup.py. (Manuel Jacob) 0.20.2 2020-06-01 * Brown bag release to fix uploads of Windows wheels. 0.20.1 2020-06-01 * Publish binary wheels for: Windows, Linux, Mac OS X. (Jelmer Vernooij, #711, #710, #629) 0.20.0 2020-06-01 * Drop support for Python 2. (Jelmer Vernooij) * Only return files from the loose store that look like git objects. (Nicolas Dandrimont) * Ignore agent= capability if sent by client. (Jelmer Vernooij) * Don't break when encountering block devices. (Jelmer Vernooij) * Decode URL paths in HttpGitClient using utf-8 rather than file system encoding. (Manuel Jacob) * Fix pushing from a shallow clone. (Brecht Machiels, #705) 0.19.16 2020-04-17 * Don't send "deepen None" to server if graph walker supports shallow. (Jelmer Vernooij, #747) * Support tweaking the compression level for loose objects through the "core.looseCompression" and "core.compression" settings. (Jelmer Vernooij) * Support tweaking the compression level for pack objects through the "core.packCompression" and "core.compression" settings. (Jelmer Vernooij) * Add a "dulwich.contrib.diffstat" module. (Kevin Hendricks) 0.19.15 2020-01-26 * Properly handle files that are just executable for the current user. (Jelmer Vernooij, #734) * Fix handling of stored encoding in ``dulwich.porcelain.get_object_by_path`` on Python 3. (Jelmer Vernooij) * Support the include_trees and rename_detector arguments at the same time when diffing trees. (Jelmer Vernooij) 0.19.14 2019-11-30 * Strip superfluous <> around email. (monnerat) * Stop checking for ref validity client-side. Users can still call check_wants manually. (Jelmer Vernooij) * Switch over to Google-style docstrings. (Jelmer Vernooij) * Add a ``dulwich.porcelain.active_branch`` function. (Jelmer Vernooij) * Cleanup new directory if clone fails. (Jelmer Vernooij, #733) * Expand "~" in global exclude path. (Jelmer Vernooij) 0.19.13 2019-08-19 BUG FIXES * Avoid ``PermissionError``, since it is Python3-specific. (Jelmer Vernooij) * Fix regression that added a dependency on C git for the test suite. (Jelmer Vernooij, #720) * Fix compatibility with Python 3.8 - mostly deprecation warnings. (Jelmer Vernooij) 0.19.12 2019-08-13 BUG FIXES * Update directory detection for `get_unstaged_changes` for Python 3. (Boris Feld, #684) * Add a basic ``porcelain.clean``. (Lane Barlow, #398) * Fix output format of ``porcelain.diff`` to match that of C Git. (Boris Feld) * Return a 404 not found error when repository is not found. * Mark ``.git`` directories as hidden on Windows. (Martin Packman, #585) * Implement ``RefsContainer.__iter__`` (Jelmer Vernooij, #717) * Don't trust modes if they can't be modified after a file has been created. (Jelmer Vernooij, #719) 0.19.11 2019-02-07 IMPROVEMENTS * Use fullname from gecos field, if available. (Jelmer Vernooij) * Support ``GIT_AUTHOR_NAME`` / ``GIT_AUTHOR_EMAIL``. (Jelmer Vernooij) * Add support for short ids in parse_commit. (Jelmer Vernooij) * Add support for ``prune`` and ``prune_tags`` arguments to ``porcelain.fetch``. (Jelmer Vernooij, #681) BUG FIXES * Fix handling of race conditions when new packs appear. (Jelmer Vernooij) 0.19.10 2018-01-15 IMPROVEMENTS * Add `dulwich.porcelain.write_tree`. (Jelmer Vernooij) * Support reading ``MERGE_HEADS`` in ``Repo.do_commit``. (Jelmer Vernooij) * Import from ``collections.abc`` rather than ``collections`` where applicable. Required for 3.8 compatibility. (Jelmer Vernooij) * Support plain strings as refspec arguments to ``dulwich.porcelain.push``. (Jelmer Vernooij) * Add support for creating signed tags. (Jelmer Vernooij, #542) BUG FIXES * Handle invalid ref that pretends to be a sub-folder under a valid ref. (KS Chan) 0.19.9 2018-11-17 BUG FIXES * Avoid fetching ghosts in ``Repo.fetch``. (Jelmer Vernooij) * Preserve port and username in parsed HTTP URLs. (Jelmer Vernooij) * Add basic server side implementation of ``git-upload-archive``. (Jelmer Vernooij) 0.19.8 2018-11-06 * Fix encoding when reading README file in setup.py. (egor , #668) 0.19.7 2018-11-05 CHANGES * Drop support for Python 3 < 3.4. This is because pkg_resources (which get used by setuptools and mock) no longer supports 3.3 and earlier. (Jelmer Vernooij) IMPROVEMENTS * Support ``depth`` argument to ``GitClient.fetch_pack`` and support fetching and updating shallow metadata. (Jelmer Vernooij, #240) BUG FIXES * Don't write to stdout and stderr when they are not available (such as is the case for pythonw). (Sylvia van Os, #652) * Fix compatibility with newer versions of git, which expect CONTENT_LENGTH to be set to 0 for empty body requests. (Jelmer Vernooij, #657) * Raise an exception client-side when a caller tries to request SHAs that are not directly referenced the servers' refs. (Jelmer Vernooij) * Raise more informative errors when unable to connect to repository over SSH or subprocess. (Jelmer Vernooij) * Handle commit identity fields with multiple ">" characters. (Nicolas Dandrimont) IMPROVEMENTS * ``dulwich.porcelain.get_object_by_path`` method for easily accessing a path in another tree. (Jelmer Vernooij) * Support the ``i18n.commitEncoding`` setting in config. (Jelmer Vernooij) 0.19.6 2018-08-11 BUG FIXES * Fix support for custom transport arguments in ``dulwich.porcelain.clone``. (Semyon Slepov) * Fix compatibility with Python 3.8 (Jelmer Vernooij, Daniel M. Capella) * Fix some corner cases in ``path_to_tree_path``. (Romain Keramitas) * Support paths as bytestrings in various places in ``dulwich.index`` (Jelmer Vernooij) * Avoid setup.cfg for now, since it seems to break pypi metadata. (Jelmer Vernooij, #658) 0.19.5 2018-07-08 IMPROVEMENTS * Add ``porcelain.describe``. (Sylvia van Os) BUG FIXES * Fix regression in ``dulwich.porcelain.clone`` that prevented cloning of remote repositories. (Jelmer Vernooij, #639) * Don't leave around empty parent directories for removed refs. (Damien Tournoud, #640) 0.19.4 2018-06-24 IMPROVEMENTS * Add ``porcelain.ls_files``. (Jelmer Vernooij) * Add ``Index.items``. (Jelmer Vernooij) BUG FIXES * Avoid unicode characters (e.g. the digraph ij in my surname) in setup.cfg, since setuptools doesn't deal well with them. See https://github.com/pypa/setuptools/issues/1062. (Jelmer Vernooij, #637) 0.19.3 2018-06-17 IMPROVEMENTS * Add really basic `dulwich.porcelain.fsck` implementation. (Jelmer Vernooij) * When the `DULWICH_PDB` environment variable is set, make SIGQUIT open pdb in the 'dulwich' command. * Add `checkout` argument to `Repo.clone`. (Jelmer Vernooij, #503) * Add `Repo.get_shallow` method. (Jelmer Vernooij) * Add basic `dulwich.stash` module. (Jelmer Vernooij) * Support a `prefix` argument to `dulwich.archive.tar_stream`. (Jelmer Vernooij) BUG FIXES * Fix handling of encoding for tags. (Jelmer Vernooij, #608) * Fix tutorial tests on Python 3. (Jelmer Vernooij, #573) * Fix remote refs created by `porcelain.fetch`. (Daniel Andersson, #623) * More robust pack creation on Windows. (Daniel Andersson) * Fix recursive option for `porcelain.ls_tree`. (Romain Keramitas) TESTS * Some improvements to paramiko tests. (Filipp Frizzy) 0.19.2 2018-04-07 BUG FIXES * Fix deprecated Index.iterblobs method. (Jelmer Vernooij) 0.19.1 2018-04-05 IMPROVEMENTS * Add 'dulwich.mailmap' file for reading mailmap files. (Jelmer Vernooij) * Dulwich no longer depends on urllib3[secure]. Instead, "dulwich[https]" can be used to pull in the necessary dependencies for HTTPS support. (Jelmer Vernooij, #616) * Support the `http.sslVerify` and `http.sslCAInfo` configuration options. (Jelmer Vernooij) * Factor out `dulwich.client.parse_rsync_url` function. (Jelmer Vernooij) * Fix repeat HTTP requests using the same smart HTTP client. (Jelmer Vernooij) * New 'client.PLinkSSHVendor' for creating connections using PuTTY's plink.exe. (Adam Bradley, Filipp Frizzy) * Only pass in `key_filename` and `password` to SSHVendor implementations if those parameters are set. (This helps with older SSHVendor implementations) (Jelmer Vernooij) API CHANGES * Index.iterblobs has been renamed to Index.iterobjects. (Jelmer Vernooij) 0.19.0 2018-03-10 BUG FIXES * Make `dulwich.archive` set the gzip header file modification time so that archives created from the same Git tree are always identical. (#577, Jonas Haag) * Allow comment characters (#, ;) within configuration file strings (Daniel Andersson, #579) * Raise exception when passing in invalid author/committer values to Repo.do_commit(). (Jelmer Vernooij, #602) IMPROVEMENTS * Add a fastimport ``extra``. (Jelmer Vernooij) * Start writing reflog entries. (Jelmer Vernooij) * Add ability to use password and keyfile ssh options with SSHVendor. (Filipp Kucheryavy) * Add ``change_type_same`` flag to ``tree_changes``. (Jelmer Vernooij) API CHANGES * ``GitClient.send_pack`` now accepts a ``generate_pack_data`` rather than a ``generate_pack_contents`` function for performance reasons. (Jelmer Vernooij) * Dulwich now uses urllib3 internally for HTTP requests. The `opener` argument to `dulwich.client.HttpGitClient` that took a `urllib2` opener instance has been replaced by a `pool_manager` argument that takes a `urllib3` pool manager instance. (Daniel Andersson) 0.18.6 2017-11-11 BUG FIXES * Fix handling of empty repositories in ``porcelain.clone``. (#570, Jelmer Vernooij) * Raise an error when attempting to add paths that are not under the repository. (Jelmer Vernooij) * Fix error message for missing trailing ]. (Daniel Andersson) * Raise EmptyFileException when corruption (in the form of an empty file) is detected. (Antoine R. Dumont, #582) IMPROVEMENTS * Enforce date field parsing consistency. This also add checks on those date fields for potential overflow. (Antoine R. Dumont, #567) 0.18.5 2017-10-29 BUG FIXES * Fix cwd for hooks. (Fabian Grünbichler) * Fix setting of origin in config when non-standard origin is passed into ``Repo.clone``. (Kenneth Lareau, #565) * Prevent setting SSH arguments from SSH URLs when using SSH through a subprocess. Note that Dulwich doesn't support cloning submodules. (CVE-2017-16228) (Jelmer Vernooij) IMPROVEMENTS * Silently ignored directories in ``Repo.stage``. (Jelmer Vernooij, #564) API CHANGES * GitFile now raises ``FileLocked`` when encountering a lock rather than OSError(EEXIST). (Jelmer Vernooij) 0.18.4 2017-10-01 BUG FIXES * Make default User-Agent start with "git/" because GitHub won't response to HTTP smart server requests otherwise (and reply with a 404). (Jelmer vernooij, #562) 0.18.3 2017-09-03 BUG FIXES * Read config during porcelain operations that involve remotes. (Jelmer Vernooij, #545) * Fix headers of empty chunks in unified diffs. (Taras Postument, #543) * Properly follow redirects over HTTP. (Jelmer Vernooij, #117) IMPROVEMENTS * Add ``dulwich.porcelain.update_head``. (Jelmer Vernooij, #439) * ``GitClient.fetch_pack`` now returns symrefs. (Jelmer Vernooij, #485) * The server now supports providing symrefs. (Jelmer Vernooij, #485) * Add ``dulwich.object_store.commit_tree_changes`` to incrementally commit changes to a tree structure. (Jelmer Vernooij) * Add basic ``PackBasedObjectStore.repack`` method. (Jelmer Vernooij, Earl Chew, #296, #549, #552) 0.18.2 2017-08-01 TEST FIXES * Use constant timestamp so tests pass in all timezones, not just BST. (Jelmer Vernooij) 0.18.1 2017-07-31 BUG FIXES * Fix syntax error in dulwich.contrib.test_swift_smoke. (Jelmer Vernooij) 0.18.0 2017-07-31 BUG FIXES * Fix remaining tests on Windows. (Jelmer Vernooij, #493) * Fix build of C extensions with Python 3 on Windows. (Jelmer Vernooij) * Pass 'mkdir' argument onto Repo.init_bare in Repo.clone. (Jelmer Vernooij, #504) * In ``dulwich.porcelain.add``, if no files are specified, add from current working directory rather than repository root. (Jelmer Vernooij, #521) * Properly deal with submodules in 'porcelain.status'. (Jelmer Vernooij, #517) * ``dulwich.porcelain.remove`` now actually removes files from disk, not just from the index. (Jelmer Vernooij, #488) * Fix handling of "reset" command with markers and without "from". (Antoine Pietri) * Fix handling of "merge" command with markers. (Antoine Pietri) * Support treeish argument to porcelain.reset(), rather than requiring a ref/commit id. (Jelmer Vernooij) * Handle race condition when mtime doesn't change between writes/reads. (Jelmer Vernooij, #541) * Fix ``dulwich.porcelain.show`` on commits with Python 3. (Jelmer Vernooij, #532) IMPROVEMENTS * Add basic support for reading ignore files in ``dulwich.ignore``. ``dulwich.porcelain.add`` and ``dulwich.porcelain.status`` now honor ignores. (Jelmer Vernooij, Segev Finer, #524, #526) * New ``dulwich.porcelain.check_ignore`` command. (Jelmer Vernooij) * ``dulwich.porcelain.status`` now supports a ``ignored`` argument. (Jelmer Vernooij) DOCUMENTATION * Clarified docstrings for Client.{send_pack,fetch_pack} implementations. (Jelmer Vernooij, #523) 0.17.3 2017-03-20 PLATFORM SUPPORT * List Python 3.3 as supported. (Jelmer Vernooij, #513) BUG FIXES * Fix compatibility with pypy 3. (Jelmer Vernooij) 0.17.2 2017-03-19 BUG FIXES * Add workaround for https://bitbucket.org/pypy/pypy/issues/2499/cpyext-pystring_asstring-doesnt-work, fixing Dulwich when used with C extensions on pypy < 5.6. (Victor Stinner) * Properly quote config values with a '#' character in them. (Jelmer Vernooij, #511) 0.17.1 2017-03-01 IMPROVEMENTS * Add basic 'dulwich pull' command. (Jelmer Vernooij) BUG FIXES * Cope with existing submodules during pull. (Jelmer Vernooij, #505) 0.17.0 2017-03-01 TEST FIXES * Skip test that requires sync to synchronize filesystems if os.sync is not available. (Koen Martens) IMPROVEMENTS * Implement MemoryRepo.{set_description,get_description}. (Jelmer Vernooij) * Raise exception in Repo.stage() when absolute paths are passed in. Allow passing in relative paths to porcelain.add().(Jelmer Vernooij) BUG FIXES * Handle multi-line quoted values in config files. (Jelmer Vernooij, #495) * Allow porcelain.clone of repository without HEAD. (Jelmer Vernooij, #501) * Support passing tag ids to Walker()'s include argument. (Jelmer Vernooij) * Don't strip trailing newlines from extra headers. (Nicolas Dandrimont) * Set bufsize=0 for subprocess interaction with SSH client. Fixes hangs on Python 3. (René Stern, #434) * Don't drop first slash for SSH paths, except for those starting with "~". (Jelmer Vernooij, René Stern, #463) * Properly log off after retrieving just refs. (Jelmer Vernooij) 0.16.3 2016-01-14 TEST FIXES * Remove racy check that relies on clock time changing between writes. (Jelmer Vernooij) IMPROVEMENTS * Add porcelain.remote_add. (Jelmer Vernooij) 0.16.2 2016-01-14 IMPROVEMENTS * Fixed failing test-cases on windows. (Koen Martens) API CHANGES * Repo is now a context manager, so that it can be easily closed using a ``with`` statement. (Søren Løvborg) TEST FIXES * Only run worktree list compat tests against git 2.7.0, when 'git worktree list' was introduced. (Jelmer Vernooij) BUG FIXES * Ignore filemode when building index when core.filemode is false. (Koen Martens) * Initialize core.filemode configuration setting by probing the filesystem for trustable permissions. (Koen Martens) * Fix ``porcelain.reset`` to respect the committish argument. (Koen Martens) * Fix dulwich.porcelain.ls_remote() on Python 3. (#471, Jelmer Vernooij) * Allow both unicode and byte strings for host paths in dulwich.client. (#435, Jelmer Vernooij) * Add remote from porcelain.clone. (#466, Jelmer Vernooij) * Fix unquoting of credentials before passing to urllib2. (#475, Volodymyr Holovko) * Cope with submodules in `build_index_from_tree`. (#477, Jelmer Vernooij) * Handle deleted files in `get_unstaged_changes`. (#483, Doug Hellmann) * Don't overwrite files when they haven't changed in `build_file_from_blob`. (#479, Benoît HERVIER) * Check for existence of index file before opening pack. Fixes a race when new packs are being added. (#482, wme) 0.16.1 2016-12-25 BUG FIXES * Fix python3 compatibility for dulwich.contrib.release_robot. (Jelmer Vernooij) 0.16.0 2016-12-24 IMPROVEMENTS * Add support for worktrees. See `git-worktree(1)` and `gitrepository-layout(5)`. (Laurent Rineau) * Add support for `commondir` file in Git control directories. (Laurent Rineau) * Add support for passwords in HTTP URLs. (Jon Bain, Mika Mäenpää) * Add `release_robot` script to contrib, allowing easy finding of current version based on Git tags. (Mark Mikofski) * Add ``Blob.splitlines`` method. (Jelmer Vernooij) BUG FIXES * Fix handling of ``Commit.tree`` being set to an actual tree object rather than a tree id. (Jelmer Vernooij) * Return remote refs from LocalGitClient.fetch_pack(), consistent with the documentation for that method. (#461, Jelmer Vernooij) * Fix handling of unknown URL schemes in get_transport_and_path. (#465, Jelmer Vernooij) 0.15.0 2016-10-09 BUG FIXES * Allow missing trailing LF when reading service name from HTTP servers. (Jelmer Vernooij, Andrew Shadura, #442) * Fix dulwich.porcelain.pull() on Python3. (Jelmer Vernooij, #451) * Properly pull in tags during dulwich.porcelain.clone. (Jelmer Vernooij, #408) CHANGES * Changed license from "GNU General Public License, version 2.0 or later" to "Apache License, version 2.0 or later or GNU General Public License, version 2.0 or later". (#153) IMPROVEMENTS * Add ``dulwich.porcelain.ls_tree`` implementation. (Jelmer Vernooij) 0.14.1 2016-07-05 BUG FIXES * Fix regression removing untouched refs when pushing over SSH. (Jelmer Vernooij #441) * Skip Python3 tests for SWIFT contrib module, as it has not yet been ported. 0.14.0 2016-07-03 BUG FIXES * Fix ShaFile.id after modification of a copied ShaFile. (Félix Mattrat, Jelmer Vernooij) * Support removing refs from porcelain.push. (Jelmer Vernooij, #437) * Stop magic protocol ref `capabilities^{}` from leaking out to clients. (Jelmer Vernooij, #254) IMPROVEMENTS * Add `dulwich.config.parse_submodules` function. * Add `RefsContainer.follow` method. (#438) 0.13.0 2016-04-24 IMPROVEMENTS * Support `ssh://` URLs in get_transport_and_path_from_url(). (Jelmer Vernooij, #402) * Support missing empty line after headers in Git commits and tags. (Nicolas Dandrimont, #413) * Fix `dulwich.porcelain.status` when used in empty trees. (Jelmer Vernooij, #415) * Return copies of objects in MemoryObjectStore rather than references, making the behaviour more consistent with that of DiskObjectStore. (Félix Mattrat, Jelmer Vernooij) * Fix ``dulwich.web`` on Python3. (#295, Jonas Haag) CHANGES * Drop support for Python 2.6. * Fix python3 client web support. (Jelmer Vernooij) BUG FIXES * Fix hang on Gzip decompression. (Jonas Haag) * Don't rely on working tell() and seek() methods on wsgi.input. (Jonas Haag) * Support fastexport/fastimport functionality on python3 with newer versions of fastimport (>= 0.9.5). (Jelmer Vernooij, Félix Mattrat) 0.12.0 2015-12-13 IMPROVEMENTS * Add a `dulwich.archive` module that can create tarballs. Based on code from Jonas Haag in klaus. * Add a `dulwich.reflog` module for reading and writing reflogs. (Jelmer Vernooij) * Fix handling of ambiguous refs in `parse_ref` to make it match the behaviour described in https://git-scm.com/docs/gitrevisions. (Chris Bunney) * Support Python3 in C modules. (Lele Gaifax) BUG FIXES * Simplify handling of SSH command invocation. Fixes quoting of paths. Thanks, Thomas Liebetraut. (#384) * Fix inconsistent handling of trailing slashes for DictRefsContainer. (#383) * Add hack to support thin packs duing fetch(), albeit while requiring the entire pack file to be loaded into memory. (jsbain) CHANGES * This will be the last release to support Python 2.6. 0.11.2 2015-09-18 IMPROVEMENTS * Add support for agent= capability. (Jelmer Vernooij, #298) * Add support for quiet capability. (Jelmer Vernooij) CHANGES * The ParamikoSSHVendor class has been moved to * dulwich.contrib.paramiko_vendor, as it's currently untested. (Jelmer Vernooij, #364) 0.11.1 2015-09-13 Fix-up release to exclude broken blame.py file. 0.11.0 2015-09-13 IMPROVEMENTS * Extended Python3 support to most of the codebase. (Gary van der Merwe, Jelmer Vernooij) * The `Repo` object has a new `close` method that can be called to close any open resources. (Gary van der Merwe) * Support 'git.bat' in SubprocessGitClient on Windows. (Stefan Zimmermann) * Advertise 'ofs-delta' capability in receive-pack server side capabilities. (Jelmer Vernooij) * Switched `default_local_git_client_cls` to `LocalGitClient`. (Gary van der Merwe) * Add `porcelain.ls_remote` and `GitClient.get_refs`. (Michael Edgar) * Add `Repo.discover` method. (B. M. Corser) * Add `dulwich.objectspec.parse_refspec`. (Jelmer Vernooij) * Add `porcelain.pack_objects` and `porcelain.repack`. (Jelmer Vernooij) BUG FIXES * Fix handling of 'done' in graph walker and implement the 'no-done' capability. (Tommy Yu, #88) * Avoid recursion limit issues resolving deltas. (William Grant, #81) * Allow arguments in local client binary path overrides. (Jelmer Vernooij) * Fix handling of commands with arguments in paramiko SSH client. (Andreas Klöckner, Jelmer Vernooij, #363) * Fix parsing of quoted strings in configs. (Jelmer Vernooij, #305) 0.10.1 2015-03-25 BUG FIXES * Return `ApplyDeltaError` when encountering delta errors in both C extensions and native delta application code. (Jelmer Vernooij, #259) 0.10.0 2015-03-22 BUG FIXES * In dulwich.index.build_index_from_tree, by default refuse to create entries that start with .git/. (Jelmer Vernooij, CVE-2014-9706) * Fix running of testsuite when installed. (Jelmer Vernooij, #223) * Use a block cache in _find_content_rename_candidates(), improving performance. (Mike Williams) * Add support for ``core.protectNTFS`` setting. (Jelmer Vernooij) * Fix TypeError when fetching empty updates. (Hwee Miin Koh) * Resolve delta refs when pulling into a MemoryRepo. (Max Shawabkeh, #256) * Fix handling of tags of non-commits in missing object finder. (Augie Fackler, #211) * Explicitly disable mmap on plan9 where it doesn't work. (Jeff Sickel) IMPROVEMENTS * New public method `Repo.reset_index`. (Jelmer Vernooij) * Prevent duplicate parsing of loose files in objects directory when reading. Thanks to David Keijser for the report. (Jelmer Vernooij, #231) 0.9.9 2015-03-20 SECURITY BUG FIXES * Fix buffer overflow in C implementation of pack apply_delta(). (CVE-2015-0838) Thanks to Ivan Fratric of the Google Security Team for reporting this issue. (Jelmer Vernooij) 0.9.8 2014-11-30 BUG FIXES * Various fixes to improve test suite running on Windows. (Gary van der Merwe) * Limit delta copy length to 64K in v2 pack files. (Robert Brown) * Strip newline from final ACKed SHA while fetching packs. (Michael Edgar) * Remove assignment to PyList_SIZE() that was causing segfaults on pypy. (Jelmer Vernooij, #196) IMPROVEMENTS * Add porcelain 'receive-pack' and 'upload-pack'. (Jelmer Vernooij) * Handle SIGINT signals in bin/dulwich. (Jelmer Vernooij) * Add 'status' support to bin/dulwich. (Jelmer Vernooij) * Add 'branch_create', 'branch_list', 'branch_delete' porcelain. (Jelmer Vernooij) * Add 'fetch' porcelain. (Jelmer Vernooij) * Add 'tag_delete' porcelain. (Jelmer Vernooij) * Add support for serializing/deserializing 'gpgsig' attributes in Commit. (Jelmer Vernooij) CHANGES * dul-web is now available as 'dulwich web-daemon'. (Jelmer Vernooij) * dulwich.porcelain.tag has been renamed to tag_create. dulwich.porcelain.list_tags has been renamed to tag_list. (Jelmer Vernooij) API CHANGES * Restore support for Python 2.6. (Jelmer Vernooij, Gary van der Merwe) 0.9.7 2014-06-08 BUG FIXES * Fix tests dependent on hash ordering. (Michael Edgar) * Support staging symbolic links in Repo.stage. (Robert Brown) * Ensure that all files object are closed when running the test suite. (Gary van der Merwe) * When writing OFS_DELTA pack entries, write correct offset. (Augie Fackler) * Fix handler of larger copy operations in packs. (Augie Fackler) * Various fixes to improve test suite running on Windows. (Gary van der Merwe) * Fix logic for extra adds of identical files in rename detector. (Robert Brown) IMPROVEMENTS * Add porcelain 'status'. (Ryan Faulkner) * Add porcelain 'daemon'. (Jelmer Vernooij) * Add `dulwich.greenthreads` module which provides support for concurrency of some object store operations. (Fabien Boucher) * Various changes to improve compatibility with Python 3. (Gary van der Merwe, Hannu Valtonen, michael-k) * Add OpenStack Swift backed repository implementation in dulwich.contrib. See README.swift for details. (Fabien Boucher) API CHANGES * An optional close function can be passed to the Protocol class. This will be called by its close method. (Gary van der Merwe) * All classes with close methods are now context managers, so that they can be easily closed using a `with` statement. (Gary van der Merwe) * Remove deprecated `num_objects` argument to `write_pack` methods. (Jelmer Vernooij) OTHER CHANGES * The 'dul-daemon' script has been removed. The same functionality is now available as 'dulwich daemon'. (Jelmer Vernooij) 0.9.6 2014-04-23 IMPROVEMENTS * Add support for recursive add in 'git add'. (Ryan Faulkner, Jelmer Vernooij) * Add porcelain 'list_tags'. (Ryan Faulkner) * Add porcelain 'push'. (Ryan Faulkner) * Add porcelain 'pull'. (Ryan Faulkner) * Support 'http.proxy' in HttpGitClient. (Jelmer Vernooij, #1096030) * Support 'http.useragent' in HttpGitClient. (Jelmer Vernooij) * In server, wait for clients to send empty list of wants when talking to empty repository. (Damien Tournoud) * Various changes to improve compatibility with Python 3. (Gary van der Merwe) BUG FIXES * Support unseekable 'wsgi.input' streams. (Jonas Haag) * Raise TypeError when passing unicode() object to Repo.__getitem__. (Jonas Haag) * Fix handling of `reset` command in dulwich.fastexport. (Jelmer Vernooij, #1249029) * In client, don't wait for server to close connection first. Fixes hang when used against GitHub server implementation. (Siddharth Agarwal) * DeltaChainIterator: fix a corner case where an object is inflated as an object already in the repository. (Damien Tournoud, #135) * Stop leaking file handles during pack reload. (Damien Tournoud) * Avoid reopening packs during pack cache reload. (Jelmer Vernooij) API CHANGES * Drop support for Python 2.6. (Jelmer Vernooij) 0.9.5 2014-02-23 IMPROVEMENTS * Add porcelain 'tag'. (Ryan Faulkner) * New module `dulwich.objectspec` for parsing strings referencing objects and commit ranges. (Jelmer Vernooij) * Add shallow branch support. (milki) * Allow passing urllib2 `opener` into HttpGitClient. (Dov Feldstern, #909037) CHANGES * Drop support for Python 2.4 and 2.5. (Jelmer Vernooij) API CHANGES * Remove long deprecated ``Repo.commit``, ``Repo.get_blob``, ``Repo.tree`` and ``Repo.tag``. (Jelmer Vernooij) * Remove long deprecated ``Repo.revision_history`` and ``Repo.ref``. (Jelmer Vernooij) * Remove long deprecated ``Tree.entries``. (Jelmer Vernooij) BUG FIXES * Raise KeyError rather than TypeError when passing in unicode object of length 20 or 40 to Repo.__getitem__. (Jelmer Vernooij) * Use 'rm' rather than 'unlink' in tests, since the latter does not exist on OpenBSD and other platforms. (Dmitrij D. Czarkoff) 0.9.4 2013-11-30 IMPROVEMENTS * Add ssh_kwargs attribute to ParamikoSSHVendor. (milki) * Add Repo.set_description(). (Víðir Valberg Guðmundsson) * Add a basic `dulwich.porcelain` module. (Jelmer Vernooij, Marcin Kuzminski) * Various performance improvements for object access. (Jelmer Vernooij) * New function `get_transport_and_path_from_url`, similar to `get_transport_and_path` but only supports URLs. (Jelmer Vernooij) * Add support for file:// URLs in `get_transport_and_path_from_url`. (Jelmer Vernooij) * Add LocalGitClient implementation. (Jelmer Vernooij) BUG FIXES * Support filesystems with 64bit inode and device numbers. (André Roth) CHANGES * Ref handling has been moved to dulwich.refs. (Jelmer Vernooij) API CHANGES * Remove long deprecated RefsContainer.set_ref(). (Jelmer Vernooij) * Repo.ref() is now deprecated in favour of Repo.refs[]. (Jelmer Vernooij) FEATURES * Add support for graftpoints. (milki) 0.9.3 2013-09-27 BUG FIXES * Fix path for stdint.h in MANIFEST.in. (Jelmer Vernooij) 0.9.2 2013-09-26 BUG FIXES * Include stdint.h in MANIFEST.in (Mark Mikofski) 0.9.1 2013-09-22 BUG FIXES * Support lookups of 40-character refs in BaseRepo.__getitem__. (Chow Loong Jin, Jelmer Vernooij) * Fix fetching packs with side-band-64k capability disabled. (David Keijser, Jelmer Vernooij) * Several fixes in send-pack protocol behaviour - handling of empty pack files and deletes. (milki, #1063087) * Fix capability negotiation when fetching packs over HTTP. (#1072461, William Grant) * Enforce determine_wants returning an empty list rather than None. (Fabien Boucher, Jelmer Vernooij) * In the server, support pushes just removing refs. (Fabien Boucher, Jelmer Vernooij) IMPROVEMENTS * Support passing a single revision to BaseRepo.get_walker() rather than a list of revisions. (Alberto Ruiz) * Add `Repo.get_description` method. (Jelmer Vernooij) * Support thin packs in Pack.iterobjects() and Pack.get_raw(). (William Grant) * Add `MemoryObjectStore.add_pack` and `MemoryObjectStore.add_thin_pack` methods. (David Bennett) * Add paramiko-based SSH vendor. (Aaron O'Mullan) * Support running 'dulwich.server' and 'dulwich.web' using 'python -m'. (Jelmer Vernooij) * Add ObjectStore.close(). (Jelmer Vernooij) * Raise appropriate NotImplementedError when encountering dumb HTTP servers. (Jelmer Vernooij) API CHANGES * SSHVendor.connect_ssh has been renamed to SSHVendor.run_command. (Jelmer Vernooij) * ObjectStore.add_pack() now returns a 3-tuple. The last element will be an abort() method that can be used to cancel the pack operation. (Jelmer Vernooij) 0.9.0 2013-05-31 BUG FIXES * Push efficiency - report missing objects only. (#562676, Artem Tikhomirov) * Use indentation consistent with C Git in config files. (#1031356, Curt Moore, Jelmer Vernooij) * Recognize and skip binary files in diff function. (Takeshi Kanemoto) * Fix handling of relative paths in dulwich.client.get_transport_and_path. (Brian Visel, #1169368) * Preserve ordering of entries in configuration. (Benjamin Pollack) * Support ~ expansion in SSH client paths. (milki, #1083439) * Support relative paths in alternate paths. (milki, Michel Lespinasse, #1175007) * Log all error messages from wsgiref server to the logging module. This makes the test suit quiet again. (Gary van der Merwe) * Support passing None for empty tree in changes_from_tree. (Kevin Watters) * Support fetching empty repository in client. (milki, #1060462) IMPROVEMENTS: * Add optional honor_filemode flag to build_index_from_tree. (Mark Mikofski) * Support core/filemode setting when building trees. (Jelmer Vernooij) * Add chapter on tags in tutorial. (Ryan Faulkner) FEATURES * Add support for mergetags. (milki, #963525) * Add support for posix shell hooks. (milki) 0.8.7 2012-11-27 BUG FIXES * Fix use of alternates in ``DiskObjectStore``.{__contains__,__iter__}. (Dmitriy) * Fix compatibility with Python 2.4. (David Carr) 0.8.6 2012-11-09 API CHANGES * dulwich.__init__ no longer imports client, protocol, repo and server modules. (Jelmer Vernooij) FEATURES * ConfigDict now behaves more like a dictionary. (Adam 'Cezar' Jenkins, issue #58) * HTTPGitApplication now takes an optional `fallback_app` argument. (Jonas Haag, issue #67) * Support for large pack index files. (Jameson Nash) TESTING * Make index entry tests a little bit less strict, to cope with slightly different behaviour on various platforms. (Jelmer Vernooij) * ``setup.py test`` (available when setuptools is installed) now runs all tests, not just the basic unit tests. (Jelmer Vernooij) BUG FIXES * Commit._deserialize now actually deserializes the current state rather than the previous one. (Yifan Zhang, issue #59) * Handle None elements in lists of TreeChange objects. (Alex Holmes) * Support cloning repositories without HEAD set. (D-Key, Jelmer Vernooij, issue #69) * Support ``MemoryRepo.get_config``. (Jelmer Vernooij) * In ``get_transport_and_path``, pass extra keyword arguments on to HttpGitClient. (Jelmer Vernooij) 0.8.5 2012-03-29 BUG FIXES * Avoid use of 'with' in dulwich.index. (Jelmer Vernooij) * Be a little bit strict about OS behaviour in index tests. Should fix the tests on Debian GNU/kFreeBSD. (Jelmer Vernooij) 0.8.4 2012-03-28 BUG FIXES * Options on the same line as sections in config files are now supported. (Jelmer Vernooij, #920553) * Only negotiate capabilities that are also supported by the server. (Rod Cloutier, Risto Kankkunen) * Fix parsing of invalid timezone offsets with two minus signs. (Jason R. Coombs, #697828) * Reset environment variables during tests, to avoid test isolation leaks reading ~/.gitconfig. (Risto Kankkunen) TESTS * $HOME is now explicitly specified for tests that use it to read ``~/.gitconfig``, to prevent test isolation issues. (Jelmer Vernooij, #920330) FEATURES * Additional arguments to get_transport_and_path are now passed on to the constructor of the transport. (Sam Vilain) * The WSGI server now transparently handles when a git client submits data using Content-Encoding: gzip. (David Blewett, Jelmer Vernooij) * Add dulwich.index.build_index_from_tree(). (milki) 0.8.3 2012-01-21 FEATURES * The config parser now supports the git-config file format as described in git-config(1) and can write git config files. (Jelmer Vernooij, #531092, #768687) * ``Repo.do_commit`` will now use the user identity from .git/config or ~/.gitconfig if none was explicitly specified. (Jelmer Vernooij) BUG FIXES * Allow ``determine_wants`` methods to include the zero sha in their return value. (Jelmer Vernooij) 0.8.2 2011-12-18 BUG FIXES * Cope with different zlib buffer sizes in sha1 file parser. (Jelmer Vernooij) * Fix get_transport_and_path for HTTP/HTTPS URLs. (Bruno Renié) * Avoid calling free_objects() on NULL in error cases. (Chris Eberle) * Fix use --bare argument to 'dulwich init'. (Chris Eberle) * Properly abort connections when the determine_wants function raises an exception. (Jelmer Vernooij, #856769) * Tweak xcodebuild hack to deal with more error output. (Jelmer Vernooij, #903840) FEATURES * Add support for retrieving tarballs from remote servers. (Jelmer Vernooij, #379087) * New method ``update_server_info`` which generates data for dumb server access. (Jelmer Vernooij, #731235) 0.8.1 2011-10-31 FEATURES * Repo.do_commit has a new argument 'ref'. * Repo.do_commit has a new argument 'merge_heads'. (Jelmer Vernooij) * New ``Repo.get_walker`` method. (Jelmer Vernooij) * New ``Repo.clone`` method. (Jelmer Vernooij, #725369) * ``GitClient.send_pack`` now supports the 'side-band-64k' capability. (Jelmer Vernooij) * ``HttpGitClient`` which supports the smart server protocol over HTTP. "dumb" access is not yet supported. (Jelmer Vernooij, #373688) * Add basic support for alternates. (Jelmer Vernooij, #810429) CHANGES * unittest2 or python >= 2.7 is now required for the testsuite. testtools is no longer supported. (Jelmer Vernooij, #830713) BUG FIXES * Fix compilation with older versions of MSVC. (Martin gz) * Special case 'refs/stash' as a valid ref. (Jelmer Vernooij, #695577) * Smart protocol clients can now change refs even if they are not uploading new data. (Jelmer Vernooij, #855993) * Don't compile C extensions when running in pypy. (Ronny Pfannschmidt, #881546) * Use different name for strnlen replacement function to avoid clashing with system strnlen. (Jelmer Vernooij, #880362) API CHANGES * ``Repo.revision_history`` is now deprecated in favor of ``Repo.get_walker``. (Jelmer Vernooij) 0.8.0 2011-08-07 FEATURES * New DeltaChainIterator abstract class for quickly iterating all objects in a pack, with implementations for pack indexing and inflation. (Dave Borowitz) * New walk module with a Walker class for customizable commit walking. (Dave Borowitz) * New tree_changes_for_merge function in diff_tree. (Dave Borowitz) * Easy rename detection in RenameDetector even without find_copies_harder. (Dave Borowitz) BUG FIXES * Avoid storing all objects in memory when writing pack. (Jelmer Vernooij, #813268) * Support IPv6 for git:// connections. (Jelmer Vernooij, #801543) * Improve performance of Repo.revision_history(). (Timo Schmid, #535118) * Fix use of SubprocessWrapper on Windows. (Paulo Madeira, #670035) * Fix compilation on newer versions of Mac OS X (Lion and up). (Ryan McKern, #794543) * Prevent raising ValueError for correct refs in RefContainer.__delitem__. * Correctly return a tuple from MemoryObjectStore.get_raw. (Dave Borowitz) * Fix a bug in reading the pack checksum when there are fewer than 20 bytes left in the buffer. (Dave Borowitz) * Support ~ in git:// URL paths. (Jelmer Vernooij, #813555) * Make ShaFile.__eq__ work when other is not a ShaFile. (Dave Borowitz) * ObjectStore.get_graph_walker() now no longer yields the same revision more than once. This has a significant improvement for performance when wide revision graphs are involved. (Jelmer Vernooij, #818168) * Teach ReceivePackHandler how to read empty packs. (Dave Borowitz) * Don't send a pack with duplicates of the same object. (Dave Borowitz) * Teach the server how to serve a clone of an empty repo. (Dave Borowitz) * Correctly advertise capabilities during receive-pack. (Dave Borowitz) * Fix add/add and add/rename conflicts in tree_changes_for_merge. (Dave Borowitz) * Use correct MIME types in web server. (Dave Borowitz) API CHANGES * write_pack no longer takes the num_objects argument and requires an object to be passed in that is iterable (rather than an iterator) and that provides __len__. (Jelmer Vernooij) * write_pack_data has been renamed to write_pack_objects and no longer takes a num_objects argument. (Jelmer Vernooij) * take_msb_bytes, read_zlib_chunks, unpack_objects, and PackStreamReader.read_objects now take an additional argument indicating a crc32 to compute. (Dave Borowitz) * PackObjectIterator was removed; its functionality is still exposed by PackData.iterobjects. (Dave Borowitz) * Add a sha arg to write_pack_object to incrementally compute a SHA. (Dave Borowitz) * Include offset in PackStreamReader results. (Dave Borowitz) * Move PackStreamReader from server to pack. (Dave Borowitz) * Extract a check_length_and_checksum, compute_file_sha, and pack_object_header pack helper functions. (Dave Borowitz) * Extract a compute_file_sha function. (Dave Borowitz) * Remove move_in_thin_pack as a separate method; add_thin_pack now completes the thin pack and moves it in in one step. Remove ThinPackData as well. (Dave Borowitz) * Custom buffer size in read_zlib_chunks. (Dave Borowitz) * New UnpackedObject data class that replaces ad-hoc tuples in the return value of unpack_object and various DeltaChainIterator methods. (Dave Borowitz) * Add a lookup_path convenience method to Tree. (Dave Borowitz) * Optionally create RenameDetectors without passing in tree SHAs. (Dave Borowitz) * Optionally include unchanged entries in RenameDetectors. (Dave Borowitz) * Optionally pass a RenameDetector to tree_changes. (Dave Borowitz) * Optionally pass a request object through to server handlers. (Dave Borowitz) TEST CHANGES * If setuptools is installed, "python setup.py test" will now run the testsuite. (Jelmer Vernooij) * Add a new build_pack test utility for building packs from a simple spec. (Dave Borowitz) * Add a new build_commit_graph test utility for building commits from a simple spec. (Dave Borowitz) 0.7.1 2011-04-12 BUG FIXES * Fix double decref in _diff_tree.c. (Ted Horst, #715528) * Fix the build on Windows. (Pascal Quantin) * Fix get_transport_and_path compatibility with pre-2.6.5 versions of Python. (Max Bowsher, #707438) * BaseObjectStore.determine_wants_all no longer breaks on zero SHAs. (Jelmer Vernooij) * write_tree_diff() now supports submodules. (Jelmer Vernooij) * Fix compilation for XCode 4 and older versions of distutils.sysconfig. (Daniele Sluijters) IMPROVEMENTS * Sphinxified documentation. (Lukasz Balcerzak) * Add Pack.keep.(Marc Brinkmann) API CHANGES * The order of the parameters to Tree.add(name, mode, sha) has changed, and is now consistent with the rest of Dulwich. Existing code will still work but print a DeprecationWarning. (Jelmer Vernooij, #663550) * Tree.entries() is now deprecated in favour of Tree.items() and Tree.iteritems(). (Jelmer Vernooij) 0.7.0 2011-01-21 FEATURES * New `dulwich.diff_tree` module for simple content-based rename detection. (Dave Borowitz) * Add Tree.items(). (Jelmer Vernooij) * Add eof() and unread_pkt_line() methods to Protocol. (Dave Borowitz) * Add write_tree_diff(). (Jelmer Vernooij) * Add `serve_command` function for git server commands as executables. (Jelmer Vernooij) * dulwich.client.get_transport_and_path now supports rsync-style repository URLs. (Dave Borowitz, #568493) BUG FIXES * Correct short-circuiting operation for no-op fetches in the server. (Dave Borowitz) * Support parsing git mbox patches without a version tail, as generated by Mercurial. (Jelmer Vernooij) * Fix dul-receive-pack and dul-upload-pack. (Jelmer Vernooij) * Zero-padded file modes in Tree objects no longer trigger an exception but the check code warns about them. (Augie Fackler, #581064) * Repo.init() now honors the mkdir flag. (#671159) * The ref format is now checked when setting a ref rather than when reading it back. (Dave Borowitz, #653527) * Make sure pack files are closed correctly. (Tay Ray Chuan) DOCUMENTATION * Run the tutorial inside the test suite. (Jelmer Vernooij) * Reorganized and updated the tutorial. (Jelmer Vernooij, Dave Borowitz, #610550, #610540) 0.6.2 2010-10-16 BUG FIXES * HTTP server correctly handles empty CONTENT_LENGTH. (Dave Borowitz) * Don't error when creating GitFiles with the default mode. (Dave Borowitz) * ThinPackData.from_file now works with resolve_ext_ref callback. (Dave Borowitz) * Provide strnlen() on mingw32 which doesn't have it. (Hans Kolek) * Set bare=true in the configuration for bare repositories. (Dirk Neumann) FEATURES * Use slots for core objects to save up on memory. (Jelmer Vernooij) * Web server supports streaming progress/pack output. (Dave Borowitz) * New public function dulwich.pack.write_pack_header. (Dave Borowitz) * Distinguish between missing files and read errors in HTTP server. (Dave Borowitz) * Initial work on support for fastimport using python-fastimport. (Jelmer Vernooij) * New dulwich.pack.MemoryPackIndex class. (Jelmer Vernooij) * Delegate SHA peeling to the object store. (Dave Borowitz) TESTS * Use GitFile when modifying packed-refs in tests. (Dave Borowitz) * New tests in test_web with better coverage and fewer ad-hoc mocks. (Dave Borowitz) * Standardize quote delimiters in test_protocol. (Dave Borowitz) * Fix use when testtools is installed. (Jelmer Vernooij) * Add trivial test for write_pack_header. (Jelmer Vernooij) * Refactor some of dulwich.tests.compat.server_utils. (Dave Borowitz) * Allow overwriting id property of objects in test utils. (Dave Borowitz) * Use real in-memory objects rather than stubs for server tests. (Dave Borowitz) * Clean up MissingObjectFinder. (Dave Borowitz) API CHANGES * ObjectStore.iter_tree_contents now walks contents in depth-first, sorted order. (Dave Borowitz) * ObjectStore.iter_tree_contents can optionally yield tree objects as well. (Dave Borowitz). * Add side-band-64k support to ReceivePackHandler. (Dave Borowitz) * Change server capabilities methods to classmethods. (Dave Borowitz) * Tweak server handler injection. (Dave Borowitz) * PackIndex1 and PackIndex2 now subclass FilePackIndex, which is itself a subclass of PackIndex. (Jelmer Vernooij) DOCUMENTATION * Add docstrings for various functions in dulwich.objects. (Jelmer Vernooij) * Clean up docstrings in dulwich.protocol. (Dave Borowitz) * Explicitly specify allowed protocol commands to ProtocolGraphWalker.read_proto_line. (Dave Borowitz) * Add utility functions to DictRefsContainer. (Dave Borowitz) 0.6.1 2010-07-22 BUG FIXES * Fix memory leak in C implementation of sorted_tree_items. (Dave Borowitz) * Use correct path separators for named repo files. (Dave Borowitz) * python > 2.7 and testtools-based test runners will now also pick up skipped tests correctly. (Jelmer Vernooij) FEATURES * Move named file initialization to BaseRepo. (Dave Borowitz) * Add logging utilities and git/HTTP server logging. (Dave Borowitz) * The GitClient interface has been cleaned up and instances are now reusable. (Augie Fackler) * Allow overriding paths to executables in GitSSHClient. (Ross Light, Jelmer Vernooij, #585204) * Add PackBasedObjectStore.pack_loose_objects(). (Jelmer Vernooij) TESTS * Add tests for sorted_tree_items and C implementation. (Dave Borowitz) * Add a MemoryRepo that stores everything in memory. (Dave Borowitz) * Quiet logging output from web tests. (Dave Borowitz) * More flexible version checking for compat tests. (Dave Borowitz) * Compat tests for servers with and without side-band-64k. (Dave Borowitz) CLEANUP * Clean up file headers. (Dave Borowitz) TESTS * Use GitFile when modifying packed-refs in tests. (Dave Borowitz) API CHANGES * dulwich.pack.write_pack_index_v{1,2} now take a file-like object rather than a filename. (Jelmer Vernooij) * Make dul-daemon/dul-web trivial wrappers around server functionality. (Dave Borowitz) * Move reference WSGI handler to web.py. (Dave Borowitz) * Factor out _report_status in ReceivePackHandler. (Dave Borowitz) * Factor out a function to convert a line to a pkt-line. (Dave Borowitz) 0.6.0 2010-05-22 note: This list is most likely incomplete for 0.6.0. BUG FIXES * Fix ReceivePackHandler to disallow removing refs without delete-refs. (Dave Borowitz) * Deal with capabilities required by the client, even if they can not be disabled in the server. (Dave Borowitz) * Fix trailing newlines in generated patch files. (Jelmer Vernooij) * Implement RefsContainer.__contains__. (Jelmer Vernooij) * Cope with \r in ref files on Windows. ( http://github.com/jelmer/dulwich/issues/#issue/13, Jelmer Vernooij) * Fix GitFile breakage on Windows. (Anatoly Techtonik, #557585) * Support packed ref deletion with no peeled refs. (Augie Fackler) * Fix send pack when there is nothing to fetch. (Augie Fackler) * Fix fetch if no progress function is specified. (Augie Fackler) * Allow double-staging of files that are deleted in the index. (Dave Borowitz) * Fix RefsContainer.add_if_new to support dangling symrefs. (Dave Borowitz) * Non-existent index files in non-bare repositories are now treated as empty. (Dave Borowitz) * Always update ShaFile.id when the contents of the object get changed. (Jelmer Vernooij) * Various Python2.4-compatibility fixes. (Dave Borowitz) * Fix thin pack handling. (Dave Borowitz) FEATURES * Add include-tag capability to server. (Dave Borowitz) * New dulwich.fastexport module that can generate fastexport streams. (Jelmer Vernooij) * Implemented BaseRepo.__contains__. (Jelmer Vernooij) * Add __setitem__ to DictRefsContainer. (Dave Borowitz) * Overall improvements checking Git objects. (Dave Borowitz) * Packs are now verified while they are received. (Dave Borowitz) TESTS * Add framework for testing compatibility with C Git. (Dave Borowitz) * Add various tests for the use of non-bare repositories. (Dave Borowitz) * Cope with diffstat not being available on all platforms. (Tay Ray Chuan, Jelmer Vernooij) * Add make_object and make_commit convenience functions to test utils. (Dave Borowitz) API BREAKAGES * The 'committer' and 'message' arguments to Repo.do_commit() have been swapped. 'committer' is now optional. (Jelmer Vernooij) * Repo.get_blob, Repo.commit, Repo.tag and Repo.tree are now deprecated. (Jelmer Vernooij) * RefsContainer.set_ref() was renamed to RefsContainer.set_symbolic_ref(), for clarity. (Jelmer Vernooij) API CHANGES * The primary serialization APIs in dulwich.objects now work with chunks of strings rather than with full-text strings. (Jelmer Vernooij) 0.5.02010-03-03 BUG FIXES * Support custom fields in commits (readonly). (Jelmer Vernooij) * Improved ref handling. (Dave Borowitz) * Rework server protocol to be smarter and interoperate with cgit client. (Dave Borowitz) * Add a GitFile class that uses the same locking protocol for writes as cgit. (Dave Borowitz) * Cope with forward slashes correctly in the index on Windows. (Jelmer Vernooij, #526793) FEATURES * --pure option to setup.py to allow building/installing without the C extensions. (Hal Wine, Anatoly Techtonik, Jelmer Vernooij, #434326) * Implement Repo.get_config(). (Jelmer Vernooij, Augie Fackler) * HTTP dumb and smart server. (Dave Borowitz) * Add abstract baseclass for Repo that does not require file system operations. (Dave Borowitz) 0.4.1 2010-01-03 FEATURES * Add ObjectStore.iter_tree_contents(). (Jelmer Vernooij) * Add Index.changes_from_tree(). (Jelmer Vernooij) * Add ObjectStore.tree_changes(). (Jelmer Vernooij) * Add functionality for writing patches in dulwich.patch. (Jelmer Vernooij) 0.4.0 2009-10-07 DOCUMENTATION * Added tutorial. API CHANGES * dulwich.object_store.tree_lookup_path will now return the mode and sha of the object found rather than the object itself. BUG FIXES * Use binascii.hexlify / binascii.unhexlify for better performance. * Cope with extra unknown data in index files by ignoring it (for now). * Add proper error message when server unexpectedly hangs up. (#415843) * Correctly write opcode for equal in create_delta. 0.3.3 2009-07-23 FEATURES * Implement ShaFile.__hash__(). * Implement Tree.__len__() BUG FIXES * Check for 'objects' and 'refs' directories when looking for a Git repository. (#380818) 0.3.2 2009-05-20 BUG FIXES * Support the encoding field in Commits. * Some Windows compatibility fixes. * Fixed several issues in commit support. FEATURES * Basic support for handling submodules. 0.3.1 2009-05-13 FEATURES * Implemented Repo.__getitem__, Repo.__setitem__ and Repo.__delitem__ to access content. API CHANGES * Removed Repo.set_ref, Repo.remove_ref, Repo.tags, Repo.get_refs and Repo.heads in favor of Repo.refs, a dictionary-like object for accessing refs. BUG FIXES * Removed import of 'sha' module in objects.py, which was causing deprecation warnings on Python 2.6. 0.3.0 2009-05-10 FEATURES * A new function 'commit_tree' has been added that can commit a tree based on an index. BUG FIXES * The memory usage when generating indexes has been significantly reduced. * A memory leak in the C implementation of parse_tree has been fixed. * The send-pack smart server command now works. (Thanks Scott Chacon) * The handling of short timestamps (less than 10 digits) has been fixed. * The handling of timezones has been fixed. 0.2.1 2009-04-30 BUG FIXES * Fix compatibility with Python2.4. 0.2.0 2009-04-30 FEATURES * Support for activity reporting in smart protocol client. * Optional C extensions for better performance in a couple of places that are performance-critical. 0.1.1 2009-03-13 BUG FIXES * Fixed regression in Repo.find_missing_objects() * Don't fetch ^{} objects from remote hosts, as requesting them causes a hangup. * Always write pack to disk completely before calculating checksum. FEATURES * Allow disabling thin packs when talking to remote hosts. 0.1.0 2009-01-24 * Initial release. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9964476 dulwich-0.22.7/PKG-INFO0000644000175100002000000001045014731042565013735 0ustar00runnerdockerMetadata-Version: 2.1 Name: dulwich Version: 0.22.7 Summary: Python Git Library Author-email: Jelmer Vernooij License: Apachev2 or later or GPLv2 Project-URL: Homepage, https://www.dulwich.io/ Project-URL: Repository, https://www.dulwich.io/code/ Project-URL: GitHub, https://github.com/dulwich/dulwich Project-URL: Bug Tracker, https://github.com/dulwich/dulwich/issues Keywords: vcs,git Classifier: Development Status :: 4 - Beta Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Operating System :: POSIX Classifier: Operating System :: Microsoft :: Windows Classifier: Topic :: Software Development :: Version Control Requires-Python: >=3.9 Description-Content-Type: text/x-rst License-File: COPYING Requires-Dist: urllib3>=1.25 Provides-Extra: fastimport Requires-Dist: fastimport; extra == "fastimport" Provides-Extra: https Requires-Dist: urllib3>=1.24.1; extra == "https" Provides-Extra: pgp Requires-Dist: gpg; extra == "pgp" Provides-Extra: paramiko Requires-Dist: paramiko; extra == "paramiko" Provides-Extra: dev Requires-Dist: ruff==0.8.3; extra == "dev" Requires-Dist: mypy==1.13.0; extra == "dev" Dulwich ======= This is the Dulwich project. It aims to provide an interface to git repos (both local and remote) that doesn't call out to git directly but instead uses pure Python. **Main website**: **License**: Apache License, version 2 or GNU General Public License, version 2 or later. SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later The project is named after the part of London that Mr. and Mrs. Git live in the particular Monty Python sketch. Installation ------------ By default, Dulwich' setup.py will attempt to build and install the optional Rust extensions. The reason for this is that they significantly improve the performance since some low-level operations that are executed often are much slower in CPython. If you don't want to install the Rust bindings, specify the --pure argument to setup.py:: $ python setup.py --pure install or if you are installing from pip:: $ pip install --no-binary dulwich dulwich --config-settings "--build-option=--pure" Note that you can also specify --build-option in a `requirements.txt `_ file, e.g. like this:: dulwich --config-settings "--build-option=--pure" Getting started --------------- Dulwich comes with both a lower-level API and higher-level plumbing ("porcelain"). For example, to use the lower level API to access the commit message of the last commit:: >>> from dulwich.repo import Repo >>> r = Repo('.') >>> r.head() '57fbe010446356833a6ad1600059d80b1e731e15' >>> c = r[r.head()] >>> c >>> c.message 'Add note about encoding.\n' And to print it using porcelain:: >>> from dulwich import porcelain >>> porcelain.log('.', max_entries=1) -------------------------------------------------- commit: 57fbe010446356833a6ad1600059d80b1e731e15 Author: Jelmer Vernooij Date: Sat Apr 29 2017 23:57:34 +0000 Add note about encoding. Further documentation --------------------- The dulwich documentation can be found in docs/ and built by running ``make doc``. It can also be found `on the web `_. Help ---- There is a *#dulwich* IRC channel on the `OFTC `_, and a `dulwich-discuss `_ mailing list. Contributing ------------ For a full list of contributors, see the git logs or `AUTHORS `_. If you'd like to contribute to Dulwich, see the `CONTRIBUTING `_ file and `list of open issues `_. Supported versions of Python ---------------------------- At the moment, Dulwich supports (and is tested on) CPython 3.9 and later and Pypy. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/README.rst0000644000175100002000000000543014731042555014330 0ustar00runnerdockerDulwich ======= This is the Dulwich project. It aims to provide an interface to git repos (both local and remote) that doesn't call out to git directly but instead uses pure Python. **Main website**: **License**: Apache License, version 2 or GNU General Public License, version 2 or later. SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later The project is named after the part of London that Mr. and Mrs. Git live in the particular Monty Python sketch. Installation ------------ By default, Dulwich' setup.py will attempt to build and install the optional Rust extensions. The reason for this is that they significantly improve the performance since some low-level operations that are executed often are much slower in CPython. If you don't want to install the Rust bindings, specify the --pure argument to setup.py:: $ python setup.py --pure install or if you are installing from pip:: $ pip install --no-binary dulwich dulwich --config-settings "--build-option=--pure" Note that you can also specify --build-option in a `requirements.txt `_ file, e.g. like this:: dulwich --config-settings "--build-option=--pure" Getting started --------------- Dulwich comes with both a lower-level API and higher-level plumbing ("porcelain"). For example, to use the lower level API to access the commit message of the last commit:: >>> from dulwich.repo import Repo >>> r = Repo('.') >>> r.head() '57fbe010446356833a6ad1600059d80b1e731e15' >>> c = r[r.head()] >>> c >>> c.message 'Add note about encoding.\n' And to print it using porcelain:: >>> from dulwich import porcelain >>> porcelain.log('.', max_entries=1) -------------------------------------------------- commit: 57fbe010446356833a6ad1600059d80b1e731e15 Author: Jelmer Vernooij Date: Sat Apr 29 2017 23:57:34 +0000 Add note about encoding. Further documentation --------------------- The dulwich documentation can be found in docs/ and built by running ``make doc``. It can also be found `on the web `_. Help ---- There is a *#dulwich* IRC channel on the `OFTC `_, and a `dulwich-discuss `_ mailing list. Contributing ------------ For a full list of contributors, see the git logs or `AUTHORS `_. If you'd like to contribute to Dulwich, see the `CONTRIBUTING `_ file and `list of open issues `_. Supported versions of Python ---------------------------- At the moment, Dulwich supports (and is tested on) CPython 3.9 and later and Pypy. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/TODO0000644000175100002000000000020014731042555013317 0ustar00runnerdocker- 'git annotate' equivalent - reflog handling Performance: - more efficient pack iteration - more efficient delta generation ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9604475 dulwich-0.22.7/bin/0000755000175100002000000000000014731042565013410 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/bin/dul-receive-pack0000755000175100002000000000235514731042555016462 0ustar00runnerdocker#!/usr/bin/python3 -u # dul-receive-pack - git-receive-pack in python # Copyright (C) 2008 John Carr # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # import os import sys from dulwich.porcelain import receive_pack if len(sys.argv) < 2: sys.stderr.write("usage: %s \n" % os.path.basename(sys.argv[0])) sys.exit(1) sys.exit(receive_pack(sys.argv[1])) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/bin/dul-upload-pack0000755000175100002000000000235114731042555016320 0ustar00runnerdocker#!/usr/bin/python3 -u # dul-upload-pack - git-upload-pack in python # Copyright (C) 2008 John Carr # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # import os import sys from dulwich.porcelain import upload_pack if len(sys.argv) < 2: sys.stderr.write("usage: %s \n" % os.path.basename(sys.argv[0])) sys.exit(1) sys.exit(upload_pack(sys.argv[1])) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9444478 dulwich-0.22.7/crates/0000755000175100002000000000000014731042565014121 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9604475 dulwich-0.22.7/crates/diff-tree/0000755000175100002000000000000014731042565015766 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/crates/diff-tree/Cargo.toml0000644000175100002000000000027314731042555017717 0ustar00runnerdocker[package] name = "diff-tree-py" version = { workspace = true } edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] pyo3 = { workspace = true, features = ["extension-module"]} ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9604475 dulwich-0.22.7/crates/diff-tree/src/0000755000175100002000000000000014731042565016555 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/crates/diff-tree/src/lib.rs0000644000175100002000000001436614731042555017702 0ustar00runnerdocker/* * Copyright (C) 2010 Google, Inc. * Copyright (C) 2024 Jelmer Vernooij * * Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU * General Public License as public by the Free Software Foundation; version 2.0 * or (at your option) any later version. You can redistribute it and/or * modify it under the terms of either of these two licenses. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * You should have received a copy of the licenses; if not, see * for a copy of the GNU General Public License * and for a copy of the Apache * License, Version 2.0. */ use pyo3::prelude::*; use pyo3::exceptions::PyTypeError; use pyo3::types::{PyBytes, PyList, PyTuple}; use pyo3::Python; use std::cmp::Ordering; const S_IFMT: u32 = 0o170000; const S_IFDIR: u32 = 0o040000; fn add_hash(get: &Bound, set: &Bound, string: &[u8], py: Python) -> PyResult<()> { let str_obj = PyBytes::new(py, string); let hash_obj = str_obj.hash()?; let value = get.call1((hash_obj,))?; let n = string.len(); set.call1((hash_obj, value.extract::()? + n))?; Ok(()) } #[pyfunction] fn _count_blocks(py: Python, obj: &Bound) -> PyResult { let default_dict_cls = PyModule::import(py, "collections")?.getattr("defaultdict")?; let int_cls = PyModule::import(py, "builtins")?.getattr("int")?; let counts = default_dict_cls.call1((int_cls,))?; let get = counts.getattr("__getitem__")?; let set = counts.getattr("__setitem__")?; let chunks = obj.call_method0("as_raw_chunks")?; if !chunks.is_instance_of::() { return Err(PyTypeError::new_err( "as_raw_chunks() did not return a list", )); } let num_chunks = chunks.extract::>()?.len(); let pym = py.import("dulwich.diff_tree")?; let block_size = pym.getattr("_BLOCK_SIZE")?.extract::()?; let mut block: Vec = Vec::with_capacity(block_size); for i in 0..num_chunks { let chunk = chunks.get_item(i)?; if !chunk.is_instance_of::() { return Err(PyTypeError::new_err("chunk is not a string")); } let chunk_str = chunk.extract::<&[u8]>()?; for c in chunk_str { block.push(*c); if *c == b'\n' || block.len() == block_size { add_hash(&get, &set, &block, py)?; block.clear(); } } } if !block.is_empty() { add_hash(&get, &set, &block, py)?; } Ok(counts.into_pyobject(py).unwrap().into()) } #[pyfunction] fn _is_tree(_py: Python, entry: &Bound) -> PyResult { let mode = entry.getattr("mode")?; if mode.is_none() { Ok(false) } else { let lmode = mode.extract::()?; Ok((lmode & S_IFMT) == S_IFDIR) } } fn tree_entries(path: &[u8], tree: &Bound, py: Python) -> PyResult> { if tree.is_none() { return Ok(Vec::new()); } let dom = py.import("dulwich.objects")?; let tree_entry_cls = dom.getattr("TreeEntry")?; let items = tree .call_method1("iteritems", (true,))? .extract::>()?; let mut result = Vec::new(); for item in items { let (name, mode, sha) = item.extract::<(Vec, u32, PyObject)>(py)?; let mut new_path = Vec::with_capacity(path.len() + name.len() + 1); if !path.is_empty() { new_path.extend_from_slice(path); new_path.push(b'/'); } new_path.extend_from_slice(name.as_slice()); let tree_entry = tree_entry_cls.call1((PyBytes::new(py, &new_path), mode, sha))?; result.push(tree_entry.into_pyobject(py).unwrap().into()); } Ok(result) } fn entry_path_cmp(entry1: &Bound, entry2: &Bound) -> PyResult { let path1_o = entry1.getattr("path")?; let path1 = path1_o.extract::<&[u8]>()?; let path2_o = entry2.getattr("path")?; let path2 = path2_o.extract::<&[u8]>()?; Ok(path1.cmp(path2)) } #[pyfunction] fn _merge_entries( py: Python, path: &[u8], tree1: &Bound, tree2: &Bound, ) -> PyResult { let entries1 = tree_entries(path, tree1, py)?; let entries2 = tree_entries(path, tree2, py)?; let pym = py.import("dulwich.diff_tree")?; let null_entry = pym.getattr("_NULL_ENTRY")?.to_object(py); let mut result = Vec::new(); let mut i1 = 0; let mut i2 = 0; while i1 < entries1.len() && i2 < entries2.len() { let cmp = entry_path_cmp(entries1[i1].bind(py), entries2[i2].bind(py))?; let (e1, e2) = match cmp { Ordering::Equal => (entries1[i1].clone_ref(py), entries2[i2].clone_ref(py)), Ordering::Less => (entries1[i1].clone_ref(py), null_entry.clone_ref(py)), Ordering::Greater => (null_entry.clone_ref(py), entries2[i2].clone_ref(py)), }; let pair = PyTuple::new(py, &[e1, e2]).unwrap(); result.push(pair); match cmp { Ordering::Equal => { i1 += 1; i2 += 1; } Ordering::Less => { i1 += 1; } Ordering::Greater => { i2 += 1; } } } while i1 < entries1.len() { let pair = PyTuple::new(py, &[entries1[i1].clone_ref(py), null_entry.clone_ref(py)]).unwrap(); result.push(pair); i1 += 1; } while i2 < entries2.len() { let pair = PyTuple::new(py, &[null_entry.clone_ref(py), entries2[i2].clone_ref(py)]).unwrap(); result.push(pair); i2 += 1; } Ok(PyList::new(py, &result).unwrap().to_object(py)) } #[pymodule] fn _diff_tree(_py: Python, m: &Bound) -> PyResult<()> { m.add_function(wrap_pyfunction!(_count_blocks, m)?)?; m.add_function(wrap_pyfunction!(_is_tree, m)?)?; m.add_function(wrap_pyfunction!(_merge_entries, m)?)?; Ok(()) } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9604475 dulwich-0.22.7/crates/objects/0000755000175100002000000000000014731042565015552 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/crates/objects/Cargo.toml0000644000175100002000000000030614731042555017500 0ustar00runnerdocker[package] name = "objects-py" version = { workspace = true } edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] pyo3 = { workspace = true, features = ["extension-module"]} memchr = "2" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9604475 dulwich-0.22.7/crates/objects/src/0000755000175100002000000000000014731042565016341 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/crates/objects/src/lib.rs0000644000175100002000000001237114731042555017460 0ustar00runnerdocker/* * Copyright (C) 2009 Jelmer Vernooij * * Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU * General Public License as public by the Free Software Foundation; version 2.0 * or (at your option) any later version. You can redistribute it and/or * modify it under the terms of either of these two licenses. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * You should have received a copy of the licenses; if not, see * for a copy of the GNU General Public License * and for a copy of the Apache * License, Version 2.0. */ use memchr::memchr; use pyo3::exceptions::PyTypeError; use pyo3::import_exception; use pyo3::prelude::*; use pyo3::types::{PyBytes, PyDict}; import_exception!(dulwich.errors, ObjectFormatException); const S_IFDIR: u32 = 0o40000; #[inline] fn bytehex(byte: u8) -> u8 { match byte { 0..=9 => byte + b'0', 10..=15 => byte - 10 + b'a', _ => unreachable!(), } } fn sha_to_pyhex(py: Python, sha: &[u8]) -> PyResult { let mut hexsha = Vec::new(); for c in sha { hexsha.push(bytehex((c & 0xF0) >> 4)); hexsha.push(bytehex(c & 0x0F)); } Ok(PyBytes::new(py, hexsha.as_slice()).into()) } #[pyfunction] #[pyo3(signature = (text, strict=None))] fn parse_tree( py: Python, mut text: &[u8], strict: Option, ) -> PyResult> { let mut entries = Vec::new(); let strict = strict.unwrap_or(false); while !text.is_empty() { let mode_end = memchr(b' ', text) .ok_or_else(|| ObjectFormatException::new_err(("Missing terminator for mode",)))?; let text_str = String::from_utf8_lossy(&text[..mode_end]).to_string(); let mode = u32::from_str_radix(text_str.as_str(), 8) .map_err(|e| ObjectFormatException::new_err((format!("invalid mode: {}", e),)))?; if strict && text[0] == b'0' { return Err(ObjectFormatException::new_err(( "Illegal leading zero on mode", ))); } text = &text[mode_end + 1..]; let namelen = memchr(b'\0', text) .ok_or_else(|| ObjectFormatException::new_err(("Missing trailing \\0",)))?; let name = &text[..namelen]; if namelen + 20 >= text.len() { return Err(ObjectFormatException::new_err(("SHA truncated",))); } text = &text[namelen + 1..]; let sha = &text[..20]; entries.push(( PyBytes::new(py, name).to_object(py), mode, sha_to_pyhex(py, sha)?, )); text = &text[20..]; } Ok(entries) } fn cmp_with_suffix(a: (u32, &[u8]), b: (u32, &[u8])) -> std::cmp::Ordering { let len = std::cmp::min(a.1.len(), b.1.len()); let cmp = a.1[..len].cmp(&b.1[..len]); if cmp != std::cmp::Ordering::Equal { return cmp; } let c1 = a.1.get(len) .map_or_else(|| if a.0 & S_IFDIR != 0 { b'/' } else { 0 }, |&c| c); let c2 = b.1.get(len) .map_or_else(|| if b.0 & S_IFDIR != 0 { b'/' } else { 0 }, |&c| c); c1.cmp(&c2) } /// Iterate over a tree entries dictionary. /// /// # Arguments /// /// name_order: If True, iterate entries in order of their name. If /// False, iterate entries in tree order, that is, treat subtree entries as /// having '/' appended. /// entries: Dictionary mapping names to (mode, sha) tuples /// /// # Returns: Iterator over (name, mode, hexsha) #[pyfunction] fn sorted_tree_items( py: Python, entries: &Bound, name_order: bool, ) -> PyResult> { let mut qsort_entries = entries .iter() .map(|(name, value)| -> PyResult<(Vec, u32, Vec)> { let value = value .extract::<(u32, Vec)>() .map_err(|e| PyTypeError::new_err((format!("invalid type: {}", e),)))?; Ok((name.extract::>().unwrap(), value.0, value.1)) }) .collect::, u32, Vec)>>>()?; if name_order { qsort_entries.sort_by(|a, b| a.0.cmp(&b.0)); } else { qsort_entries.sort_by(|a, b| cmp_with_suffix((a.1, a.0.as_slice()), (b.1, b.0.as_slice()))); } let objectsm = py.import("dulwich.objects")?; let tree_entry_cls = objectsm.getattr("TreeEntry")?; qsort_entries .into_iter() .map(|(name, mode, hexsha)| -> PyResult { Ok(tree_entry_cls .call1(( PyBytes::new(py, name.as_slice()).to_object(py), mode, PyBytes::new(py, hexsha.as_slice()).to_object(py), ))? .to_object(py)) }) .collect::>>() } #[pymodule] fn _objects(_py: Python, m: &Bound) -> PyResult<()> { m.add_function(wrap_pyfunction!(sorted_tree_items, m)?)?; m.add_function(wrap_pyfunction!(parse_tree, m)?)?; Ok(()) } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9604475 dulwich-0.22.7/crates/pack/0000755000175100002000000000000014731042565015037 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/crates/pack/Cargo.toml0000644000175100002000000000030314731042555016762 0ustar00runnerdocker[package] name = "pack-py" version = { workspace = true } edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] pyo3 = { workspace = true, features = ["extension-module"]} memchr = "2" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9604475 dulwich-0.22.7/crates/pack/src/0000755000175100002000000000000014731042565015626 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/crates/pack/src/lib.rs0000644000175100002000000001532514731042555016747 0ustar00runnerdocker/* * Copyright (C) 2009 Jelmer Vernooij * * Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU * General Public License as public by the Free Software Foundation; version 2.0 * or (at your option) any later version. You can redistribute it and/or * modify it under the terms of either of these two licenses. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * You should have received a copy of the licenses; if not, see * for a copy of the GNU General Public License * and for a copy of the Apache * License, Version 2.0. */ use pyo3::exceptions::{PyTypeError, PyValueError}; use pyo3::prelude::*; use pyo3::types::{PyBytes, PyList}; pyo3::import_exception!(dulwich.errors, ApplyDeltaError); fn py_is_sha(sha: &PyObject, py: Python) -> PyResult { // Check if the object is a bytes object if sha.bind(py).is_instance_of::() { // Check if the bytes object has a size of 20 if sha.extract::<&[u8]>(py)?.len() == 20 { Ok(true) } else { Ok(false) } } else { Ok(false) } } #[pyfunction] fn bisect_find_sha( py: Python, start: i32, end: i32, sha: Py, unpack_name: PyObject, ) -> PyResult> { // Convert sha_obj to a byte slice let sha = sha.as_bytes(py); let sha_len = sha.len(); // Check if sha is 20 bytes long if sha_len != 20 { return Err(PyValueError::new_err("Sha is not 20 bytes long")); } // Check if start > end if start > end { return Err(PyValueError::new_err("start > end")); } // Binary search loop let mut start = start; let mut end = end; loop { if start > end { break; } let i = (start + end) / 2; let file_sha = unpack_name.call1(py, (i,))?; if !py_is_sha(&file_sha, py)? { return Err(PyTypeError::new_err("unpack_name returned non-sha object")); } match file_sha.extract::<&[u8]>(py).unwrap().cmp(sha) { std::cmp::Ordering::Less => { start = i + 1; } std::cmp::Ordering::Greater => { end = i - 1; } std::cmp::Ordering::Equal => { return Ok(Some(i)); } } } Ok(None) } fn get_delta_header_size(delta: &[u8], index: &mut usize, length: usize) -> usize { let mut size: usize = 0; let mut i: usize = 0; while *index < length { let cmd = delta[*index]; *index += 1; size |= ((cmd & !0x80) as usize) << i; i += 7; if cmd & 0x80 == 0 { break; } } size } fn py_chunked_as_string<'a>( py: Python<'a>, py_buf: &'a PyObject, ) -> PyResult> { if let Ok(py_list) = py_buf.extract::>(py) { let mut buf = Vec::new(); for chunk in py_list.iter() { if let Ok(chunk) = chunk.extract::<&[u8]>() { buf.extend_from_slice(chunk); } else if let Ok(chunk) = chunk.extract::>() { buf.extend(chunk); } else { return Err(PyTypeError::new_err(format!( "chunk is not a byte string, but a {:?}", chunk.get_type().name() ))); } } Ok(buf.into()) } else if py_buf.extract::>(py).is_ok() { Ok(std::borrow::Cow::Borrowed(py_buf.extract::<&[u8]>(py)?)) } else { Err(PyTypeError::new_err( "buf is not a string or a list of chunks", )) } } #[pyfunction] fn apply_delta(py: Python, py_src_buf: PyObject, py_delta: PyObject) -> PyResult> { let src_buf = py_chunked_as_string(py, &py_src_buf)?; let delta = py_chunked_as_string(py, &py_delta)?; let src_buf_len = src_buf.len(); let delta_len = delta.len(); let mut index = 0; let src_size = get_delta_header_size(delta.as_ref(), &mut index, delta_len); if src_size != src_buf_len { return Err(ApplyDeltaError::new_err(format!( "Unexpected source buffer size: {} vs {}", src_size, src_buf_len ))); } let dest_size = get_delta_header_size(delta.as_ref(), &mut index, delta_len); let mut out = vec![0; dest_size]; let mut outindex = 0; while index < delta_len { let cmd = delta[index]; index += 1; if cmd & 0x80 != 0 { let mut cp_off = 0; let mut cp_size = 0; for i in 0..4 { if cmd & (1 << i) != 0 { let x = delta[index] as usize; index += 1; cp_off |= x << (i * 8); } } for i in 0..3 { if cmd & (1 << (4 + i)) != 0 { let x = delta[index] as usize; index += 1; cp_size |= x << (i * 8); } } if cp_size == 0 { cp_size = 0x10000; } if cp_off + cp_size < cp_size || cp_off + cp_size > src_size || cp_size > dest_size { break; } out[outindex..outindex + cp_size].copy_from_slice(&src_buf[cp_off..cp_off + cp_size]); outindex += cp_size; } else if cmd != 0 { if (cmd as usize) > dest_size { break; } // Raise ApplyDeltaError if there are more bytes to copy than space if outindex + cmd as usize > dest_size { return Err(ApplyDeltaError::new_err("Not enough space to copy")); } out[outindex..outindex + cmd as usize] .copy_from_slice(&delta[index..index + cmd as usize]); outindex += cmd as usize; index += cmd as usize; } else { return Err(ApplyDeltaError::new_err("Invalid opcode 0")); } } if index != delta_len { return Err(ApplyDeltaError::new_err("delta not empty")); } if outindex != dest_size { return Err(ApplyDeltaError::new_err("dest size incorrect")); } Ok(vec![PyBytes::new(py, &out).into()]) } #[pymodule] fn _pack(_py: Python, m: &Bound) -> PyResult<()> { m.add_function(wrap_pyfunction!(bisect_find_sha, m)?)?; m.add_function(wrap_pyfunction!(apply_delta, m)?)?; Ok(()) } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9604475 dulwich-0.22.7/docs/0000755000175100002000000000000014731042565013570 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/Makefile0000644000175100002000000000653514731042555015240 0ustar00runnerdocker# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " pdf to make PDF document" @echo " dirhtml to make HTML files named index.html in directories" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* apidocs: sphinx-apidoc -feM -s txt -o api ../dulwich html: apidocs $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: apidocs $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." pickle: apidocs $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: apidocs $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: apidocs $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: apidocs $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/dulwich.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/dulwich.qhc" latex: apidocs $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." changes: apidocs $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." pdf: $(SPHINXBUILD) -b pdf $(ALLSPHINXOPTS) $(BUILDDIR)/pdf @echo @echo "Build finished. The PDF files are in $(BUILDDIR)/pdf." ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9604475 dulwich-0.22.7/docs/api/0000755000175100002000000000000014731042565014341 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/api/index.txt0000644000175100002000000000024714731042555016213 0ustar00runnerdockerThis is the API documentation for Dulwich. Module reference ---------------- .. toctree:: :maxdepth: 3 modules Indices: * :ref:`modindex` * :ref:`search` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/conf.py0000644000175100002000000001524014731042555015070 0ustar00runnerdocker# # dulwich documentation build configuration file, created by # sphinx-quickstart on Thu Feb 18 23:18:28 2010. # # This file is execfile()d with the current directory set to its containing # dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("..")) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__)))) dulwich = __import__("dulwich") # -- General configuration ---------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.ifconfig", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", ] autoclass_content = "both" # Add any paths that contain templates here, relative to this directory. templates_path = ["templates"] # The suffix of source filenames. source_suffix = ".txt" # The encoding of source files. # source_encoding = 'utf-8' # The master toctree document. master_doc = "index" # General information about the project. project = "dulwich" copyright = "2011-2023 Jelmer Vernooij" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = ".".join(map(str, dulwich.__version__[:2])) # The full version, including alpha/beta/rc tags. release = ".".join(map(str, dulwich.__version__)) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. # unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ["build"] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. # html_theme = 'default' html_theme = "agogo" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["theme"] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_use_modindex = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = "dulwichdoc" # -- Options for LaTeX output ------------------------------------------------ # The paper size ('letter' or 'a4'). # latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). # latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ("index", "dulwich.tex", "dulwich Documentation", "Jelmer Vernooij", "manual"), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # Additional stuff for the LaTeX preamble. # latex_preamble = '' # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_use_modindex = True # Add mappings intersphinx_mapping = { "urllib3": ("http://urllib3.readthedocs.org/en/latest", None), "python": ("http://docs.python.org/3", None), } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/index.txt0000644000175100002000000000064614731042555015445 0ustar00runnerdocker.. _index: ====================================== dulwich - Python implementation of Git ====================================== Overview ======== .. include:: ../README.rst Documentation ============= .. toctree:: :maxdepth: 2 protocol tutorial/index api/index Changelog ========= .. include:: ../NEWS Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/make.bat0000644000175100002000000000630414731042555015177 0ustar00runnerdocker@ECHO OFF REM Command file for Sphinx documentation set SPHINXBUILD=sphinx-build set BUILDDIR=build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. pdf to make PDF document echo. dirhtml to make HTML files named index.html in directories echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\dulwich.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\dulwich.ghc goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "pdf" ( %SPHINXBUILD% -b pdf %ALLSPHINXOPTS% %BUILDDIR%/pdf echo. echo.Build finished. The PDF files are in %BUILDDIR%/pdf. goto end ) :end ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/protocol.txt0000644000175100002000000000434414731042555016176 0ustar00runnerdocker.. _protocol: =================== Git Server Protocol =================== Transport ========= The Git protocol operates over pipes or TCP/IP. When a client connects over TCP/IP, it sends a header that tells the server which program to run and what parameters to use. When invoked over SSH, git will run a program with the parameters as command line arguments. Protocols ========= Basics ------ Git communicates with a server by piping data between a local program and a remote program. A common way of sending a unit of information is a pkt_line. This is a 4 byte size as human encoded hex (i.e. totally underusing the 4 bytes...) that tells you the size of the payload, followed by the payload. The size includes the 4 bytes used by the size itself. 0009ABCD\n Git can also multiplex data using the sideband. As well as 4 bytes size, there would be a 1 byte channel number. This is in binary, so ``1`` will be ``\x01``. Typically Git will piggyback a list of capabilities on the first pkt_line it sends. It will also look for capabilities in the first pkt_like it receives. Git will degrade as much as possible when encountering a server or client with differing capabilities. git-upload-pack --------------- git-upload pack is used by git-ls-remote, git-clone, git-fetch and git-pull. And i'm sure others. Typically a client will connect a local git-fetch-pack to a remote git-upload-pack. Capabilities for this protocol include multi_ack, thin-pack, ofs-delta, sideband and sideband-64k A thin pack can reference objects not in the current pack. The server tells the client what refs it has. The client states which of those SHA1's it would like. It then starts to report which SHA1's it has. The server ACKs these allowing the client to work out when to stop sending SHA1's. This saves a lot of transfer because the client can make decisions like "well if it has this SHA, then it has all its parents so I don't need to care about those". When the client stops sending shas, the server can work out an optimal pack and then send it to the client. git-receive-pack ---------------- git-receive-pack is used by git push. Typically a client connects a local git-send-pack to a remote git-receive-pack. Capabilities include report-status and delete-ref. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/requirements.txt0000644000175100002000000000000014731042555017041 0ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9644475 dulwich-0.22.7/docs/tutorial/0000755000175100002000000000000014731042565015433 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/tutorial/Makefile0000644000175100002000000000023214731042555017067 0ustar00runnerdockerRST2HTML = rst2html TXT=$(shell ls *.txt) ALL: index.html index.html: $(TXT) $(RST2HTML) index.txt index.html clean: rm -f index.html .PHONY: clean ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/tutorial/conclusion.txt0000644000175100002000000000050214731042555020344 0ustar00runnerdocker.. _tutorial-conclusion: Conclusion ========== This tutorial currently only covers a small (but important) part of Dulwich. It still needs to be extended to cover packs, refs, reflogs and network communication. Dulwich is abstracting much of the Git plumbing, so there would be more to see. For now, that's all folks! ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/tutorial/encoding.txt0000644000175100002000000000221414731042555017760 0ustar00runnerdockerEncoding ======== You will notice that all lower-level functions in Dulwich take byte strings rather than unicode strings. This is intentional. Although `C git`_ recommends the use of UTF-8 for encoding, this is not strictly enforced and C git treats filenames as sequences of non-NUL bytes. There are repositories in the wild that use non-UTF-8 encoding for filenames and commit messages. .. _C git: https://github.com/git/git/blob/master/Documentation/i18n.txt The library should be able to read *all* existing git repositories, regardless of what encoding they use. This is the main reason why Dulwich does not convert paths to unicode strings. A further consideration is that converting back and forth to unicode is an extra performance penalty. E.g. if you are just iterating over file contents, there is no need to consider encoded strings. Users of the library may have specific assumptions they can make about the encoding - e.g. they could just decide that all their data is latin-1, or the default Python encoding. Higher level functions, such as the porcelain in dulwich.porcelain, will automatically convert unicode strings to UTF-8 bytestrings. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/tutorial/file-format.txt0000644000175100002000000000603214731042555020401 0ustar00runnerdockerGit File format =============== For a better understanding of Dulwich, we'll start by explaining most of the Git secrets. Open the ".git" folder of any Git-managed repository. You'll find folders like "branches", "hooks"... We're only interested in "objects" here. Open it. You'll mostly see 2 hex-digits folders. Git identifies content by its SHA-1 digest. The 2 hex-digits plus the 38 hex-digits of files inside these folders form the 40 characters (or 20 bytes) id of Git objects you'll manage in Dulwich. We'll first study the three main objects: - The Commit; - The Tree; - The Blob. The Commit ---------- You're used to generate commits using Git. You have set up your name and e-mail, and you know how to see the history using ``git log``. A commit file looks like this:: commit tree parent [parent if several parents from merges] author committer But where are the changes you committed? The commit contains a reference to a tree. The Tree -------- A tree is a collection of file information, the state of a single directory at a given point in time. A tree file looks like this:: tree ... And repeats for every file in the tree. Note that the SHA-1 digest is in binary form here. The file mode is like the octal argument you could give to the ``chmod`` command. Except it is in extended form to tell regular files from directories and other types. We now know how our files are referenced but we haven't found their actual content yet. That's where the reference to a blob comes in. The Blob -------- A blob is simply the content of files you are versioning. A blob file looks like this:: blob If you change a single line, another blob will be generated by Git each time you successfully run ``git add``. This is how Git can fastly checkout any version in time. On the opposite, several identical files with different filenames generate only one blob. That's mostly how renames are so cheap and efficient in Git. Dulwich Objects --------------- Dulwich implements these three objects with an API to easily access the information you need, while abstracting some more secrets Git is using to accelerate operations and reduce space. More About Git formats ---------------------- These three objects make up most of the contents of a Git repository and are used for the history. They can either appear as simple files on disk (one file per object) or in a ``pack`` file, which is a container for a number of these objects. There is also an index of the current state of the working copy in the repository as well as files to track the existing branches and tags. For a more detailed explanation of object formats and SHA-1 digests, see: http://www-cs-students.stanford.edu/~blynn/gitmagic/ch08.html Just note that recent versions of Git compress object files using zlib. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/tutorial/index.txt0000644000175100002000000000027214731042555017303 0ustar00runnerdocker.. _tutorial: ======== Tutorial ======== .. toctree:: :maxdepth: 2 introduction encoding file-format repo object-store remote tag porcelain conclusion ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/tutorial/introduction.txt0000644000175100002000000000125714731042555020721 0ustar00runnerdocker.. _tutorial-introduction: Introduction ============ Like Git itself, Dulwich consists of two main layers; the so-called plumbing and the porcelain. The plumbing is the lower layer and it deals with the Git object database and the nitty gritty internals. The porcelain is roughly what you would expect to be exposed to as a user of the ``git`` command-like tool. Dulwich has a fairly complete plumbing implementation, and a more recently added porcelain implementation. The porcelain code lives in ``dulwich.porcelain``. For the large part, this tutorial introduces you to the internal concepts of Git and the main plumbing parts of Dulwich. The last chapter covers the porcelain. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/tutorial/object-store.txt0000644000175100002000000001414214731042555020575 0ustar00runnerdocker.. _tutorial-object-store: The object store ================ The objects are stored in the ``object store`` of the repository. >>> from dulwich.repo import Repo >>> repo = Repo.init("myrepo", mkdir=True) Initial commit -------------- When you use Git, you generally add or modify content. As our repository is empty for now, we'll start by adding a new file:: >>> from dulwich.objects import Blob >>> blob = Blob.from_string(b"My file content\n") >>> print(blob.id.decode('ascii')) c55063a4d5d37aa1af2b2dad3a70aa34dae54dc6 Of course you could create a blob from an existing file using ``from_file`` instead. As said in the introduction, file content is separated from file name. Let's give this content a name:: >>> from dulwich.objects import Tree >>> tree = Tree() >>> tree.add(b"spam", 0o100644, blob.id) Note that "0o100644" is the octal form for a regular file with common permissions. You can hardcode them or you can use the ``stat`` module. The tree state of our repository still needs to be placed in time. That's the job of the commit:: >>> from dulwich.objects import Commit, parse_timezone >>> from time import time >>> commit = Commit() >>> commit.tree = tree.id >>> author = b"Your Name " >>> commit.author = commit.committer = author >>> commit.commit_time = commit.author_time = int(time()) >>> tz = parse_timezone(b'-0200')[0] >>> commit.commit_timezone = commit.author_timezone = tz >>> commit.encoding = b"UTF-8" >>> commit.message = b"Initial commit" Note that the initial commit has no parents. At this point, the repository is still empty because all operations happen in memory. Let's "commit" it. >>> object_store = repo.object_store >>> object_store.add_object(blob) Now the ".git/objects" folder contains a first SHA-1 file. Let's continue saving the changes:: >>> object_store.add_object(tree) >>> object_store.add_object(commit) Now the physical repository contains three objects but still has no branch. Let's create the master branch like Git would:: >>> repo.refs[b'refs/heads/master'] = commit.id The master branch now has a commit where to start. When we commit to master, we are also moving HEAD, which is Git's currently checked out branch: >>> head = repo.refs[b'HEAD'] >>> head == commit.id True >>> head == repo.refs[b'refs/heads/master'] True How did that work? As it turns out, HEAD is a special kind of ref called a symbolic ref, and it points at master. Most functions on the refs container work transparently with symbolic refs, but we can also take a peek inside HEAD: >>> import sys >>> print(repo.refs.read_ref(b'HEAD').decode(sys.getfilesystemencoding())) ref: refs/heads/master Normally, you won't need to use read_ref. If you want to change what ref HEAD points to, in order to check out another branch, just use set_symbolic_ref. Now our repository is officially tracking a branch named "master" referring to a single commit. Playing again with Git ---------------------- At this point you can come back to the shell, go into the "myrepo" folder and type ``git status`` to let Git confirm that this is a regular repository on branch "master". Git will tell you that the file "spam" is deleted, which is normal because Git is comparing the repository state with the current working copy. And we have absolutely no working copy using Dulwich because we don't need it at all! You can checkout the last state using ``git checkout -f``. The force flag will prevent Git from complaining that there are uncommitted changes in the working copy. The file ``spam`` appears and with no surprise contains the same bytes as the blob:: $ cat spam My file content Changing a File and Committing it --------------------------------- Now we have a first commit, the next one will show a difference. As seen in the introduction, it's about making a path in a tree point to a new blob. The old blob will remain to compute the diff. The tree is altered and the new commit'task is to point to this new version. Let's first build the blob:: >>> from dulwich.objects import Blob >>> spam = Blob.from_string(b"My new file content\n") >>> print(spam.id.decode('ascii')) 16ee2682887a962f854ebd25a61db16ef4efe49f An alternative is to alter the previously constructed blob object:: >>> blob.data = b"My new file content\n" >>> print(blob.id.decode('ascii')) 16ee2682887a962f854ebd25a61db16ef4efe49f In any case, update the blob id known as "spam". You also have the opportunity of changing its mode:: >>> tree[b"spam"] = (0o100644, spam.id) Now let's record the change:: >>> from dulwich.objects import Commit >>> from time import time >>> c2 = Commit() >>> c2.tree = tree.id >>> c2.parents = [commit.id] >>> c2.author = c2.committer = b"John Doe " >>> c2.commit_time = c2.author_time = int(time()) >>> c2.commit_timezone = c2.author_timezone = 0 >>> c2.encoding = b"UTF-8" >>> c2.message = b'Changing "spam"' In this new commit we record the changed tree id, and most important, the previous commit as the parent. Parents are actually a list because a commit may happen to have several parents after merging branches. Let's put the objects in the object store:: >>> repo.object_store.add_object(spam) >>> repo.object_store.add_object(tree) >>> repo.object_store.add_object(c2) You can already ask git to introspect this commit using ``git show`` and the value of ``c2.id`` as an argument. You'll see the difference will the previous blob recorded as "spam". The diff between the previous head and the new one can be printed using write_tree_diff:: >>> from dulwich.patch import write_tree_diff >>> from io import BytesIO >>> out = BytesIO() >>> write_tree_diff(out, repo.object_store, commit.tree, tree.id) >>> import sys; _ = sys.stdout.write(out.getvalue().decode('ascii')) diff --git a/spam b/spam index c55063a..16ee268 100644 --- a/spam +++ b/spam @@ -1 +1 @@ -My file content +My new file content You won't see it using git log because the head is still the previous commit. It's easy to remedy:: >>> repo.refs[b'refs/heads/master'] = c2.id Now all git tools will work as expected. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/tutorial/porcelain.txt0000644000175100002000000000261514731042555020153 0ustar00runnerdockerPorcelain ========= The ``porcelain`` is the higher level interface, built on top of the lower level implementation covered in previous chapters of this tutorial. The ``dulwich.porcelain`` module in Dulwich is aimed to closely resemble the Git command-line API that you are familiar with. Basic concepts -------------- The porcelain operations are implemented as top-level functions in the ``dulwich.porcelain`` module. Most arguments can either be strings or more complex Dulwich objects; e.g. a repository argument will either take a string with a path to the repository or an instance of a ``Repo`` object. Initializing a new repository ----------------------------- >>> from dulwich import porcelain >>> repo = porcelain.init("myrepo") Clone a repository ------------------ >>> porcelain.clone("git://github.com/jelmer/dulwich", "dulwich-clone") Basic authentication works using the ``username`` and ``password`` parameters: >>> porcelain.clone( "https://example.com/a-private-repo.git", "a-private-repo-clone", username="user", password="password") Commit changes -------------- >>> r = porcelain.init("testrepo") >>> open("testrepo/testfile", "w").write("data") >>> porcelain.add(r, "testfile") >>> porcelain.commit(r, b"A sample commit") Push changes ------------ >>> tr = porcelain.init("targetrepo") >>> r = porcelain.push("testrepo", "targetrepo", "master") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/tutorial/remote.txt0000644000175100002000000000624514731042555017475 0ustar00runnerdocker.. _tutorial-remote: Most of the tests in this file require a Dulwich server, so let's start one: >>> from dulwich.repo import Repo >>> from dulwich.server import DictBackend, TCPGitServer >>> import threading >>> repo = Repo.init("remote", mkdir=True) >>> cid = repo.do_commit(b"message", committer=b"Jelmer ") >>> backend = DictBackend({b'/': repo}) >>> dul_server = TCPGitServer(backend, b'localhost', 0) >>> server_thread = threading.Thread(target=dul_server.serve) >>> server_thread.start() >>> server_address, server_port=dul_server.socket.getsockname() Remote repositories =================== The interface for remote Git repositories is different from that for local repositories. The Git smart server protocol provides three basic operations: * upload-pack - provides a pack with objects requested by the client * receive-pack - imports a pack with objects provided by the client * upload-archive - provides a tarball with the contents of a specific revision The smart server protocol can be accessed over either plain TCP (git://), SSH (git+ssh://) or tunneled over HTTP (http://). Dulwich provides support for accessing remote repositories in ``dulwich.client``. To create a new client, you can construct one manually:: >>> from dulwich.client import TCPGitClient >>> client = TCPGitClient(server_address, server_port) Retrieving raw pack files ------------------------- The client object can then be used to retrieve a pack. The ``fetch_pack`` method takes a ``determine_wants`` callback argument, which allows the client to determine which objects it wants to end up with:: >>> def determine_wants(refs, depth=None): ... # retrieve all objects ... return refs.values() Note that the ``depth`` keyword argument will contain an optional requested shallow fetch depth. Another required object is a "graph walker", which is used to determine which objects that the client already has should not be sent again by the server. Here in the tutorial we'll just use a dummy graph walker which claims that the client doesn't have any objects:: >>> class DummyGraphWalker(object): ... def ack(self, sha): pass ... def nak(self): pass ... def next(self): pass ... def __next__(self): pass With the ``determine_wants`` function in place, we can now fetch a pack, which we will write to a ``BytesIO`` object:: >>> from io import BytesIO >>> f = BytesIO() >>> result = client.fetch_pack(b"/", determine_wants, ... DummyGraphWalker(), pack_data=f.write) ``f`` will now contain a full pack file:: >>> print(f.getvalue()[:4].decode('ascii')) PACK Fetching objects into a local repository ---------------------------------------- It is also possible to fetch from a remote repository into a local repository, in which case Dulwich takes care of providing the right graph walker, and importing the received pack file into the local repository:: >>> from dulwich.repo import Repo >>> local = Repo.init("local", mkdir=True) >>> remote_refs = client.fetch(b"/", local) >>> local.close() Let's shut down the server now that all tests have been run:: >>> dul_server.shutdown() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/tutorial/repo.txt0000644000175100002000000000571414731042555017147 0ustar00runnerdocker.. _tutorial-repo: The repository ============== After this introduction, let's start directly with code:: >>> from dulwich.repo import Repo The access to a repository is through the Repo object. You can open an existing repository or you can create a new one. There are two types of Git repositories: Regular Repositories -- They are the ones you create using ``git init`` and you daily use. They contain a ``.git`` folder. Bare Repositories -- There is no ".git" folder. The top-level folder contains itself the "branches", "hooks"... folders. These are used for published repositories (mirrors). They do not have a working tree. Creating a repository --------------------- Let's create a folder and turn it into a repository, like ``git init`` would:: >>> from os import mkdir >>> import sys >>> mkdir("myrepo") >>> repo = Repo.init("myrepo") >>> repo You can already look at the structure of the "myrepo/.git" folder, though it is mostly empty for now. Opening an existing repository ------------------------------ To reopen an existing repository, simply pass its path to the constructor of ``Repo``:: >>> repo = Repo("myrepo") >>> repo Opening the index ----------------- The index is used as a staging area. Once you do a commit, the files tracked in the index will be recorded as the contents of the new commit. As mentioned earlier, only non-bare repositories have a working tree, so only non-bare repositories will have an index, too. To open the index, simply call:: >>> index = repo.open_index() >>> print(index.path) myrepo/.git/index Since the repository was just created, the index will be empty:: >>> list(index) [] Staging new files ----------------- The repository allows "staging" files. Only files can be staged - directories aren't tracked explicitly by git. Let's create a simple text file and stage it:: >>> f = open('myrepo/foo', 'wb') >>> _ = f.write(b"monty") >>> f.close() >>> repo.stage([b"foo"]) It will now show up in the index:: >>> print(",".join([f.decode(sys.getfilesystemencoding()) for f in repo.open_index()])) foo Creating new commits -------------------- Now that we have staged a change, we can commit it. The easiest way to do this is by using ``Repo.do_commit``. It is also possible to manipulate the lower-level objects involved in this, but we'll leave that for a separate chapter of the tutorial. To create a simple commit on the current branch, it is only necessary to specify the message. The committer and author will be retrieved from the repository configuration or global configuration if they are not specified:: >>> commit_id = repo.do_commit( ... b"The first commit", committer=b"Jelmer Vernooij ") ``do_commit`` returns the SHA1 of the commit. Since the commit was to the default branch, the repository's head will now be set to that commit:: >>> repo.head() == commit_id True ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/docs/tutorial/tag.txt0000644000175100002000000000334214731042555016750 0ustar00runnerdocker.. _tutorial-tag: Tagging ======= This tutorial will demonstrate how to add a tag to a commit via dulwich. First let's initialize the repository: >>> from dulwich.repo import Repo >>> _repo = Repo("myrepo", mkdir=True) Next we build the commit object and add it to the object store: >>> from dulwich.objects import Blob, Tree, Commit, parse_timezone >>> permissions = 0100644 >>> author = "John Smith" >>> blob = Blob.from_string("empty") >>> tree = Tree() >>> tree.add(tag, permissions, blob.id) >>> commit = Commit() >>> commit.tree = tree.id >>> commit.author = commit.committer = author >>> commit.commit_time = commit.author_time = int(time()) >>> tz = parse_timezone('-0200')[0] >>> commit.commit_timezone = commit.author_timezone = tz >>> commit.encoding = "UTF-8" >>> commit.message = 'Tagging repo: ' + message Add objects to the repo store instance: >>> object_store = _repo.object_store >>> object_store.add_object(blob) >>> object_store.add_object(tree) >>> object_store.add_object(commit) >>> master_branch = 'master' >>> _repo.refs['refs/heads/' + master_branch] = commit.id Finally, add the tag top the repo: >>> _repo['refs/tags/' + commit] = commit.id Alternatively, we can use the tag object if we'd like to annotate the tag: >>> from dulwich.objects import Blob, Tree, Commit, parse_timezone, Tag >>> tag_message = "Tag Annotation" >>> tag = Tag() >>> tag.tagger = author >>> tag.message = message >>> tag.name = "v0.1" >>> tag.object = (Commit, commit.id) >>> tag.tag_time = commit.author_time >>> tag.tag_timezone = tz >>> object_store.add_object(tag) >>> _repo['refs/tags/' + tag] = tag.id ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9684477 dulwich-0.22.7/dulwich/0000755000175100002000000000000014731042565014277 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/__init__.py0000644000175100002000000000222114731042555016404 0ustar00runnerdocker# __init__.py -- The git module of dulwich # Copyright (C) 2007 James Westby # Copyright (C) 2008 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Python implementation of the Git file formats and protocols.""" __version__ = (0, 22, 7) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/__main__.py0000644000175100002000000000007614731042555016373 0ustar00runnerdockerfrom . import cli if __name__ == "__main__": cli._main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/archive.py0000644000175100002000000001135114731042555016272 0ustar00runnerdocker# archive.py -- Creating an archive from a tarball # Copyright (C) 2015 Jonas Haag # Copyright (C) 2015 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Generates tarballs for Git trees.""" import posixpath import stat import struct import tarfile from contextlib import closing from io import BytesIO from os import SEEK_END class ChunkedBytesIO: """Turn a list of bytestrings into a file-like object. This is similar to creating a `BytesIO` from a concatenation of the bytestring list, but saves memory by NOT creating one giant bytestring first:: BytesIO(b''.join(list_of_bytestrings)) =~= ChunkedBytesIO( list_of_bytestrings) """ def __init__(self, contents) -> None: self.contents = contents self.pos = (0, 0) def read(self, maxbytes=None): if maxbytes < 0: maxbytes = float("inf") buf = [] chunk, cursor = self.pos while chunk < len(self.contents): if maxbytes < len(self.contents[chunk]) - cursor: buf.append(self.contents[chunk][cursor : cursor + maxbytes]) cursor += maxbytes self.pos = (chunk, cursor) break else: buf.append(self.contents[chunk][cursor:]) maxbytes -= len(self.contents[chunk]) - cursor chunk += 1 cursor = 0 self.pos = (chunk, cursor) return b"".join(buf) def tar_stream(store, tree, mtime, prefix=b"", format=""): """Generate a tar stream for the contents of a Git tree. Returns a generator that lazily assembles a .tar.gz archive, yielding it in pieces (bytestrings). To obtain the complete .tar.gz binary file, simply concatenate these chunks. Args: store: Object store to retrieve objects from tree: Tree object for the tree root mtime: UNIX timestamp that is assigned as the modification time for all files, and the gzip header modification time if format='gz' format: Optional compression format for tarball Returns: Bytestrings """ buf = BytesIO() with closing(tarfile.open(None, f"w:{format}", buf)) as tar: if format == "gz": # Manually correct the gzip header file modification time so that # archives created from the same Git tree are always identical. # The gzip header file modification time is not currently # accessible from the tarfile API, see: # https://bugs.python.org/issue31526 buf.seek(0) assert buf.read(2) == b"\x1f\x8b", "Invalid gzip header" buf.seek(4) buf.write(struct.pack(" # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Bundle format support.""" from collections.abc import Sequence from typing import Optional, Union from .pack import PackData, write_pack_data class Bundle: version: Optional[int] capabilities: dict[str, str] prerequisites: list[tuple[bytes, str]] references: dict[str, bytes] pack_data: Union[PackData, Sequence[bytes]] def __repr__(self) -> str: return ( f"<{type(self).__name__}(version={self.version}, " f"capabilities={self.capabilities}, " f"prerequisites={self.prerequisites}, " f"references={self.references})>" ) def __eq__(self, other): if not isinstance(other, type(self)): return False if self.version != other.version: return False if self.capabilities != other.capabilities: return False if self.prerequisites != other.prerequisites: return False if self.references != other.references: return False if self.pack_data != other.pack_data: return False return True def _read_bundle(f, version): capabilities = {} prerequisites = [] references = {} line = f.readline() if version >= 3: while line.startswith(b"@"): line = line[1:].rstrip(b"\n") try: key, value = line.split(b"=", 1) except ValueError: key = line value = None else: value = value.decode("utf-8") capabilities[key.decode("utf-8")] = value line = f.readline() while line.startswith(b"-"): (obj_id, comment) = line[1:].rstrip(b"\n").split(b" ", 1) prerequisites.append((obj_id, comment.decode("utf-8"))) line = f.readline() while line != b"\n": (obj_id, ref) = line.rstrip(b"\n").split(b" ", 1) references[ref] = obj_id line = f.readline() pack_data = PackData.from_file(f) ret = Bundle() ret.references = references ret.capabilities = capabilities ret.prerequisites = prerequisites ret.pack_data = pack_data ret.version = version return ret def read_bundle(f): """Read a bundle file.""" firstline = f.readline() if firstline == b"# v2 git bundle\n": return _read_bundle(f, 2) if firstline == b"# v3 git bundle\n": return _read_bundle(f, 3) raise AssertionError(f"unsupported bundle format header: {firstline!r}") def write_bundle(f, bundle) -> None: version = bundle.version if version is None: if bundle.capabilities: version = 3 else: version = 2 if version == 2: f.write(b"# v2 git bundle\n") elif version == 3: f.write(b"# v3 git bundle\n") else: raise AssertionError(f"unknown version {version}") if version == 3: for key, value in bundle.capabilities.items(): f.write(b"@" + key.encode("utf-8")) if value is not None: f.write(b"=" + value.encode("utf-8")) f.write(b"\n") for obj_id, comment in bundle.prerequisites: f.write(b"-%s %s\n" % (obj_id, comment.encode("utf-8"))) for ref, obj_id in bundle.references.items(): f.write(b"%s %s\n" % (obj_id, ref)) f.write(b"\n") write_pack_data( f.write, num_records=len(bundle.pack_data), records=bundle.pack_data.iter_unpacked(), ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/cli.py0000755000175100002000000006177014731042555015435 0ustar00runnerdocker# # dulwich - Simple command-line interface to Dulwich # Copyright (C) 2008-2011 Jelmer Vernooij # vim: expandtab # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Simple command-line interface to Dulwich>. This is a very simple command-line wrapper for Dulwich. It is by no means intended to be a full-blown Git command-line interface but just a way to test Dulwich. """ import argparse import optparse import os import signal import sys from getopt import getopt from typing import TYPE_CHECKING, ClassVar, Optional from dulwich import porcelain from .client import GitProtocolError, get_transport_and_path from .errors import ApplyDeltaError from .index import Index from .objectspec import parse_commit from .pack import Pack, sha_to_hex from .repo import Repo if TYPE_CHECKING: from .objects import ObjectID from .refs import Ref def signal_int(signal, frame) -> None: sys.exit(1) def signal_quit(signal, frame) -> None: import pdb pdb.set_trace() class Command: """A Dulwich subcommand.""" def run(self, args) -> Optional[int]: """Run the command.""" raise NotImplementedError(self.run) class cmd_archive(Command): def run(self, args) -> None: parser = argparse.ArgumentParser() parser.add_argument( "--remote", type=str, help="Retrieve archive from specified remote repo", ) parser.add_argument("committish", type=str, nargs="?") args = parser.parse_args(args) if args.remote: client, path = get_transport_and_path(args.remote) client.archive( path, args.committish, sys.stdout.write, write_error=sys.stderr.write, ) else: porcelain.archive( ".", args.committish, outstream=sys.stdout.buffer, errstream=sys.stderr ) class cmd_add(Command): def run(self, argv) -> None: parser = argparse.ArgumentParser() args = parser.parse_args(argv) porcelain.add(".", paths=args) class cmd_rm(Command): def run(self, argv) -> None: parser = argparse.ArgumentParser() args = parser.parse_args(argv) porcelain.rm(".", paths=args) class cmd_fetch_pack(Command): def run(self, argv) -> None: parser = argparse.ArgumentParser() parser.add_argument("--all", action="store_true") parser.add_argument("location", nargs="?", type=str) parser.add_argument("refs", nargs="*", type=str) args = parser.parse_args(argv) client, path = get_transport_and_path(args.location) r = Repo(".") if args.all: determine_wants = r.object_store.determine_wants_all else: def determine_wants( refs: dict[Ref, ObjectID], depth: Optional[int] = None ) -> list[ObjectID]: return [y.encode("utf-8") for y in args.refs if y not in r.object_store] client.fetch(path, r, determine_wants) class cmd_fetch(Command): def run(self, args) -> None: opts, args = getopt(args, "", []) dict(opts) client, path = get_transport_and_path(args.pop(0)) r = Repo(".") def progress(msg: bytes) -> None: sys.stdout.buffer.write(msg) refs = client.fetch(path, r, progress=progress) print("Remote refs:") for item in refs.items(): print("{} -> {}".format(*item)) class cmd_for_each_ref(Command): def run(self, args) -> None: parser = argparse.ArgumentParser() parser.add_argument("pattern", type=str, nargs="?") args = parser.parse_args(args) for sha, object_type, ref in porcelain.for_each_ref(".", args.pattern): print(f"{sha.decode()} {object_type.decode()}\t{ref.decode()}") class cmd_fsck(Command): def run(self, args) -> None: opts, args = getopt(args, "", []) dict(opts) for obj, msg in porcelain.fsck("."): print(f"{obj}: {msg}") class cmd_log(Command): def run(self, args) -> None: parser = optparse.OptionParser() parser.add_option( "--reverse", dest="reverse", action="store_true", help="Reverse order in which entries are printed", ) parser.add_option( "--name-status", dest="name_status", action="store_true", help="Print name/status for each changed file", ) options, args = parser.parse_args(args) porcelain.log( ".", paths=args, reverse=options.reverse, name_status=options.name_status, outstream=sys.stdout, ) class cmd_diff(Command): def run(self, args) -> None: opts, args = getopt(args, "", []) r = Repo(".") if args == []: commit_id = b"HEAD" else: commit_id = args[0] commit = parse_commit(r, commit_id) parent_commit = r[commit.parents[0]] porcelain.diff_tree( r, parent_commit.tree, commit.tree, outstream=sys.stdout.buffer ) class cmd_dump_pack(Command): def run(self, args) -> None: opts, args = getopt(args, "", []) if args == []: print("Usage: dulwich dump-pack FILENAME") sys.exit(1) basename, _ = os.path.splitext(args[0]) x = Pack(basename) print(f"Object names checksum: {x.name()}") print(f"Checksum: {sha_to_hex(x.get_stored_checksum())}") x.check() print(f"Length: {len(x)}") for name in x: try: print(f"\t{x[name]}") except KeyError as k: print(f"\t{name}: Unable to resolve base {k}") except ApplyDeltaError as e: print(f"\t{name}: Unable to apply delta: {e!r}") class cmd_dump_index(Command): def run(self, args) -> None: opts, args = getopt(args, "", []) if args == []: print("Usage: dulwich dump-index FILENAME") sys.exit(1) filename = args[0] idx = Index(filename) for o in idx: print(o, idx[o]) class cmd_init(Command): def run(self, args) -> None: opts, args = getopt(args, "", ["bare"]) kwopts = dict(opts) if args == []: path = os.getcwd() else: path = args[0] porcelain.init(path, bare=("--bare" in kwopts)) class cmd_clone(Command): def run(self, args) -> None: parser = optparse.OptionParser() parser.add_option( "--bare", dest="bare", help="Whether to create a bare repository.", action="store_true", ) parser.add_option( "--depth", dest="depth", type=int, help="Depth at which to fetch" ) parser.add_option( "-b", "--branch", dest="branch", type=str, help=("Check out branch instead of branch pointed to by remote " "HEAD"), ) parser.add_option( "--refspec", dest="refspec", type=str, help="References to fetch", action="append", ) parser.add_option( "--filter", dest="filter_spec", type=str, help="git-rev-list-style object filter", ) parser.add_option( "--protocol", dest="protocol", type=int, help="Git protocol version to use" ) options, args = parser.parse_args(args) if args == []: print("usage: dulwich clone host:path [PATH]") sys.exit(1) source = args.pop(0) if len(args) > 0: target = args.pop(0) else: target = None try: porcelain.clone( source, target, bare=options.bare, depth=options.depth, branch=options.branch, refspec=options.refspec, filter_spec=options.filter_spec, protocol_version=options.protocol, ) except GitProtocolError as e: print(f"{e}") class cmd_commit(Command): def run(self, args) -> None: opts, args = getopt(args, "", ["message"]) kwopts = dict(opts) porcelain.commit(".", message=kwopts["--message"]) class cmd_commit_tree(Command): def run(self, args) -> None: opts, args = getopt(args, "", ["message"]) if args == []: print("usage: dulwich commit-tree tree") sys.exit(1) kwopts = dict(opts) porcelain.commit_tree(".", tree=args[0], message=kwopts["--message"]) class cmd_update_server_info(Command): def run(self, args) -> None: porcelain.update_server_info(".") class cmd_symbolic_ref(Command): def run(self, args) -> None: opts, args = getopt(args, "", ["ref-name", "force"]) if not args: print("Usage: dulwich symbolic-ref REF_NAME [--force]") sys.exit(1) ref_name = args.pop(0) porcelain.symbolic_ref(".", ref_name=ref_name, force="--force" in args) class cmd_pack_refs(Command): def run(self, argv) -> None: parser = argparse.ArgumentParser() parser.add_argument("--all", action="store_true") # ignored, we never prune parser.add_argument("--no-prune", action="store_true") args = parser.parse_args(argv) porcelain.pack_refs(".", all=args.all) class cmd_show(Command): def run(self, argv) -> None: parser = argparse.ArgumentParser() parser.add_argument("objectish", type=str, nargs="*") args = parser.parse_args(argv) porcelain.show(".", args.objectish or None) class cmd_diff_tree(Command): def run(self, args) -> None: opts, args = getopt(args, "", []) if len(args) < 2: print("Usage: dulwich diff-tree OLD-TREE NEW-TREE") sys.exit(1) porcelain.diff_tree(".", args[0], args[1]) class cmd_rev_list(Command): def run(self, args) -> None: opts, args = getopt(args, "", []) if len(args) < 1: print("Usage: dulwich rev-list COMMITID...") sys.exit(1) porcelain.rev_list(".", args) class cmd_tag(Command): def run(self, args) -> None: parser = optparse.OptionParser() parser.add_option( "-a", "--annotated", help="Create an annotated tag.", action="store_true", ) parser.add_option( "-s", "--sign", help="Sign the annotated tag.", action="store_true" ) options, args = parser.parse_args(args) porcelain.tag_create( ".", args[0], annotated=options.annotated, sign=options.sign ) class cmd_repack(Command): def run(self, args) -> None: opts, args = getopt(args, "", []) dict(opts) porcelain.repack(".") class cmd_reset(Command): def run(self, args) -> None: opts, args = getopt(args, "", ["hard", "soft", "mixed"]) kwopts = dict(opts) mode = "" if "--hard" in kwopts: mode = "hard" elif "--soft" in kwopts: mode = "soft" elif "--mixed" in kwopts: mode = "mixed" porcelain.reset(".", mode=mode) class cmd_daemon(Command): def run(self, args) -> None: from dulwich import log_utils from .protocol import TCP_GIT_PORT parser = optparse.OptionParser() parser.add_option( "-l", "--listen_address", dest="listen_address", default="localhost", help="Binding IP address.", ) parser.add_option( "-p", "--port", dest="port", type=int, default=TCP_GIT_PORT, help="Binding TCP port.", ) options, args = parser.parse_args(args) log_utils.default_logging_config() if len(args) >= 1: gitdir = args[0] else: gitdir = "." porcelain.daemon(gitdir, address=options.listen_address, port=options.port) class cmd_web_daemon(Command): def run(self, args) -> None: from dulwich import log_utils parser = optparse.OptionParser() parser.add_option( "-l", "--listen_address", dest="listen_address", default="", help="Binding IP address.", ) parser.add_option( "-p", "--port", dest="port", type=int, default=8000, help="Binding TCP port.", ) options, args = parser.parse_args(args) log_utils.default_logging_config() if len(args) >= 1: gitdir = args[0] else: gitdir = "." porcelain.web_daemon(gitdir, address=options.listen_address, port=options.port) class cmd_write_tree(Command): def run(self, args) -> None: parser = optparse.OptionParser() options, args = parser.parse_args(args) sys.stdout.write("{}\n".format(porcelain.write_tree("."))) class cmd_receive_pack(Command): def run(self, args) -> None: parser = optparse.OptionParser() options, args = parser.parse_args(args) if len(args) >= 1: gitdir = args[0] else: gitdir = "." porcelain.receive_pack(gitdir) class cmd_upload_pack(Command): def run(self, args) -> None: parser = optparse.OptionParser() options, args = parser.parse_args(args) if len(args) >= 1: gitdir = args[0] else: gitdir = "." porcelain.upload_pack(gitdir) class cmd_status(Command): def run(self, args) -> None: parser = optparse.OptionParser() options, args = parser.parse_args(args) if len(args) >= 1: gitdir = args[0] else: gitdir = "." status = porcelain.status(gitdir) if any(names for (kind, names) in status.staged.items()): sys.stdout.write("Changes to be committed:\n\n") for kind, names in status.staged.items(): for name in names: sys.stdout.write( f"\t{kind}: {name.decode(sys.getfilesystemencoding())}\n" ) sys.stdout.write("\n") if status.unstaged: sys.stdout.write("Changes not staged for commit:\n\n") for name in status.unstaged: sys.stdout.write(f"\t{name.decode(sys.getfilesystemencoding())}\n") sys.stdout.write("\n") if status.untracked: sys.stdout.write("Untracked files:\n\n") for name in status.untracked: sys.stdout.write(f"\t{name}\n") sys.stdout.write("\n") class cmd_ls_remote(Command): def run(self, args) -> None: opts, args = getopt(args, "", []) if len(args) < 1: print("Usage: dulwich ls-remote URL") sys.exit(1) refs = porcelain.ls_remote(args[0]) for ref in sorted(refs): sys.stdout.write(f"{ref}\t{refs[ref]}\n") class cmd_ls_tree(Command): def run(self, args) -> None: parser = optparse.OptionParser() parser.add_option( "-r", "--recursive", action="store_true", help="Recursively list tree contents.", ) parser.add_option("--name-only", action="store_true", help="Only display name.") options, args = parser.parse_args(args) try: treeish = args.pop(0) except IndexError: treeish = None porcelain.ls_tree( ".", treeish, outstream=sys.stdout, recursive=options.recursive, name_only=options.name_only, ) class cmd_pack_objects(Command): def run(self, args) -> None: deltify = False reuse_deltas = True opts, args = getopt(args, "", ["stdout", "deltify", "no-reuse-deltas"]) kwopts = dict(opts) if len(args) < 1 and "--stdout" not in kwopts.keys(): print("Usage: dulwich pack-objects basename") sys.exit(1) object_ids = [line.strip() for line in sys.stdin.readlines()] if "--deltify" in kwopts.keys(): deltify = True if "--no-reuse-deltas" in kwopts.keys(): reuse_deltas = False if "--stdout" in kwopts.keys(): packf = getattr(sys.stdout, "buffer", sys.stdout) idxf = None close = [] else: basename = args[0] packf = open(basename + ".pack", "wb") idxf = open(basename + ".idx", "wb") close = [packf, idxf] porcelain.pack_objects( ".", object_ids, packf, idxf, deltify=deltify, reuse_deltas=reuse_deltas ) for f in close: f.close() class cmd_pull(Command): def run(self, args) -> None: parser = argparse.ArgumentParser() parser.add_argument("from_location", type=str) parser.add_argument("refspec", type=str, nargs="*") parser.add_argument("--filter", type=str, nargs=1) parser.add_argument("--protocol", type=int, nargs=1) args = parser.parse_args(args) porcelain.pull( ".", args.from_location or None, args.refspec or None, filter_spec=args.filter, protocol_version=args.protocol_version or None, ) class cmd_push(Command): def run(self, argv) -> Optional[int]: parser = argparse.ArgumentParser() parser.add_argument("-f", "--force", action="store_true", help="Force") parser.add_argument("to_location", type=str) parser.add_argument("refspec", type=str, nargs="*") args = parser.parse_args(argv) try: porcelain.push( ".", args.to_location, args.refspec or None, force=args.force ) except porcelain.DivergedBranches: sys.stderr.write("Diverged branches; specify --force to override") return 1 return None class cmd_remote_add(Command): def run(self, args) -> None: parser = optparse.OptionParser() options, args = parser.parse_args(args) porcelain.remote_add(".", args[0], args[1]) class SuperCommand(Command): subcommands: ClassVar[dict[str, type[Command]]] = {} default_command: ClassVar[Optional[type[Command]]] = None def run(self, args): if not args and not self.default_command: print( "Supported subcommands: {}".format(", ".join(self.subcommands.keys())) ) return False cmd = args[0] try: cmd_kls = self.subcommands[cmd] except KeyError: print(f"No such subcommand: {args[0]}") return False return cmd_kls().run(args[1:]) class cmd_remote(SuperCommand): subcommands: ClassVar[dict[str, type[Command]]] = { "add": cmd_remote_add, } class cmd_submodule_list(Command): def run(self, argv) -> None: parser = argparse.ArgumentParser() parser.parse_args(argv) for path, sha in porcelain.submodule_list("."): sys.stdout.write(f" {sha} {path}\n") class cmd_submodule_init(Command): def run(self, argv) -> None: parser = argparse.ArgumentParser() parser.parse_args(argv) porcelain.submodule_init(".") class cmd_submodule(SuperCommand): subcommands: ClassVar[dict[str, type[Command]]] = { "init": cmd_submodule_init, } default_command = cmd_submodule_init class cmd_check_ignore(Command): def run(self, args): parser = optparse.OptionParser() options, args = parser.parse_args(args) ret = 1 for path in porcelain.check_ignore(".", args): print(path) ret = 0 return ret class cmd_check_mailmap(Command): def run(self, args) -> None: parser = optparse.OptionParser() options, args = parser.parse_args(args) for arg in args: canonical_identity = porcelain.check_mailmap(".", arg) print(canonical_identity) class cmd_stash_list(Command): def run(self, args) -> None: parser = optparse.OptionParser() options, args = parser.parse_args(args) for i, entry in porcelain.stash_list("."): print("stash@{{{}}}: {}".format(i, entry.message.rstrip("\n"))) class cmd_stash_push(Command): def run(self, args) -> None: parser = optparse.OptionParser() options, args = parser.parse_args(args) porcelain.stash_push(".") print("Saved working directory and index state") class cmd_stash_pop(Command): def run(self, args) -> None: parser = optparse.OptionParser() options, args = parser.parse_args(args) porcelain.stash_pop(".") print("Restrored working directory and index state") class cmd_stash(SuperCommand): subcommands: ClassVar[dict[str, type[Command]]] = { "list": cmd_stash_list, "pop": cmd_stash_pop, "push": cmd_stash_push, } class cmd_ls_files(Command): def run(self, args) -> None: parser = optparse.OptionParser() options, args = parser.parse_args(args) for name in porcelain.ls_files("."): print(name) class cmd_describe(Command): def run(self, args) -> None: parser = optparse.OptionParser() options, args = parser.parse_args(args) print(porcelain.describe(".")) class cmd_help(Command): def run(self, args) -> None: parser = optparse.OptionParser() parser.add_option( "-a", "--all", dest="all", action="store_true", help="List all commands.", ) options, args = parser.parse_args(args) if options.all: print("Available commands:") for cmd in sorted(commands): print(f" {cmd}") else: print( """\ The dulwich command line tool is currently a very basic frontend for the Dulwich python module. For full functionality, please see the API reference. For a list of supported commands, see 'dulwich help -a'. """ ) commands = { "add": cmd_add, "archive": cmd_archive, "check-ignore": cmd_check_ignore, "check-mailmap": cmd_check_mailmap, "clone": cmd_clone, "commit": cmd_commit, "commit-tree": cmd_commit_tree, "describe": cmd_describe, "daemon": cmd_daemon, "diff": cmd_diff, "diff-tree": cmd_diff_tree, "dump-pack": cmd_dump_pack, "dump-index": cmd_dump_index, "fetch-pack": cmd_fetch_pack, "fetch": cmd_fetch, "for-each-ref": cmd_for_each_ref, "fsck": cmd_fsck, "help": cmd_help, "init": cmd_init, "log": cmd_log, "ls-files": cmd_ls_files, "ls-remote": cmd_ls_remote, "ls-tree": cmd_ls_tree, "pack-objects": cmd_pack_objects, "pack-refs": cmd_pack_refs, "pull": cmd_pull, "push": cmd_push, "receive-pack": cmd_receive_pack, "remote": cmd_remote, "repack": cmd_repack, "reset": cmd_reset, "rev-list": cmd_rev_list, "rm": cmd_rm, "show": cmd_show, "stash": cmd_stash, "status": cmd_status, "symbolic-ref": cmd_symbolic_ref, "submodule": cmd_submodule, "tag": cmd_tag, "update-server-info": cmd_update_server_info, "upload-pack": cmd_upload_pack, "web-daemon": cmd_web_daemon, "write-tree": cmd_write_tree, } def main(argv=None): if argv is None: argv = sys.argv[1:] if len(argv) < 1: print("Usage: dulwich <{}> [OPTIONS...]".format("|".join(commands.keys()))) return 1 cmd = argv[0] try: cmd_kls = commands[cmd] except KeyError: print(f"No such subcommand: {cmd}") return 1 # TODO(jelmer): Return non-0 on errors return cmd_kls().run(argv[1:]) def _main() -> None: if "DULWICH_PDB" in os.environ and getattr(signal, "SIGQUIT", None): signal.signal(signal.SIGQUIT, signal_quit) # type: ignore signal.signal(signal.SIGINT, signal_int) sys.exit(main()) if __name__ == "__main__": _main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/client.py0000644000175100002000000031300014731042555016123 0ustar00runnerdocker# client.py -- Implementation of the client side git protocols # Copyright (C) 2008-2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Client side support for the Git protocol. The Dulwich client supports the following capabilities: * thin-pack * multi_ack_detailed * multi_ack * side-band-64k * ofs-delta * quiet * report-status * delete-refs * shallow Known capabilities that are not supported: * no-progress * include-tag """ import copy import logging import os import select import socket import subprocess import sys from collections.abc import Iterable, Iterator from contextlib import closing from io import BufferedReader, BytesIO from typing import ( IO, TYPE_CHECKING, Callable, ClassVar, Optional, Union, ) from urllib.parse import quote as urlquote from urllib.parse import unquote as urlunquote from urllib.parse import urljoin, urlparse, urlunparse, urlunsplit if TYPE_CHECKING: import urllib3 import dulwich from .config import Config, apply_instead_of, get_xdg_config_home_path from .errors import GitProtocolError, NotGitRepository, SendPackError from .pack import ( PACK_SPOOL_FILE_MAX_SIZE, PackChunkGenerator, UnpackedObject, write_pack_from_container, ) from .protocol import ( _RBUFSIZE, CAPABILITIES_REF, CAPABILITY_AGENT, CAPABILITY_DELETE_REFS, CAPABILITY_FETCH, CAPABILITY_FILTER, CAPABILITY_INCLUDE_TAG, CAPABILITY_MULTI_ACK, CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_OFS_DELTA, CAPABILITY_QUIET, CAPABILITY_REPORT_STATUS, CAPABILITY_SHALLOW, CAPABILITY_SIDE_BAND_64K, CAPABILITY_SYMREF, CAPABILITY_THIN_PACK, COMMAND_DEEPEN, COMMAND_DONE, COMMAND_HAVE, COMMAND_SHALLOW, COMMAND_UNSHALLOW, COMMAND_WANT, DEFAULT_GIT_PROTOCOL_VERSION_FETCH, DEFAULT_GIT_PROTOCOL_VERSION_SEND, GIT_PROTOCOL_VERSIONS, KNOWN_RECEIVE_CAPABILITIES, KNOWN_UPLOAD_CAPABILITIES, SIDE_BAND_CHANNEL_DATA, SIDE_BAND_CHANNEL_FATAL, SIDE_BAND_CHANNEL_PROGRESS, TCP_GIT_PORT, ZERO_SHA, HangupException, PktLineParser, Protocol, agent_string, capability_agent, extract_capabilities, extract_capability_names, filter_ref_prefix, parse_capability, pkt_line, pkt_seq, ) from .refs import ( PEELED_TAG_SUFFIX, Ref, _import_remote_refs, _set_default_branch, _set_head, _set_origin_head, read_info_refs, split_peeled_refs, ) from .repo import Repo # Default ref prefix, used if none is specified. # GitHub defaults to just sending HEAD if no ref-prefix is # specified, so explicitly request all refs to match # behaviour with v1 when no ref-prefix is specified. DEFAULT_REF_PREFIX = [b"HEAD", b"refs/"] ObjectID = bytes logger = logging.getLogger(__name__) class InvalidWants(Exception): """Invalid wants.""" def __init__(self, wants) -> None: Exception.__init__( self, f"requested wants not in server provided refs: {wants!r}" ) class HTTPUnauthorized(Exception): """Raised when authentication fails.""" def __init__(self, www_authenticate, url) -> None: Exception.__init__(self, "No valid credentials provided") self.www_authenticate = www_authenticate self.url = url class HTTPProxyUnauthorized(Exception): """Raised when proxy authentication fails.""" def __init__(self, proxy_authenticate, url) -> None: Exception.__init__(self, "No valid proxy credentials provided") self.proxy_authenticate = proxy_authenticate self.url = url def _fileno_can_read(fileno): """Check if a file descriptor is readable.""" return len(select.select([fileno], [], [], 0)[0]) > 0 def _win32_peek_avail(handle): """Wrapper around PeekNamedPipe to check how many bytes are available.""" from ctypes import byref, windll, wintypes c_avail = wintypes.DWORD() c_message = wintypes.DWORD() success = windll.kernel32.PeekNamedPipe( handle, None, 0, None, byref(c_avail), byref(c_message) ) if not success: raise OSError(wintypes.GetLastError()) return c_avail.value COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K] UPLOAD_CAPABILITIES = [ CAPABILITY_THIN_PACK, CAPABILITY_MULTI_ACK, CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_SHALLOW, *COMMON_CAPABILITIES, ] RECEIVE_CAPABILITIES = [ CAPABILITY_REPORT_STATUS, CAPABILITY_DELETE_REFS, *COMMON_CAPABILITIES, ] class ReportStatusParser: """Handle status as reported by servers with 'report-status' capability.""" def __init__(self) -> None: self._done = False self._pack_status = None self._ref_statuses: list[bytes] = [] def check(self): """Check if there were any errors and, if so, raise exceptions. Raises: SendPackError: Raised when the server could not unpack Returns: iterator over refs """ if self._pack_status not in (b"unpack ok", None): raise SendPackError(self._pack_status) for status in self._ref_statuses: try: status, rest = status.split(b" ", 1) except ValueError: # malformed response, move on to the next one continue if status == b"ng": ref, error = rest.split(b" ", 1) yield ref, error.decode("utf-8") elif status == b"ok": yield rest, None else: raise GitProtocolError(f"invalid ref status {status!r}") def handle_packet(self, pkt) -> None: """Handle a packet. Raises: GitProtocolError: Raised when packets are received after a flush packet. """ if self._done: raise GitProtocolError("received more data after status report") if pkt is None: self._done = True return if self._pack_status is None: self._pack_status = pkt.strip() else: ref_status = pkt.strip() self._ref_statuses.append(ref_status) def negotiate_protocol_version(proto) -> int: pkt = proto.read_pkt_line() if pkt is not None and pkt.strip() == b"version 2": return 2 proto.unread_pkt_line(pkt) return 0 def read_server_capabilities(pkt_seq): server_capabilities = [] for pkt in pkt_seq: server_capabilities.append(pkt) return set(server_capabilities) def read_pkt_refs_v2( pkt_seq, ) -> tuple[dict[bytes, bytes], dict[bytes, bytes], dict[bytes, bytes]]: refs = {} symrefs = {} peeled = {} # Receive refs from server for pkt in pkt_seq: parts = pkt.rstrip(b"\n").split(b" ") sha = parts[0] if sha == b"unborn": sha = None ref = parts[1] for part in parts[2:]: if part.startswith(b"peeled:"): peeled[ref] = part[7:] elif part.startswith(b"symref-target:"): symrefs[ref] = part[14:] else: logging.warning("unknown part in pkt-ref: %s", part) refs[ref] = sha return refs, symrefs, peeled def read_pkt_refs_v1(pkt_seq) -> tuple[dict[bytes, bytes], set[bytes]]: server_capabilities = None refs = {} # Receive refs from server for pkt in pkt_seq: (sha, ref) = pkt.rstrip(b"\n").split(None, 1) if sha == b"ERR": raise GitProtocolError(ref.decode("utf-8", "replace")) if server_capabilities is None: (ref, server_capabilities) = extract_capabilities(ref) refs[ref] = sha if len(refs) == 0: return {}, set() if refs == {CAPABILITIES_REF: ZERO_SHA}: refs = {} assert server_capabilities is not None return refs, set(server_capabilities) class FetchPackResult: """Result of a fetch-pack operation. Attributes: refs: Dictionary with all remote refs symrefs: Dictionary with remote symrefs agent: User agent string """ _FORWARDED_ATTRS: ClassVar[set[str]] = { "clear", "copy", "fromkeys", "get", "items", "keys", "pop", "popitem", "setdefault", "update", "values", "viewitems", "viewkeys", "viewvalues", } def __init__( self, refs, symrefs, agent, new_shallow=None, new_unshallow=None ) -> None: self.refs = refs self.symrefs = symrefs self.agent = agent self.new_shallow = new_shallow self.new_unshallow = new_unshallow def _warn_deprecated(self) -> None: import warnings warnings.warn( "Use FetchPackResult.refs instead.", DeprecationWarning, stacklevel=3, ) def __eq__(self, other): if isinstance(other, dict): self._warn_deprecated() return self.refs == other return ( self.refs == other.refs and self.symrefs == other.symrefs and self.agent == other.agent ) def __contains__(self, name) -> bool: self._warn_deprecated() return name in self.refs def __getitem__(self, name): self._warn_deprecated() return self.refs[name] def __len__(self) -> int: self._warn_deprecated() return len(self.refs) def __iter__(self): self._warn_deprecated() return iter(self.refs) def __getattribute__(self, name): if name in type(self)._FORWARDED_ATTRS: self._warn_deprecated() return getattr(self.refs, name) return super().__getattribute__(name) def __repr__(self) -> str: return f"{self.__class__.__name__}({self.refs!r}, {self.symrefs!r}, {self.agent!r})" class SendPackResult: """Result of a upload-pack operation. Attributes: refs: Dictionary with all remote refs agent: User agent string ref_status: Optional dictionary mapping ref name to error message (if it failed to update), or None if it was updated successfully """ _FORWARDED_ATTRS: ClassVar[set[str]] = { "clear", "copy", "fromkeys", "get", "items", "keys", "pop", "popitem", "setdefault", "update", "values", "viewitems", "viewkeys", "viewvalues", } def __init__(self, refs, agent=None, ref_status=None) -> None: self.refs = refs self.agent = agent self.ref_status = ref_status def _warn_deprecated(self) -> None: import warnings warnings.warn( "Use SendPackResult.refs instead.", DeprecationWarning, stacklevel=3, ) def __eq__(self, other): if isinstance(other, dict): self._warn_deprecated() return self.refs == other return self.refs == other.refs and self.agent == other.agent def __contains__(self, name) -> bool: self._warn_deprecated() return name in self.refs def __getitem__(self, name): self._warn_deprecated() return self.refs[name] def __len__(self) -> int: self._warn_deprecated() return len(self.refs) def __iter__(self): self._warn_deprecated() return iter(self.refs) def __getattribute__(self, name): if name in type(self)._FORWARDED_ATTRS: self._warn_deprecated() return getattr(self.refs, name) return super().__getattribute__(name) def __repr__(self) -> str: return f"{self.__class__.__name__}({self.refs!r}, {self.agent!r})" def _read_shallow_updates(pkt_seq): new_shallow = set() new_unshallow = set() for pkt in pkt_seq: if pkt == b"shallow-info\n": # Git-protocol v2 continue try: cmd, sha = pkt.split(b" ", 1) except ValueError: raise GitProtocolError(f"unknown command {pkt}") if cmd == COMMAND_SHALLOW: new_shallow.add(sha.strip()) elif cmd == COMMAND_UNSHALLOW: new_unshallow.add(sha.strip()) else: raise GitProtocolError(f"unknown command {pkt}") return (new_shallow, new_unshallow) class _v1ReceivePackHeader: def __init__(self, capabilities, old_refs, new_refs) -> None: self.want: list[bytes] = [] self.have: list[bytes] = [] self._it = self._handle_receive_pack_head(capabilities, old_refs, new_refs) self.sent_capabilities = False def __iter__(self): return self._it def _handle_receive_pack_head(self, capabilities, old_refs, new_refs): """Handle the head of a 'git-receive-pack' request. Args: capabilities: List of negotiated capabilities old_refs: Old refs, as received from the server new_refs: Refs to change Returns: (have, want) tuple """ self.have = [x for x in old_refs.values() if not x == ZERO_SHA] for refname in new_refs: if not isinstance(refname, bytes): raise TypeError(f"refname is not a bytestring: {refname!r}") old_sha1 = old_refs.get(refname, ZERO_SHA) if not isinstance(old_sha1, bytes): raise TypeError( f"old sha1 for {refname!r} is not a bytestring: {old_sha1!r}" ) new_sha1 = new_refs.get(refname, ZERO_SHA) if not isinstance(new_sha1, bytes): raise TypeError( f"old sha1 for {refname!r} is not a bytestring {new_sha1!r}" ) if old_sha1 != new_sha1: logger.debug( "Sending updated ref %r: %r -> %r", refname, old_sha1, new_sha1 ) if self.sent_capabilities: yield old_sha1 + b" " + new_sha1 + b" " + refname else: yield ( old_sha1 + b" " + new_sha1 + b" " + refname + b"\0" + b" ".join(sorted(capabilities)) ) self.sent_capabilities = True if new_sha1 not in self.have and new_sha1 != ZERO_SHA: self.want.append(new_sha1) yield None def _read_side_band64k_data(pkt_seq: Iterable[bytes]) -> Iterator[tuple[int, bytes]]: """Read per-channel data. This requires the side-band-64k capability. Args: pkt_seq: Sequence of packets to read """ for pkt in pkt_seq: channel = ord(pkt[:1]) yield channel, pkt[1:] def find_capability(capabilities, key, value): for capability in capabilities: k, v = parse_capability(capability) if k != key: continue if value and value not in v.split(b" "): continue return capability def _handle_upload_pack_head( proto, capabilities, graph_walker, wants, can_read, depth, protocol_version, ): """Handle the head of a 'git-upload-pack' request. Args: proto: Protocol object to read from capabilities: List of negotiated capabilities graph_walker: GraphWalker instance to call .ack() on wants: List of commits to fetch can_read: function that returns a boolean that indicates whether there is extra graph data to read on proto depth: Depth for request protocol_version: Neogiated Git protocol version. """ assert isinstance(wants, list) and isinstance(wants[0], bytes) wantcmd = COMMAND_WANT + b" " + wants[0] if protocol_version is None: protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND if protocol_version != 2: wantcmd += b" " + b" ".join(sorted(capabilities)) wantcmd += b"\n" proto.write_pkt_line(wantcmd) for want in wants[1:]: proto.write_pkt_line(COMMAND_WANT + b" " + want + b"\n") if depth not in (0, None) or getattr(graph_walker, "shallow", None): if protocol_version == 2: if not find_capability(capabilities, CAPABILITY_FETCH, CAPABILITY_SHALLOW): raise GitProtocolError( "server does not support shallow capability required for " "depth" ) elif CAPABILITY_SHALLOW not in capabilities: raise GitProtocolError( "server does not support shallow capability required for " "depth" ) for sha in graph_walker.shallow: proto.write_pkt_line(COMMAND_SHALLOW + b" " + sha + b"\n") if depth is not None: proto.write_pkt_line( COMMAND_DEEPEN + b" " + str(depth).encode("ascii") + b"\n" ) if protocol_version == 2: proto.write_pkt_line(None) if protocol_version != 2: proto.write_pkt_line(None) if depth not in (0, None): if can_read is not None: (new_shallow, new_unshallow) = _read_shallow_updates(proto.read_pkt_seq()) else: new_shallow = new_unshallow = None else: new_shallow = new_unshallow = set() have = next(graph_walker) while have: proto.write_pkt_line(COMMAND_HAVE + b" " + have + b"\n") if can_read is not None and can_read(): pkt = proto.read_pkt_line() parts = pkt.rstrip(b"\n").split(b" ") if parts[0] == b"ACK": graph_walker.ack(parts[1]) if parts[2] in (b"continue", b"common"): pass elif parts[2] == b"ready": break else: raise AssertionError( f"{parts[2]} not in ('continue', 'ready', 'common)" ) have = next(graph_walker) proto.write_pkt_line(COMMAND_DONE + b"\n") if protocol_version == 2: proto.write_pkt_line(None) return (new_shallow, new_unshallow) def _handle_upload_pack_tail( proto, capabilities: set[bytes], graph_walker, pack_data: Callable[[bytes], None], progress: Optional[Callable[[bytes], None]] = None, rbufsize=_RBUFSIZE, protocol_version=0, ) -> None: """Handle the tail of a 'git-upload-pack' request. Args: proto: Protocol object to read from capabilities: List of negotiated capabilities graph_walker: GraphWalker instance to call .ack() on pack_data: Function to call with pack data progress: Optional progress reporting function rbufsize: Read buffer size protocol_version: Neogiated Git protocol version. """ pkt = proto.read_pkt_line() while pkt: parts = pkt.rstrip(b"\n").split(b" ") if protocol_version == 2 and parts[0] != "packfile": break else: if parts[0] == b"ACK": graph_walker.ack(parts[1]) if parts[0] == b"NAK": graph_walker.nak() if len(parts) < 3 or parts[2] not in ( b"ready", b"continue", b"common", ): break pkt = proto.read_pkt_line() if CAPABILITY_SIDE_BAND_64K in capabilities or protocol_version == 2: if progress is None: # Just ignore progress data def progress(x) -> None: pass for chan, data in _read_side_band64k_data(proto.read_pkt_seq()): if chan == SIDE_BAND_CHANNEL_DATA: pack_data(data) elif chan == SIDE_BAND_CHANNEL_PROGRESS: progress(data) else: raise AssertionError(f"Invalid sideband channel {chan}") else: while True: data = proto.read(rbufsize) if data == b"": break pack_data(data) def _extract_symrefs_and_agent(capabilities): """Extract symrefs and agent from capabilities. Args: capabilities: List of capabilities Returns: (symrefs, agent) tuple """ symrefs = {} agent = None for capability in capabilities: k, v = parse_capability(capability) if k == CAPABILITY_SYMREF: (src, dst) = v.split(b":", 1) symrefs[src] = dst if k == CAPABILITY_AGENT: agent = v return (symrefs, agent) # TODO(durin42): this doesn't correctly degrade if the server doesn't # support some capabilities. This should work properly with servers # that don't support multi_ack. class GitClient: """Git smart server client.""" def __init__( self, thin_packs=True, report_activity=None, quiet=False, include_tags=False, **kwargs, ) -> None: """Create a new GitClient instance. Args: thin_packs: Whether or not thin packs should be retrieved report_activity: Optional callback for reporting transport activity. include_tags: send annotated tags when sending the objects they point to """ self._report_activity = report_activity self._report_status_parser: Optional[ReportStatusParser] = None self._fetch_capabilities = set(UPLOAD_CAPABILITIES) self._fetch_capabilities.add(capability_agent()) self._send_capabilities = set(RECEIVE_CAPABILITIES) self._send_capabilities.add(capability_agent()) if quiet: self._send_capabilities.add(CAPABILITY_QUIET) if not thin_packs: self._fetch_capabilities.remove(CAPABILITY_THIN_PACK) if include_tags: self._fetch_capabilities.add(CAPABILITY_INCLUDE_TAG) self.protocol_version = 0 # will be overridden later def get_url(self, path) -> str: """Retrieves full url to given path. Args: path: Repository path (as string) Returns: Url to path (as string) """ raise NotImplementedError(self.get_url) @classmethod def from_parsedurl(cls, parsedurl, **kwargs) -> "GitClient": """Create an instance of this client from a urlparse.parsed object. Args: parsedurl: Result of urlparse() Returns: A `GitClient` object """ raise NotImplementedError(cls.from_parsedurl) def send_pack( self, path: str, update_refs, generate_pack_data: Callable[ [set[bytes], set[bytes], bool], tuple[int, Iterator[UnpackedObject]] ], progress=None, ) -> SendPackResult: """Upload a pack to a remote repository. Args: path: Repository path (as bytestring) update_refs: Function to determine changes to remote refs. Receive dict with existing remote refs, returns dict with changed refs (name -> sha, where sha=ZERO_SHA for deletions) generate_pack_data: Function that can return a tuple with number of objects and list of pack data to include progress: Optional progress function Returns: SendPackResult object Raises: SendPackError: if server rejects the pack data """ raise NotImplementedError(self.send_pack) def clone( self, path, target_path, mkdir: bool = True, bare: bool = False, origin: Optional[str] = "origin", checkout=None, branch=None, progress=None, depth=None, ref_prefix: Optional[list[Ref]] = None, filter_spec=None, protocol_version: Optional[int] = None, ) -> Repo: """Clone a repository.""" if mkdir: os.mkdir(target_path) try: target = None if not bare: target = Repo.init(target_path) if checkout is None: checkout = True else: if checkout: raise ValueError("checkout and bare are incompatible") target = Repo.init_bare(target_path) # TODO(jelmer): abstract method for get_location? if isinstance(self, (LocalGitClient, SubprocessGitClient)): encoded_path = path.encode("utf-8") else: encoded_path = self.get_url(path).encode("utf-8") assert target is not None if origin is not None: target_config = target.get_config() target_config.set( (b"remote", origin.encode("utf-8")), b"url", encoded_path ) target_config.set( (b"remote", origin.encode("utf-8")), b"fetch", b"+refs/heads/*:refs/remotes/" + origin.encode("utf-8") + b"/*", ) target_config.write_to_path() ref_message = b"clone: from " + encoded_path result = self.fetch( path, target, progress=progress, depth=depth, ref_prefix=ref_prefix, filter_spec=filter_spec, protocol_version=protocol_version, ) if origin is not None: _import_remote_refs( target.refs, origin, result.refs, message=ref_message ) origin_head = result.symrefs.get(b"HEAD") origin_sha = result.refs.get(b"HEAD") if origin is None or (origin_sha and not origin_head): # set detached HEAD target.refs[b"HEAD"] = origin_sha head = origin_sha else: _set_origin_head(target.refs, origin.encode("utf-8"), origin_head) head_ref = _set_default_branch( target.refs, origin.encode("utf-8"), origin_head, branch, ref_message, ) # Update target head if head_ref: head = _set_head(target.refs, head_ref, ref_message) else: head = None if checkout and head is not None: target.reset_index() except BaseException: if target is not None: target.close() if mkdir: import shutil shutil.rmtree(target_path) raise return target def fetch( self, path: str, target: Repo, determine_wants: Optional[ Callable[[dict[bytes, bytes], Optional[int]], list[bytes]] ] = None, progress: Optional[Callable[[bytes], None]] = None, depth: Optional[int] = None, ref_prefix: Optional[list[Ref]] = None, filter_spec: Optional[bytes] = None, protocol_version: Optional[int] = None, ) -> FetchPackResult: """Fetch into a target repository. Args: path: Path to fetch from (as bytestring) target: Target repository to fetch into determine_wants: Optional function to determine what refs to fetch. Receives dictionary of name->sha, should return list of shas to fetch. Defaults to all shas. progress: Optional progress function depth: Depth to fetch at ref_prefix: List of prefixes of desired references, as a list of bytestrings. Filtering is done by the server if supported, and client side otherwise. filter_spec: A git-rev-list-style object filter spec, as bytestring. Only used if the server supports the Git protocol-v2 'filter' feature, and ignored otherwise. protocol_version: Desired Git protocol version. By default the highest mutually supported protocol version will be used. Returns: Dictionary with all remote refs (not just those fetched) """ if determine_wants is None: determine_wants = target.object_store.determine_wants_all if CAPABILITY_THIN_PACK in self._fetch_capabilities: from tempfile import SpooledTemporaryFile f: IO[bytes] = SpooledTemporaryFile( max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-", dir=getattr(target.object_store, "path", None), ) def commit() -> None: if f.tell(): f.seek(0) target.object_store.add_thin_pack(f.read, None, progress=progress) # type: ignore f.close() def abort() -> None: f.close() else: f, commit, abort = target.object_store.add_pack() try: result = self.fetch_pack( path, determine_wants, target.get_graph_walker(), f.write, progress=progress, depth=depth, ref_prefix=ref_prefix, filter_spec=filter_spec, protocol_version=protocol_version, ) except BaseException: abort() raise else: commit() target.update_shallow(result.new_shallow, result.new_unshallow) return result def fetch_pack( self, path: str, determine_wants, graph_walker, pack_data, *, progress: Optional[Callable[[bytes], None]] = None, depth: Optional[int] = None, ref_prefix: Optional[list[Ref]] = None, filter_spec=None, protocol_version: Optional[int] = None, ) -> FetchPackResult: """Retrieve a pack from a git smart server. Args: path: Remote path to fetch from determine_wants: Function determine what refs to fetch. Receives dictionary of name->sha, should return list of shas to fetch. graph_walker: Object with next() and ack(). pack_data: Callback called for each bit of data in the pack progress: Callback for progress reports (strings) depth: Shallow fetch depth ref_prefix: List of prefixes of desired references, as a list of bytestrings. Filtering is done by the server if supported, and client side otherwise. filter_spec: A git-rev-list-style object filter spec, as bytestring. Only used if the server supports the Git protocol-v2 'filter' feature, and ignored otherwise. protocol_version: Desired Git protocol version. By default the highest mutually supported protocol version will be used. Returns: FetchPackResult object """ raise NotImplementedError(self.fetch_pack) def get_refs( self, path, protocol_version: Optional[int] = None, ref_prefix: Optional[list[Ref]] = None, ) -> dict[Ref, ObjectID]: """Retrieve the current refs from a git smart server. Args: path: Path to the repo to fetch from. (as bytestring) """ raise NotImplementedError(self.get_refs) @staticmethod def _should_send_pack(new_refs): # The packfile MUST NOT be sent if the only command used is delete. return any(sha != ZERO_SHA for sha in new_refs.values()) def _negotiate_receive_pack_capabilities(self, server_capabilities): negotiated_capabilities = self._send_capabilities & server_capabilities (agent, _symrefs) = _extract_symrefs_and_agent(server_capabilities) (extract_capability_names(server_capabilities) - KNOWN_RECEIVE_CAPABILITIES) # TODO(jelmer): warn about unknown capabilities return negotiated_capabilities, agent def _handle_receive_pack_tail( self, proto: Protocol, capabilities: set[bytes], progress: Optional[Callable[[bytes], None]] = None, ) -> Optional[dict[bytes, Optional[str]]]: """Handle the tail of a 'git-receive-pack' request. Args: proto: Protocol object to read from capabilities: List of negotiated capabilities progress: Optional progress reporting function Returns: dict mapping ref name to: error message if the ref failed to update None if it was updated successfully """ if CAPABILITY_SIDE_BAND_64K in capabilities or self.protocol_version == 2: if progress is None: def progress(x) -> None: pass if CAPABILITY_REPORT_STATUS in capabilities: assert self._report_status_parser is not None pktline_parser = PktLineParser(self._report_status_parser.handle_packet) for chan, data in _read_side_band64k_data(proto.read_pkt_seq()): if chan == SIDE_BAND_CHANNEL_DATA: if CAPABILITY_REPORT_STATUS in capabilities: pktline_parser.parse(data) elif chan == SIDE_BAND_CHANNEL_PROGRESS: progress(data) else: raise AssertionError(f"Invalid sideband channel {chan}") else: if CAPABILITY_REPORT_STATUS in capabilities: assert self._report_status_parser for pkt in proto.read_pkt_seq(): self._report_status_parser.handle_packet(pkt) if self._report_status_parser is not None: return dict(self._report_status_parser.check()) return None def _negotiate_upload_pack_capabilities(self, server_capabilities): (extract_capability_names(server_capabilities) - KNOWN_UPLOAD_CAPABILITIES) # TODO(jelmer): warn about unknown capabilities fetch_capa = None for capability in server_capabilities: k, v = parse_capability(capability) if self.protocol_version == 2 and k == CAPABILITY_FETCH: fetch_capa = CAPABILITY_FETCH fetch_features = [] v = v.strip().split(b" ") if b"shallow" in v: fetch_features.append(CAPABILITY_SHALLOW) if b"filter" in v: fetch_features.append(CAPABILITY_FILTER) for i in range(len(fetch_features)): if i == 0: fetch_capa += b"=" else: fetch_capa += b" " fetch_capa += fetch_features[i] (symrefs, agent) = _extract_symrefs_and_agent(server_capabilities) negotiated_capabilities = self._fetch_capabilities & server_capabilities if fetch_capa: negotiated_capabilities.add(fetch_capa) return (negotiated_capabilities, symrefs, agent) def archive( self, path, committish, write_data, progress=None, write_error=None, format=None, subdirs=None, prefix=None, ) -> None: """Retrieve an archive of the specified tree.""" raise NotImplementedError(self.archive) @staticmethod def _warn_filter_objects() -> None: import warnings warnings.warn( "object filtering not recognized by server, ignoring", UserWarning, ) def check_wants(wants, refs) -> None: """Check that a set of wants is valid. Args: wants: Set of object SHAs to fetch refs: Refs dictionary to check against """ missing = set(wants) - { v for (k, v) in refs.items() if not k.endswith(PEELED_TAG_SUFFIX) } if missing: raise InvalidWants(missing) def _remote_error_from_stderr(stderr): if stderr is None: return HangupException() lines = [line.rstrip(b"\n") for line in stderr.readlines()] for line in lines: if line.startswith(b"ERROR: "): return GitProtocolError(line[len(b"ERROR: ") :].decode("utf-8", "replace")) return HangupException(lines) class TraditionalGitClient(GitClient): """Traditional Git client.""" DEFAULT_ENCODING = "utf-8" def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs) -> None: self._remote_path_encoding = path_encoding super().__init__(**kwargs) def _connect( self, cmd: bytes, path: Union[str, bytes], protocol_version: Optional[int] = None, ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]: """Create a connection to the server. This method is abstract - concrete implementations should implement their own variant which connects to the server and returns an initialized Protocol object with the service ready for use and a can_read function which may be used to see if reads would block. Args: cmd: The git service name to which we should connect. path: The path we should pass to the service. (as bytestirng) protocol_version: Desired Git protocol version. By default the highest mutually supported protocol version will be used. """ raise NotImplementedError def send_pack(self, path, update_refs, generate_pack_data, progress=None): """Upload a pack to a remote repository. Args: path: Repository path (as bytestring) update_refs: Function to determine changes to remote refs. Receive dict with existing remote refs, returns dict with changed refs (name -> sha, where sha=ZERO_SHA for deletions) generate_pack_data: Function that can return a tuple with number of objects and pack data to upload. progress: Optional callback called with progress updates Returns: SendPackResult Raises: SendPackError: if server rejects the pack data """ self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND proto, unused_can_read, stderr = self._connect(b"receive-pack", path) with proto: try: old_refs, server_capabilities = read_pkt_refs_v1(proto.read_pkt_seq()) except HangupException as exc: raise _remote_error_from_stderr(stderr) from exc ( negotiated_capabilities, agent, ) = self._negotiate_receive_pack_capabilities(server_capabilities) if CAPABILITY_REPORT_STATUS in negotiated_capabilities: self._report_status_parser = ReportStatusParser() report_status_parser = self._report_status_parser try: new_refs = orig_new_refs = update_refs(dict(old_refs)) except BaseException: proto.write_pkt_line(None) raise if set(new_refs.items()).issubset(set(old_refs.items())): proto.write_pkt_line(None) return SendPackResult(new_refs, agent=agent, ref_status={}) if CAPABILITY_DELETE_REFS not in server_capabilities: # Server does not support deletions. Fail later. new_refs = dict(orig_new_refs) for ref, sha in orig_new_refs.items(): if sha == ZERO_SHA: if CAPABILITY_REPORT_STATUS in negotiated_capabilities: report_status_parser._ref_statuses.append( b"ng " + ref + b" remote does not support deleting refs" ) report_status_parser._ref_status_ok = False del new_refs[ref] if new_refs is None: proto.write_pkt_line(None) return SendPackResult(old_refs, agent=agent, ref_status={}) if len(new_refs) == 0 and orig_new_refs: # NOOP - Original new refs filtered out by policy proto.write_pkt_line(None) if report_status_parser is not None: ref_status = dict(report_status_parser.check()) else: ref_status = None return SendPackResult(old_refs, agent=agent, ref_status=ref_status) header_handler = _v1ReceivePackHeader( negotiated_capabilities, old_refs, new_refs ) for pkt in header_handler: proto.write_pkt_line(pkt) pack_data_count, pack_data = generate_pack_data( header_handler.have, header_handler.want, ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities), progress=progress, ) if self._should_send_pack(new_refs): for chunk in PackChunkGenerator( pack_data_count, pack_data, progress=progress ): proto.write(chunk) ref_status = self._handle_receive_pack_tail( proto, negotiated_capabilities, progress ) return SendPackResult(new_refs, agent=agent, ref_status=ref_status) def fetch_pack( self, path, determine_wants, graph_walker, pack_data, progress=None, depth=None, ref_prefix: Optional[list[Ref]] = None, filter_spec=None, protocol_version: Optional[int] = None, ): """Retrieve a pack from a git smart server. Args: path: Remote path to fetch from determine_wants: Function determine what refs to fetch. Receives dictionary of name->sha, should return list of shas to fetch. graph_walker: Object with next() and ack(). pack_data: Callback called for each bit of data in the pack progress: Callback for progress reports (strings) depth: Shallow fetch depth ref_prefix: List of prefixes of desired references, as a list of bytestrings. Filtering is done by the server if supported, and client side otherwise. filter_spec: A git-rev-list-style object filter spec, as bytestring. Only used if the server supports the Git protocol-v2 'filter' feature, and ignored otherwise. protocol_version: Desired Git protocol version. By default the highest mutually supported protocol version will be used. Returns: FetchPackResult object """ if ( protocol_version is not None and protocol_version not in GIT_PROTOCOL_VERSIONS ): raise ValueError(f"unknown Git protocol version {protocol_version}") proto, can_read, stderr = self._connect(b"upload-pack", path, protocol_version) server_protocol_version = negotiate_protocol_version(proto) if server_protocol_version not in GIT_PROTOCOL_VERSIONS: raise ValueError( f"unknown Git protocol version {server_protocol_version} used by server" ) if protocol_version and server_protocol_version > protocol_version: raise ValueError( f"bad Git protocol version {server_protocol_version} used by server" ) self.protocol_version = server_protocol_version with proto: if self.protocol_version == 2: try: server_capabilities = read_server_capabilities(proto.read_pkt_seq()) except HangupException as exc: raise _remote_error_from_stderr(stderr) from exc ( negotiated_capabilities, symrefs, agent, ) = self._negotiate_upload_pack_capabilities(server_capabilities) proto.write_pkt_line(b"command=ls-refs\n") proto.write(b"0001") # delim-pkt proto.write_pkt_line(b"symrefs") proto.write_pkt_line(b"peel") if ref_prefix is None: ref_prefix = DEFAULT_REF_PREFIX for prefix in ref_prefix: proto.write_pkt_line(b"ref-prefix " + prefix) proto.write_pkt_line(None) refs, symrefs, _peeled = read_pkt_refs_v2(proto.read_pkt_seq()) else: try: refs, server_capabilities = read_pkt_refs_v1(proto.read_pkt_seq()) except HangupException as exc: raise _remote_error_from_stderr(stderr) from exc ( negotiated_capabilities, symrefs, agent, ) = self._negotiate_upload_pack_capabilities(server_capabilities) if ref_prefix is not None: refs = filter_ref_prefix(refs, ref_prefix) if refs is None: proto.write_pkt_line(None) return FetchPackResult(refs, symrefs, agent) try: if depth is not None: wants = determine_wants(refs, depth=depth) else: wants = determine_wants(refs) except BaseException: proto.write_pkt_line(None) raise if wants is not None: wants = [cid for cid in wants if cid != ZERO_SHA] if not wants: proto.write_pkt_line(None) return FetchPackResult(refs, symrefs, agent) if self.protocol_version == 2: proto.write_pkt_line(b"command=fetch\n") proto.write(b"0001") # delim-pkt if ( find_capability( negotiated_capabilities, CAPABILITY_FETCH, CAPABILITY_FILTER ) and filter_spec ): proto.write(pkt_line(b"filter %s\n" % filter_spec)) elif filter_spec: self._warn_filter_objects() elif filter_spec: self._warn_filter_objects() (new_shallow, new_unshallow) = _handle_upload_pack_head( proto, negotiated_capabilities, graph_walker, wants, can_read, depth=depth, protocol_version=self.protocol_version, ) _handle_upload_pack_tail( proto, negotiated_capabilities, graph_walker, pack_data, progress, protocol_version=self.protocol_version, ) return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow) def get_refs( self, path, protocol_version: Optional[int] = None, ref_prefix: Optional[list[Ref]] = None, ): """Retrieve the current refs from a git smart server.""" # stock `git ls-remote` uses upload-pack if ( protocol_version is not None and protocol_version not in GIT_PROTOCOL_VERSIONS ): raise ValueError(f"unknown Git protocol version {protocol_version}") proto, _, stderr = self._connect(b"upload-pack", path, protocol_version) server_protocol_version = negotiate_protocol_version(proto) if server_protocol_version not in GIT_PROTOCOL_VERSIONS: raise ValueError( f"unknown Git protocol version {server_protocol_version} used by server" ) if protocol_version and server_protocol_version > protocol_version: raise ValueError( f"bad Git protocol version {server_protocol_version} used by server" ) self.protocol_version = server_protocol_version if self.protocol_version == 2: server_capabilities = read_server_capabilities(proto.read_pkt_seq()) proto.write_pkt_line(b"command=ls-refs\n") proto.write(b"0001") # delim-pkt proto.write_pkt_line(b"symrefs") proto.write_pkt_line(b"peel") if ref_prefix is None: ref_prefix = DEFAULT_REF_PREFIX for prefix in ref_prefix: proto.write_pkt_line(b"ref-prefix " + prefix) proto.write_pkt_line(None) with proto: try: refs, _symrefs, peeled = read_pkt_refs_v2(proto.read_pkt_seq()) except HangupException as exc: raise _remote_error_from_stderr(stderr) from exc proto.write_pkt_line(None) for refname, refvalue in peeled.items(): refs[refname + PEELED_TAG_SUFFIX] = refvalue return refs else: with proto: try: refs, server_capabilities = read_pkt_refs_v1(proto.read_pkt_seq()) except HangupException as exc: raise _remote_error_from_stderr(stderr) from exc proto.write_pkt_line(None) (_symrefs, _agent) = _extract_symrefs_and_agent(server_capabilities) if ref_prefix is not None: refs = filter_ref_prefix(refs, ref_prefix) return refs def archive( self, path, committish, write_data, progress=None, write_error=None, format=None, subdirs=None, prefix=None, ) -> None: proto, can_read, stderr = self._connect(b"upload-archive", path) with proto: if format is not None: proto.write_pkt_line(b"argument --format=" + format) proto.write_pkt_line(b"argument " + committish) if subdirs is not None: for subdir in subdirs: proto.write_pkt_line(b"argument " + subdir) if prefix is not None: proto.write_pkt_line(b"argument --prefix=" + prefix) proto.write_pkt_line(None) try: pkt = proto.read_pkt_line() except HangupException as exc: raise _remote_error_from_stderr(stderr) from exc if pkt == b"NACK\n" or pkt == b"NACK": return elif pkt == b"ACK\n" or pkt == b"ACK": pass elif pkt.startswith(b"ERR "): raise GitProtocolError(pkt[4:].rstrip(b"\n").decode("utf-8", "replace")) else: raise AssertionError(f"invalid response {pkt!r}") ret = proto.read_pkt_line() if ret is not None: raise AssertionError("expected pkt tail") for chan, data in _read_side_band64k_data(proto.read_pkt_seq()): if chan == SIDE_BAND_CHANNEL_DATA: write_data(data) elif chan == SIDE_BAND_CHANNEL_PROGRESS: progress(data) elif chan == SIDE_BAND_CHANNEL_FATAL: write_error(data) else: raise AssertionError(f"Invalid sideband channel {chan}") class TCPGitClient(TraditionalGitClient): """A Git Client that works over TCP directly (i.e. git://).""" def __init__(self, host, port=None, **kwargs) -> None: if port is None: port = TCP_GIT_PORT self._host = host self._port = port super().__init__(**kwargs) @classmethod def from_parsedurl(cls, parsedurl, **kwargs): return cls(parsedurl.hostname, port=parsedurl.port, **kwargs) def get_url(self, path): netloc = self._host if self._port is not None and self._port != TCP_GIT_PORT: netloc += f":{self._port}" return urlunsplit(("git", netloc, path, "", "")) def _connect( self, cmd: bytes, path: Union[str, bytes], protocol_version: Optional[int] = None, ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]: if not isinstance(cmd, bytes): raise TypeError(cmd) if not isinstance(path, bytes): path = path.encode(self._remote_path_encoding) sockaddrs = socket.getaddrinfo( self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM ) s = None err = OSError(f"no address found for {self._host}") for family, socktype, protof, canonname, sockaddr in sockaddrs: s = socket.socket(family, socktype, protof) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) try: s.connect(sockaddr) break except OSError as e: err = e if s is not None: s.close() s = None if s is None: raise err # -1 means system default buffering rfile = s.makefile("rb", -1) # 0 means unbuffered wfile = s.makefile("wb", 0) def close() -> None: rfile.close() wfile.close() s.close() proto = Protocol( rfile.read, wfile.write, close, report_activity=self._report_activity, ) if path.startswith(b"/~"): path = path[1:] if cmd == b"upload-pack": if protocol_version is None: self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH else: self.protocol_version = protocol_version else: self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND if cmd == b"upload-pack" and self.protocol_version == 2: # Git protocol version advertisement is hidden behind two NUL bytes # for compatibility with older Git server implementations, which # would crash if something other than a "host=" header was found # after the first NUL byte. version_str = b"\0\0version=%d\0" % self.protocol_version else: version_str = b"" # TODO(jelmer): Alternative to ascii? proto.send_cmd( b"git-" + cmd, path, b"host=" + self._host.encode("ascii") + version_str ) return proto, lambda: _fileno_can_read(s), None class SubprocessWrapper: """A socket-like object that talks to a subprocess via pipes.""" def __init__(self, proc) -> None: self.proc = proc self.read = BufferedReader(proc.stdout).read self.write = proc.stdin.write @property def stderr(self): return self.proc.stderr def can_read(self): if sys.platform == "win32": from msvcrt import get_osfhandle handle = get_osfhandle(self.proc.stdout.fileno()) return _win32_peek_avail(handle) != 0 else: return _fileno_can_read(self.proc.stdout.fileno()) def close(self) -> None: self.proc.stdin.close() self.proc.stdout.close() if self.proc.stderr: self.proc.stderr.close() self.proc.wait() def find_git_command() -> list[str]: """Find command to run for system Git (usually C Git).""" if sys.platform == "win32": # support .exe, .bat and .cmd try: # to avoid overhead import pywintypes import win32api except ImportError: # run through cmd.exe with some overhead return ["cmd", "/c", "git"] else: try: status, git = win32api.FindExecutable("git") return [git] except pywintypes.error: return ["cmd", "/c", "git"] else: return ["git"] class SubprocessGitClient(TraditionalGitClient): """Git client that talks to a server using a subprocess.""" @classmethod def from_parsedurl(cls, parsedurl, **kwargs): return cls(**kwargs) git_command = None def _connect( self, service: bytes, path: Union[bytes, str], protocol_version: Optional[int] = None, ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]: if not isinstance(service, bytes): raise TypeError(service) if isinstance(path, bytes): path = path.decode(self._remote_path_encoding) if self.git_command is None: git_command = find_git_command() argv = [*git_command, service.decode("ascii"), path] p = subprocess.Popen( argv, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) pw = SubprocessWrapper(p) return ( Protocol( pw.read, pw.write, pw.close, report_activity=self._report_activity, ), pw.can_read, p.stderr, ) class LocalGitClient(GitClient): """Git Client that just uses a local on-disk repository.""" def __init__( self, thin_packs: bool = True, report_activity=None, config: Optional[Config] = None, ) -> None: """Create a new LocalGitClient instance. Args: thin_packs: Whether or not thin packs should be retrieved report_activity: Optional callback for reporting transport activity. """ self._report_activity = report_activity # Ignore the thin_packs argument def get_url(self, path): return urlunsplit(("file", "", path, "", "")) @classmethod def from_parsedurl(cls, parsedurl, **kwargs): return cls(**kwargs) @classmethod def _open_repo(cls, path): if not isinstance(path, str): path = os.fsdecode(path) return closing(Repo(path)) def send_pack(self, path, update_refs, generate_pack_data, progress=None): """Upload a pack to a local on-disk repository. Args: path: Repository path (as bytestring) update_refs: Function to determine changes to remote refs. Receive dict with existing remote refs, returns dict with changed refs (name -> sha, where sha=ZERO_SHA for deletions) with number of items and pack data to upload. progress: Optional progress function Returns: SendPackResult Raises: SendPackError: if server rejects the pack data """ if not progress: def progress(x) -> None: pass with self._open_repo(path) as target: old_refs = target.get_refs() new_refs = update_refs(dict(old_refs)) have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA] want = [] for refname, new_sha1 in new_refs.items(): if ( new_sha1 not in have and new_sha1 not in want and new_sha1 != ZERO_SHA ): want.append(new_sha1) if not want and set(new_refs.items()).issubset(set(old_refs.items())): return SendPackResult(new_refs, ref_status={}) target.object_store.add_pack_data( *generate_pack_data(have, want, ofs_delta=True) ) ref_status = {} for refname, new_sha1 in new_refs.items(): old_sha1 = old_refs.get(refname, ZERO_SHA) if new_sha1 != ZERO_SHA: if not target.refs.set_if_equals(refname, old_sha1, new_sha1): msg = f"unable to set {refname} to {new_sha1}" progress(msg) ref_status[refname] = msg else: if not target.refs.remove_if_equals(refname, old_sha1): progress(f"unable to remove {refname}") ref_status[refname] = "unable to remove" return SendPackResult(new_refs, ref_status=ref_status) def fetch( self, path: str, target: Repo, determine_wants: Optional[ Callable[[dict[bytes, bytes], Optional[int]], list[bytes]] ] = None, progress: Optional[Callable[[bytes], None]] = None, depth: Optional[int] = None, ref_prefix: Optional[list[Ref]] = None, filter_spec: Optional[bytes] = None, protocol_version: Optional[int] = None, **kwargs, ): """Fetch into a target repository. Args: path: Path to fetch from (as bytestring) target: Target repository to fetch into determine_wants: Optional function determine what refs to fetch. Receives dictionary of name->sha, should return list of shas to fetch. Defaults to all shas. progress: Optional progress function depth: Shallow fetch depth ref_prefix: List of prefixes of desired references, as a list of bytestrings. Filtering is done by the server if supported, and client side otherwise. filter_spec: A git-rev-list-style object filter spec, as bytestring. Only used if the server supports the Git protocol-v2 'filter' feature, and ignored otherwise. Returns: FetchPackResult object """ with self._open_repo(path) as r: refs = r.fetch( target, determine_wants=determine_wants, progress=progress, depth=depth, ) return FetchPackResult(refs, r.refs.get_symrefs(), agent_string()) def fetch_pack( self, path, determine_wants, graph_walker, pack_data, progress=None, depth=None, ref_prefix: Optional[list[Ref]] = None, filter_spec: Optional[bytes] = None, protocol_version: Optional[int] = None, ) -> FetchPackResult: """Retrieve a pack from a local on-disk repository. Args: path: Remote path to fetch from determine_wants: Function determine what refs to fetch. Receives dictionary of name->sha, should return list of shas to fetch. graph_walker: Object with next() and ack(). pack_data: Callback called for each bit of data in the pack progress: Callback for progress reports (strings) depth: Shallow fetch depth ref_prefix: List of prefixes of desired references, as a list of bytestrings. Filtering is done by the server if supported, and client side otherwise. filter_spec: A git-rev-list-style object filter spec, as bytestring. Only used if the server supports the Git protocol-v2 'filter' feature, and ignored otherwise. Returns: FetchPackResult object """ with self._open_repo(path) as r: missing_objects = r.find_missing_objects( determine_wants, graph_walker, progress=progress, depth=depth ) other_haves = missing_objects.get_remote_has() object_ids = list(missing_objects) symrefs = r.refs.get_symrefs() agent = agent_string() # Did the process short-circuit (e.g. in a stateless RPC call)? # Note that the client still expects a 0-object pack in most cases. if object_ids is None: return FetchPackResult(None, symrefs, agent) write_pack_from_container( pack_data, r.object_store, object_ids, other_haves=other_haves ) return FetchPackResult(r.get_refs(), symrefs, agent) def get_refs( self, path, protocol_version: Optional[int] = None, ref_prefix: Optional[list[Ref]] = None, ): """Retrieve the current refs from a local on-disk repository.""" with self._open_repo(path) as target: return target.get_refs() # What Git client to use for local access default_local_git_client_cls = LocalGitClient class SSHVendor: """A client side SSH implementation.""" def run_command( self, host, command, username=None, port=None, password=None, key_filename=None, ssh_command=None, protocol_version: Optional[int] = None, ): """Connect to an SSH server. Run a command remotely and return a file-like object for interaction with the remote command. Args: host: Host name command: Command to run (as argv array) username: Optional ame of user to log in as port: Optional SSH port to use password: Optional ssh password for login or private key key_filename: Optional path to private keyfile ssh_command: Optional SSH command protocol_version: Desired Git protocol version. By default the highest mutually supported protocol version will be used. """ raise NotImplementedError(self.run_command) class StrangeHostname(Exception): """Refusing to connect to strange SSH hostname.""" def __init__(self, hostname) -> None: super().__init__(hostname) class SubprocessSSHVendor(SSHVendor): """SSH vendor that shells out to the local 'ssh' command.""" def run_command( self, host, command, username=None, port=None, password=None, key_filename=None, ssh_command=None, protocol_version: Optional[int] = None, ): if password is not None: raise NotImplementedError( "Setting password not supported by SubprocessSSHVendor." ) if ssh_command: import shlex args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-x"] else: args = ["ssh", "-x"] if port: args.extend(["-p", str(port)]) if key_filename: args.extend(["-i", str(key_filename)]) if protocol_version is None: protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH if protocol_version > 0: args.extend(["-o", f"SetEnv GIT_PROTOCOL=version={protocol_version}"]) if username: host = f"{username}@{host}" if host.startswith("-"): raise StrangeHostname(hostname=host) args.append(host) proc = subprocess.Popen( [*args, command], bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) return SubprocessWrapper(proc) class PLinkSSHVendor(SSHVendor): """SSH vendor that shells out to the local 'plink' command.""" def run_command( self, host, command, username=None, port=None, password=None, key_filename=None, ssh_command=None, protocol_version: Optional[int] = None, ): if ssh_command: import shlex args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-ssh"] elif sys.platform == "win32": args = ["plink.exe", "-ssh"] else: args = ["plink", "-ssh"] if password is not None: import warnings warnings.warn( "Invoking PLink with a password exposes the password in the " "process list." ) args.extend(["-pw", str(password)]) if port: args.extend(["-P", str(port)]) if key_filename: args.extend(["-i", str(key_filename)]) if username: host = f"{username}@{host}" if host.startswith("-"): raise StrangeHostname(hostname=host) args.append(host) # plink.exe does not provide a way to pass environment variables # via the command line. The best we can do is set an environment # variable and hope that plink will pass it to the server. If this # does not work then the server should behave as if we had requested # protocol version 0. env = copy.deepcopy(os.environ) if protocol_version is None: protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH if protocol_version > 0: env["GIT_PROTOCOL"] = f"version={protocol_version}" proc = subprocess.Popen( [*args, command], bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, ) return SubprocessWrapper(proc) def ParamikoSSHVendor(**kwargs): import warnings warnings.warn( "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.", DeprecationWarning, ) from .contrib.paramiko_vendor import ParamikoSSHVendor return ParamikoSSHVendor(**kwargs) # Can be overridden by users get_ssh_vendor = SubprocessSSHVendor class SSHGitClient(TraditionalGitClient): def __init__( self, host, port=None, username=None, vendor=None, config=None, password=None, key_filename=None, ssh_command=None, **kwargs, ) -> None: self.host = host self.port = port self.username = username self.password = password self.key_filename = key_filename self.ssh_command = ssh_command or os.environ.get( "GIT_SSH_COMMAND", os.environ.get("GIT_SSH") ) super().__init__(**kwargs) self.alternative_paths: dict[bytes, bytes] = {} if vendor is not None: self.ssh_vendor = vendor else: self.ssh_vendor = get_ssh_vendor() def get_url(self, path): netloc = self.host if self.port is not None: netloc += f":{self.port}" if self.username is not None: netloc = urlquote(self.username, "@/:") + "@" + netloc return urlunsplit(("ssh", netloc, path, "", "")) @classmethod def from_parsedurl(cls, parsedurl, **kwargs): return cls( host=parsedurl.hostname, port=parsedurl.port, username=parsedurl.username, **kwargs, ) def _get_cmd_path(self, cmd): cmd = self.alternative_paths.get(cmd, b"git-" + cmd) assert isinstance(cmd, bytes) return cmd def _connect( self, cmd: bytes, path: Union[str, bytes], protocol_version: Optional[int] = None, ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]: if not isinstance(cmd, bytes): raise TypeError(cmd) if isinstance(path, bytes): path = path.decode(self._remote_path_encoding) if path.startswith("/~"): path = path[1:] argv = ( self._get_cmd_path(cmd).decode(self._remote_path_encoding) + " '" + path + "'" ) kwargs = {} if self.password is not None: kwargs["password"] = self.password if self.key_filename is not None: kwargs["key_filename"] = self.key_filename # GIT_SSH_COMMAND takes precedence over GIT_SSH if self.ssh_command is not None: kwargs["ssh_command"] = self.ssh_command con = self.ssh_vendor.run_command( self.host, argv, port=self.port, username=self.username, protocol_version=protocol_version, **kwargs, ) return ( Protocol( con.read, con.write, con.close, report_activity=self._report_activity, ), con.can_read, getattr(con, "stderr", None), ) def default_user_agent_string(): # Start user agent with "git/", because GitHub requires this. :-( See # https://github.com/jelmer/dulwich/issues/562 for details. return "git/dulwich/{}".format(".".join([str(x) for x in dulwich.__version__])) def default_urllib3_manager( config, pool_manager_cls=None, proxy_manager_cls=None, base_url=None, **override_kwargs, ) -> Union["urllib3.ProxyManager", "urllib3.PoolManager"]: """Return urllib3 connection pool manager. Honour detected proxy configurations. Args: config: `dulwich.config.ConfigDict` instance with Git configuration. override_kwargs: Additional arguments for `urllib3.ProxyManager` Returns: Either pool_manager_cls (defaults to `urllib3.ProxyManager`) instance for proxy configurations, proxy_manager_cls (defaults to `urllib3.PoolManager`) instance otherwise """ proxy_server = user_agent = None ca_certs = ssl_verify = None if proxy_server is None: for proxyname in ("https_proxy", "http_proxy", "all_proxy"): proxy_server = os.environ.get(proxyname) if proxy_server: break if proxy_server: if check_for_proxy_bypass(base_url): proxy_server = None if config is not None: if proxy_server is None: try: proxy_server = config.get(b"http", b"proxy") except KeyError: pass try: user_agent = config.get(b"http", b"useragent") except KeyError: pass # TODO(jelmer): Support per-host settings try: ssl_verify = config.get_boolean(b"http", b"sslVerify") except KeyError: ssl_verify = True try: ca_certs = config.get(b"http", b"sslCAInfo") except KeyError: ca_certs = None if user_agent is None: user_agent = default_user_agent_string() headers = {"User-agent": user_agent} kwargs = { "ca_certs": ca_certs, } if ssl_verify is True: kwargs["cert_reqs"] = "CERT_REQUIRED" elif ssl_verify is False: kwargs["cert_reqs"] = "CERT_NONE" else: # Default to SSL verification kwargs["cert_reqs"] = "CERT_REQUIRED" kwargs.update(override_kwargs) import urllib3 if proxy_server is not None: if proxy_manager_cls is None: proxy_manager_cls = urllib3.ProxyManager if not isinstance(proxy_server, str): proxy_server = proxy_server.decode() proxy_server_url = urlparse(proxy_server) if proxy_server_url.username is not None: proxy_headers = urllib3.make_headers( proxy_basic_auth=f"{proxy_server_url.username}:{proxy_server_url.password or ''}" # type: ignore ) else: proxy_headers = {} manager = proxy_manager_cls( proxy_server, proxy_headers=proxy_headers, headers=headers, **kwargs ) else: if pool_manager_cls is None: pool_manager_cls = urllib3.PoolManager manager = pool_manager_cls(headers=headers, **kwargs) return manager def check_for_proxy_bypass(base_url) -> bool: # Check if a proxy bypass is defined with the no_proxy environment variable if base_url: # only check if base_url is provided no_proxy_str = os.environ.get("no_proxy") if no_proxy_str: # implementation based on curl behavior: https://curl.se/libcurl/c/CURLOPT_NOPROXY.html # get hostname of provided parsed url parsed_url = urlparse(base_url) hostname = parsed_url.hostname if hostname: import ipaddress # check if hostname is an ip address try: hostname_ip = ipaddress.ip_address(hostname) except ValueError: hostname_ip = None no_proxy_values = no_proxy_str.split(",") for no_proxy_value in no_proxy_values: no_proxy_value = no_proxy_value.strip() if no_proxy_value: no_proxy_value = no_proxy_value.lower() no_proxy_value = no_proxy_value.lstrip( "." ) # ignore leading dots if hostname_ip: # check if no_proxy_value is a ip network try: no_proxy_value_network = ipaddress.ip_network( no_proxy_value, strict=False ) except ValueError: no_proxy_value_network = None if no_proxy_value_network: # if hostname is a ip address and no_proxy_value is a ip network -> check if ip address is part of network if hostname_ip in no_proxy_value_network: return True if no_proxy_value == "*": # '*' is special case for always bypass proxy return True if hostname == no_proxy_value: return True no_proxy_value = ( "." + no_proxy_value ) # add a dot to only match complete domains if hostname.endswith(no_proxy_value): return True return False class AbstractHttpGitClient(GitClient): """Abstract base class for HTTP Git Clients. This is agonistic of the actual HTTP implementation. Subclasses should provide an implementation of the _http_request method. """ def __init__(self, base_url, dumb=False, **kwargs) -> None: self._base_url = base_url.rstrip("/") + "/" self.dumb = dumb GitClient.__init__(self, **kwargs) def _http_request(self, url, headers=None, data=None): """Perform HTTP request. Args: url: Request URL. headers: Optional custom headers to override defaults. data: Request data. Returns: Tuple (response, read), where response is an urllib3 response object with additional content_type and redirect_location properties, and read is a consumable read method for the response data. Raises: GitProtocolError """ raise NotImplementedError(self._http_request) def _discover_references( self, service, base_url, protocol_version: Optional[int] = None, ref_prefix: Optional[list[Ref]] = None, ) -> tuple[ dict[Ref, ObjectID], set[bytes], str, dict[Ref, Ref], dict[Ref, ObjectID] ]: if ( protocol_version is not None and protocol_version not in GIT_PROTOCOL_VERSIONS ): raise ValueError(f"unknown Git protocol version {protocol_version}") assert base_url[-1] == "/" tail = "info/refs" headers = {"Accept": "*/*"} if self.dumb is not True: tail += "?service={}".format(service.decode("ascii")) # Enable protocol v2 only when fetching, not when pushing. # Git does not yet implement push over protocol v2, and as of # git version 2.37.3 git-http-backend's behaviour is erratic if # we try: It responds with a Git-protocol-v1-style ref listing # which lacks the "001f# service=git-receive-pack" marker. if service == b"git-upload-pack": if protocol_version is None: self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH else: self.protocol_version = protocol_version if self.protocol_version == 2: headers["Git-Protocol"] = "version=2" else: self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND url = urljoin(base_url, tail) resp, read = self._http_request(url, headers) if resp.redirect_location: # Something changed (redirect!), so let's update the base URL if not resp.redirect_location.endswith(tail): raise GitProtocolError( f"Redirected from URL {url} to URL {resp.redirect_location} without {tail}" ) base_url = urljoin(url, resp.redirect_location[: -len(tail)]) try: self.dumb = resp.content_type is None or not resp.content_type.startswith( "application/x-git-" ) if not self.dumb: def begin_protocol_v2(proto): nonlocal ref_prefix server_capabilities = read_server_capabilities(proto.read_pkt_seq()) if ref_prefix is None: ref_prefix = DEFAULT_REF_PREFIX pkts = [ b"symrefs", b"peel", ] for prefix in ref_prefix: pkts.append(b"ref-prefix " + prefix) body = b"".join( [pkt_line(b"command=ls-refs\n"), b"0001", pkt_seq(*pkts)] ) resp, read = self._smart_request( service.decode("ascii"), base_url, body ) proto = Protocol(read, None) return server_capabilities, resp, read, proto proto = Protocol(read, None) server_protocol_version = negotiate_protocol_version(proto) if server_protocol_version not in GIT_PROTOCOL_VERSIONS: raise ValueError( f"unknown Git protocol version {server_protocol_version} used by server" ) if protocol_version and server_protocol_version > protocol_version: raise ValueError( f"bad Git protocol version {server_protocol_version} used by server" ) self.protocol_version = server_protocol_version if self.protocol_version == 2: server_capabilities, resp, read, proto = begin_protocol_v2(proto) (refs, symrefs, peeled) = read_pkt_refs_v2(proto.read_pkt_seq()) return refs, server_capabilities, base_url, symrefs, peeled else: try: [pkt] = list(proto.read_pkt_seq()) except ValueError as exc: raise GitProtocolError( "unexpected number of packets received" ) from exc if pkt.rstrip(b"\n") != (b"# service=" + service): raise GitProtocolError( f"unexpected first line {pkt!r} from smart server" ) # Github sends "version 2" after sending the service name. # Try to negotiate protocol version 2 again. server_protocol_version = negotiate_protocol_version(proto) if server_protocol_version not in GIT_PROTOCOL_VERSIONS: raise ValueError( f"unknown Git protocol version {server_protocol_version} used by server" ) if protocol_version and server_protocol_version > protocol_version: raise ValueError( f"bad Git protocol version {server_protocol_version} used by server" ) self.protocol_version = server_protocol_version if self.protocol_version == 2: server_capabilities, resp, read, proto = begin_protocol_v2( proto ) (refs, symrefs, peeled) = read_pkt_refs_v2(proto.read_pkt_seq()) else: ( refs, server_capabilities, ) = read_pkt_refs_v1(proto.read_pkt_seq()) (refs, peeled) = split_peeled_refs(refs) (symrefs, agent) = _extract_symrefs_and_agent( server_capabilities ) if ref_prefix is not None: refs = filter_ref_prefix(refs, ref_prefix) return refs, server_capabilities, base_url, symrefs, peeled else: self.protocol_version = 0 # dumb servers only support protocol v0 (refs, peeled) = split_peeled_refs(read_info_refs(resp)) if ref_prefix is not None: refs = filter_ref_prefix(refs, ref_prefix) return refs, set(), base_url, {}, peeled finally: resp.close() def _smart_request(self, service, url, data): """Send a 'smart' HTTP request. This is a simple wrapper around _http_request that sets a couple of extra headers. """ assert url[-1] == "/" url = urljoin(url, service) result_content_type = f"application/x-{service}-result" headers = { "Content-Type": f"application/x-{service}-request", "Accept": result_content_type, } if self.protocol_version == 2: headers["Git-Protocol"] = "version=2" if isinstance(data, bytes): headers["Content-Length"] = str(len(data)) resp, read = self._http_request(url, headers, data) if resp.content_type.split(";")[0] != result_content_type: raise GitProtocolError( f"Invalid content-type from server: {resp.content_type}" ) return resp, read def send_pack(self, path, update_refs, generate_pack_data, progress=None): """Upload a pack to a remote repository. Args: path: Repository path (as bytestring) update_refs: Function to determine changes to remote refs. Receives dict with existing remote refs, returns dict with changed refs (name -> sha, where sha=ZERO_SHA for deletions) generate_pack_data: Function that can return a tuple with number of elements and pack data to upload. progress: Optional progress function Returns: SendPackResult Raises: SendPackError: if server rejects the pack data """ url = self._get_url(path) old_refs, server_capabilities, url, symrefs, peeled = self._discover_references( b"git-receive-pack", url ) ( negotiated_capabilities, agent, ) = self._negotiate_receive_pack_capabilities(server_capabilities) negotiated_capabilities.add(capability_agent()) if CAPABILITY_REPORT_STATUS in negotiated_capabilities: self._report_status_parser = ReportStatusParser() new_refs = update_refs(dict(old_refs)) if new_refs is None: # Determine wants function is aborting the push. return SendPackResult(old_refs, agent=agent, ref_status={}) if set(new_refs.items()).issubset(set(old_refs.items())): return SendPackResult(new_refs, agent=agent, ref_status={}) if self.dumb: raise NotImplementedError(self.fetch_pack) def body_generator(): header_handler = _v1ReceivePackHeader( negotiated_capabilities, old_refs, new_refs ) for pkt in header_handler: yield pkt_line(pkt) pack_data_count, pack_data = generate_pack_data( header_handler.have, header_handler.want, ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities), ) if self._should_send_pack(new_refs): yield from PackChunkGenerator(pack_data_count, pack_data) resp, read = self._smart_request("git-receive-pack", url, data=body_generator()) try: resp_proto = Protocol(read, None) ref_status = self._handle_receive_pack_tail( resp_proto, negotiated_capabilities, progress ) return SendPackResult(new_refs, agent=agent, ref_status=ref_status) finally: resp.close() def fetch_pack( self, path, determine_wants, graph_walker, pack_data, progress=None, depth=None, ref_prefix: Optional[list[Ref]] = None, filter_spec=None, protocol_version: Optional[int] = None, ): """Retrieve a pack from a git smart server. Args: path: Path to fetch from determine_wants: Callback that returns list of commits to fetch graph_walker: Object with next() and ack(). pack_data: Callback called for each bit of data in the pack progress: Callback for progress reports (strings) depth: Depth for request ref_prefix: List of prefixes of desired references, as a list of bytestrings. Filtering is done by the server if supported, and client side otherwise. filter_spec: A git-rev-list-style object filter spec, as bytestring. Only used if the server supports the Git protocol-v2 'filter' feature, and ignored otherwise. protocol_version: Desired Git protocol version. By default the highest mutually supported protocol version will be used. Returns: FetchPackResult object """ url = self._get_url(path) refs, server_capabilities, url, symrefs, peeled = self._discover_references( b"git-upload-pack", url, protocol_version=protocol_version, ref_prefix=ref_prefix, ) ( negotiated_capabilities, capa_symrefs, agent, ) = self._negotiate_upload_pack_capabilities(server_capabilities) if not symrefs and capa_symrefs: symrefs = capa_symrefs if depth is not None: wants = determine_wants(refs, depth=depth) else: wants = determine_wants(refs) if wants is not None: wants = [cid for cid in wants if cid != ZERO_SHA] if not wants: return FetchPackResult(refs, symrefs, agent) if self.dumb: raise NotImplementedError(self.fetch_pack) req_data = BytesIO() req_proto = Protocol(None, req_data.write) (new_shallow, new_unshallow) = _handle_upload_pack_head( req_proto, negotiated_capabilities, graph_walker, wants, can_read=None, depth=depth, protocol_version=self.protocol_version, ) if self.protocol_version == 2: data = pkt_line(b"command=fetch\n") + b"0001" if ( find_capability( negotiated_capabilities, CAPABILITY_FETCH, CAPABILITY_FILTER ) and filter_spec ): data += pkt_line(b"filter %s\n" % filter_spec) elif filter_spec: self._warn_filter_objects() data += req_data.getvalue() else: if filter_spec: self._warn_filter_objects() data = req_data.getvalue() resp, read = self._smart_request("git-upload-pack", url, data) try: resp_proto = Protocol(read, None) if new_shallow is None and new_unshallow is None: (new_shallow, new_unshallow) = _read_shallow_updates( resp_proto.read_pkt_seq() ) _handle_upload_pack_tail( resp_proto, negotiated_capabilities, graph_walker, pack_data, progress, protocol_version=self.protocol_version, ) return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow) finally: resp.close() def get_refs( self, path, protocol_version: Optional[int] = None, ref_prefix: Optional[list[Ref]] = None, ): """Retrieve the current refs from a git smart server.""" url = self._get_url(path) refs, _, _, _, peeled = self._discover_references( b"git-upload-pack", url, protocol_version=protocol_version, ref_prefix=ref_prefix, ) for refname, refvalue in peeled.items(): refs[refname + PEELED_TAG_SUFFIX] = refvalue return refs def get_url(self, path): return self._get_url(path).rstrip("/") def _get_url(self, path): return urljoin(self._base_url, path).rstrip("/") + "/" @classmethod def from_parsedurl(cls, parsedurl, **kwargs): password = parsedurl.password if password is not None: kwargs["password"] = urlunquote(password) username = parsedurl.username if username is not None: kwargs["username"] = urlunquote(username) return cls(urlunparse(parsedurl), **kwargs) def __repr__(self) -> str: return f"{type(self).__name__}({self._base_url!r}, dumb={self.dumb!r})" def _wrap_urllib3_exceptions(func): from urllib3.exceptions import ProtocolError def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ProtocolError as error: raise GitProtocolError(str(error)) from error return wrapper class Urllib3HttpGitClient(AbstractHttpGitClient): def __init__( self, base_url, dumb=None, pool_manager=None, config=None, username=None, password=None, **kwargs, ) -> None: self._username = username self._password = password if pool_manager is None: self.pool_manager = default_urllib3_manager(config, base_url=base_url) else: self.pool_manager = pool_manager if username is not None: # No escaping needed: ":" is not allowed in username: # https://tools.ietf.org/html/rfc2617#section-2 credentials = f"{username}:{password or ''}" import urllib3.util basic_auth = urllib3.util.make_headers(basic_auth=credentials) self.pool_manager.headers.update(basic_auth) # type: ignore self.config = config super().__init__(base_url=base_url, dumb=dumb, **kwargs) def _get_url(self, path): if not isinstance(path, str): # urllib3.util.url._encode_invalid_chars() converts the path back # to bytes using the utf-8 codec. path = path.decode("utf-8") return urljoin(self._base_url, path).rstrip("/") + "/" def _http_request(self, url, headers=None, data=None): import urllib3.exceptions req_headers = self.pool_manager.headers.copy() if headers is not None: req_headers.update(headers) req_headers["Pragma"] = "no-cache" try: if data is None: resp = self.pool_manager.request( "GET", url, headers=req_headers, preload_content=False ) else: resp = self.pool_manager.request( "POST", url, headers=req_headers, body=data, preload_content=False ) except urllib3.exceptions.HTTPError as e: raise GitProtocolError(str(e)) from e if resp.status == 404: raise NotGitRepository if resp.status == 401: raise HTTPUnauthorized(resp.headers.get("WWW-Authenticate"), url) if resp.status == 407: raise HTTPProxyUnauthorized(resp.headers.get("Proxy-Authenticate"), url) if resp.status != 200: raise GitProtocolError(f"unexpected http resp {resp.status} for {url}") resp.content_type = resp.headers.get("Content-Type") # Check if geturl() is available (urllib3 version >= 1.23) try: resp_url = resp.geturl() except AttributeError: # get_redirect_location() is available for urllib3 >= 1.1 resp.redirect_location = resp.get_redirect_location() else: resp.redirect_location = resp_url if resp_url != url else "" return resp, _wrap_urllib3_exceptions(resp.read) HttpGitClient = Urllib3HttpGitClient def _win32_url_to_path(parsed) -> str: """Convert a file: URL to a path. https://datatracker.ietf.org/doc/html/rfc8089 """ assert parsed.scheme == "file" _, netloc, path, _, _, _ = parsed if netloc == "localhost" or not netloc: netloc = "" elif ( netloc and len(netloc) >= 2 and netloc[0].isalpha() and netloc[1:2] in (":", ":/") ): # file://C:/foo.bar/baz or file://C://foo.bar//baz netloc = netloc[:2] else: raise NotImplementedError("Non-local file URLs are not supported") from nturl2path import url2pathname return url2pathname(netloc + path) def get_transport_and_path_from_url( url: str, config: Optional[Config] = None, operation: Optional[str] = None, **kwargs ) -> tuple[GitClient, str]: """Obtain a git client from a URL. Args: url: URL to open (a unicode string) config: Optional config object operation: Kind of operation that'll be performed; "pull" or "push" thin_packs: Whether or not thin packs should be retrieved report_activity: Optional callback for reporting transport activity. Returns: Tuple with client instance and relative path. """ if config is not None: url = apply_instead_of(config, url, push=(operation == "push")) return _get_transport_and_path_from_url( url, config=config, operation=operation, **kwargs ) def _get_transport_and_path_from_url(url, config, operation, **kwargs): parsed = urlparse(url) if parsed.scheme == "git": return (TCPGitClient.from_parsedurl(parsed, **kwargs), parsed.path) elif parsed.scheme in ("git+ssh", "ssh"): return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path elif parsed.scheme in ("http", "https"): return ( HttpGitClient.from_parsedurl(parsed, config=config, **kwargs), parsed.path, ) elif parsed.scheme == "file": if sys.platform == "win32" or os.name == "nt": return default_local_git_client_cls(**kwargs), _win32_url_to_path(parsed) return ( default_local_git_client_cls.from_parsedurl(parsed, **kwargs), parsed.path, ) raise ValueError(f"unknown scheme '{parsed.scheme}'") def parse_rsync_url(location: str) -> tuple[Optional[str], str, str]: """Parse a rsync-style URL.""" if ":" in location and "@" not in location: # SSH with no user@, zero or one leading slash. (host, path) = location.split(":", 1) user = None elif ":" in location: # SSH with user@host:foo. user_host, path = location.split(":", 1) if "@" in user_host: user, host = user_host.rsplit("@", 1) else: user = None host = user_host else: raise ValueError("not a valid rsync-style URL") return (user, host, path) def get_transport_and_path( location: str, config: Optional[Config] = None, operation: Optional[str] = None, **kwargs, ) -> tuple[GitClient, str]: """Obtain a git client from a URL. Args: location: URL or path (a string) config: Optional config object operation: Kind of operation that'll be performed; "pull" or "push" thin_packs: Whether or not thin packs should be retrieved report_activity: Optional callback for reporting transport activity. Returns: Tuple with client instance and relative path. """ if config is not None: location = apply_instead_of(config, location, push=(operation == "push")) # First, try to parse it as a URL try: return _get_transport_and_path_from_url( location, config=config, operation=operation, **kwargs ) except ValueError: pass if sys.platform == "win32" and location[0].isalpha() and location[1:3] == ":\\": # Windows local path return default_local_git_client_cls(**kwargs), location try: (username, hostname, path) = parse_rsync_url(location) except ValueError: # Otherwise, assume it's a local path. return default_local_git_client_cls(**kwargs), location else: return SSHGitClient(hostname, username=username, **kwargs), path DEFAULT_GIT_CREDENTIALS_PATHS = [ os.path.expanduser("~/.git-credentials"), get_xdg_config_home_path("git", "credentials"), ] def get_credentials_from_store( scheme, hostname, username=None, fnames=DEFAULT_GIT_CREDENTIALS_PATHS ): for fname in fnames: try: with open(fname, "rb") as f: for line in f: parsed_line = urlparse(line.strip()) if ( parsed_line.scheme == scheme and parsed_line.hostname == hostname and (username is None or parsed_line.username == username) ): return parsed_line.username, parsed_line.password except FileNotFoundError: # If the file doesn't exist, try the next one. continue ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9724476 dulwich-0.22.7/dulwich/cloud/0000755000175100002000000000000014731042565015405 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/cloud/__init__.py0000644000175100002000000000000014731042555017503 0ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/cloud/gcs.py0000644000175100002000000000614214731042555016535 0ustar00runnerdocker# object_store.py -- Object store for git objects # Copyright (C) 2021 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Storage of repositories on GCS.""" import posixpath import tempfile from ..object_store import BucketBasedObjectStore from ..pack import PACK_SPOOL_FILE_MAX_SIZE, Pack, PackData, load_pack_index_file # TODO(jelmer): For performance, read ranges? class GcsObjectStore(BucketBasedObjectStore): def __init__(self, bucket, subpath="") -> None: super().__init__() self.bucket = bucket self.subpath = subpath def __repr__(self) -> str: return f"{type(self).__name__}({self.bucket!r}, subpath={self.subpath!r})" def _remove_pack(self, name) -> None: self.bucket.delete_blobs( [posixpath.join(self.subpath, name) + "." + ext for ext in ["pack", "idx"]] ) def _iter_pack_names(self): packs = {} for blob in self.bucket.list_blobs(prefix=self.subpath): name, ext = posixpath.splitext(posixpath.basename(blob.name)) packs.setdefault(name, set()).add(ext) for name, exts in packs.items(): if exts == {".pack", ".idx"}: yield name def _load_pack_data(self, name): b = self.bucket.blob(posixpath.join(self.subpath, name + ".pack")) f = tempfile.SpooledTemporaryFile(max_size=PACK_SPOOL_FILE_MAX_SIZE) b.download_to_file(f) f.seek(0) return PackData(name + ".pack", f) def _load_pack_index(self, name): b = self.bucket.blob(posixpath.join(self.subpath, name + ".idx")) f = tempfile.SpooledTemporaryFile(max_size=PACK_SPOOL_FILE_MAX_SIZE) b.download_to_file(f) f.seek(0) return load_pack_index_file(name + ".idx", f) def _get_pack(self, name): return Pack.from_lazy_objects( lambda: self._load_pack_data(name), lambda: self._load_pack_index(name) ) def _upload_pack(self, basename, pack_file, index_file) -> None: idxblob = self.bucket.blob(posixpath.join(self.subpath, basename + ".idx")) datablob = self.bucket.blob(posixpath.join(self.subpath, basename + ".pack")) idxblob.upload_from_file(index_file) datablob.upload_from_file(pack_file) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/config.py0000644000175100002000000006127414731042555016127 0ustar00runnerdocker# config.py - Reading and writing Git config files # Copyright (C) 2011-2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Reading and writing Git configuration files. Todo: * preserve formatting when updating configuration files * treat subsection names as case-insensitive for [branch.foo] style subsections """ import os import sys from collections.abc import Iterable, Iterator, KeysView, MutableMapping from contextlib import suppress from typing import ( Any, BinaryIO, Optional, Union, overload, ) from .file import GitFile SENTINEL = object() def lower_key(key): if isinstance(key, (bytes, str)): return key.lower() if isinstance(key, Iterable): return type(key)(map(lower_key, key)) # type: ignore return key class CaseInsensitiveOrderedMultiDict(MutableMapping): def __init__(self) -> None: self._real: list[Any] = [] self._keyed: dict[Any, Any] = {} @classmethod def make(cls, dict_in=None): if isinstance(dict_in, cls): return dict_in out = cls() if dict_in is None: return out if not isinstance(dict_in, MutableMapping): raise TypeError for key, value in dict_in.items(): out[key] = value return out def __len__(self) -> int: return len(self._keyed) def keys(self) -> KeysView[tuple[bytes, ...]]: return self._keyed.keys() def items(self): return iter(self._real) def __iter__(self): return self._keyed.__iter__() def values(self): return self._keyed.values() def __setitem__(self, key, value) -> None: self._real.append((key, value)) self._keyed[lower_key(key)] = value def __delitem__(self, key) -> None: key = lower_key(key) del self._keyed[key] for i, (actual, unused_value) in reversed(list(enumerate(self._real))): if lower_key(actual) == key: del self._real[i] def __getitem__(self, item): return self._keyed[lower_key(item)] def get(self, key, default=SENTINEL): try: return self[key] except KeyError: pass if default is SENTINEL: return type(self)() return default def get_all(self, key): key = lower_key(key) for actual, value in self._real: if lower_key(actual) == key: yield value def setdefault(self, key, default=SENTINEL): try: return self[key] except KeyError: self[key] = self.get(key, default) return self[key] Name = bytes NameLike = Union[bytes, str] Section = tuple[bytes, ...] SectionLike = Union[bytes, str, tuple[Union[bytes, str], ...]] Value = bytes ValueLike = Union[bytes, str] class Config: """A Git configuration.""" def get(self, section: SectionLike, name: NameLike) -> Value: """Retrieve the contents of a configuration setting. Args: section: Tuple with section name and optional subsection name name: Variable name Returns: Contents of the setting Raises: KeyError: if the value is not set """ raise NotImplementedError(self.get) def get_multivar(self, section: SectionLike, name: NameLike) -> Iterator[Value]: """Retrieve the contents of a multivar configuration setting. Args: section: Tuple with section name and optional subsection namee name: Variable name Returns: Contents of the setting as iterable Raises: KeyError: if the value is not set """ raise NotImplementedError(self.get_multivar) @overload def get_boolean( self, section: SectionLike, name: NameLike, default: bool ) -> bool: ... @overload def get_boolean(self, section: SectionLike, name: NameLike) -> Optional[bool]: ... def get_boolean( self, section: SectionLike, name: NameLike, default: Optional[bool] = None ) -> Optional[bool]: """Retrieve a configuration setting as boolean. Args: section: Tuple with section name and optional subsection name name: Name of the setting, including section and possible subsection. Returns: Contents of the setting """ try: value = self.get(section, name) except KeyError: return default if value.lower() == b"true": return True elif value.lower() == b"false": return False raise ValueError(f"not a valid boolean string: {value!r}") def set( self, section: SectionLike, name: NameLike, value: Union[ValueLike, bool] ) -> None: """Set a configuration value. Args: section: Tuple with section name and optional subsection namee name: Name of the configuration value, including section and optional subsection value: value of the setting """ raise NotImplementedError(self.set) def items(self, section: SectionLike) -> Iterator[tuple[Name, Value]]: """Iterate over the configuration pairs for a specific section. Args: section: Tuple with section name and optional subsection namee Returns: Iterator over (name, value) pairs """ raise NotImplementedError(self.items) def sections(self) -> Iterator[Section]: """Iterate over the sections. Returns: Iterator over section tuples """ raise NotImplementedError(self.sections) def has_section(self, name: Section) -> bool: """Check if a specified section exists. Args: name: Name of section to check for Returns: boolean indicating whether the section exists """ return name in self.sections() class ConfigDict(Config, MutableMapping[Section, MutableMapping[Name, Value]]): """Git configuration stored in a dictionary.""" def __init__( self, values: Union[ MutableMapping[Section, MutableMapping[Name, Value]], None ] = None, encoding: Union[str, None] = None, ) -> None: """Create a new ConfigDict.""" if encoding is None: encoding = sys.getdefaultencoding() self.encoding = encoding self._values = CaseInsensitiveOrderedMultiDict.make(values) def __repr__(self) -> str: return f"{self.__class__.__name__}({self._values!r})" def __eq__(self, other: object) -> bool: return isinstance(other, self.__class__) and other._values == self._values def __getitem__(self, key: Section) -> MutableMapping[Name, Value]: return self._values.__getitem__(key) def __setitem__(self, key: Section, value: MutableMapping[Name, Value]) -> None: return self._values.__setitem__(key, value) def __delitem__(self, key: Section) -> None: return self._values.__delitem__(key) def __iter__(self) -> Iterator[Section]: return self._values.__iter__() def __len__(self) -> int: return self._values.__len__() @classmethod def _parse_setting(cls, name: str): parts = name.split(".") if len(parts) == 3: return (parts[0], parts[1], parts[2]) else: return (parts[0], None, parts[1]) def _check_section_and_name( self, section: SectionLike, name: NameLike ) -> tuple[Section, Name]: if not isinstance(section, tuple): section = (section,) checked_section = tuple( [ subsection.encode(self.encoding) if not isinstance(subsection, bytes) else subsection for subsection in section ] ) if not isinstance(name, bytes): name = name.encode(self.encoding) return checked_section, name def get_multivar(self, section: SectionLike, name: NameLike) -> Iterator[Value]: section, name = self._check_section_and_name(section, name) if len(section) > 1: try: return self._values[section].get_all(name) except KeyError: pass return self._values[(section[0],)].get_all(name) def get( # type: ignore[override] self, section: SectionLike, name: NameLike, ) -> Value: section, name = self._check_section_and_name(section, name) if len(section) > 1: try: return self._values[section][name] except KeyError: pass return self._values[(section[0],)][name] def set( self, section: SectionLike, name: NameLike, value: Union[ValueLike, bool], ) -> None: section, name = self._check_section_and_name(section, name) if isinstance(value, bool): value = b"true" if value else b"false" if not isinstance(value, bytes): value = value.encode(self.encoding) self._values.setdefault(section)[name] = value def items( # type: ignore[override] self, section: Section ) -> Iterator[tuple[Name, Value]]: return self._values.get(section).items() def sections(self) -> Iterator[Section]: return self._values.keys() def _format_string(value: bytes) -> bytes: if ( value.startswith((b" ", b"\t")) or value.endswith((b" ", b"\t")) or b"#" in value ): return b'"' + _escape_value(value) + b'"' else: return _escape_value(value) _ESCAPE_TABLE = { ord(b"\\"): ord(b"\\"), ord(b'"'): ord(b'"'), ord(b"n"): ord(b"\n"), ord(b"t"): ord(b"\t"), ord(b"b"): ord(b"\b"), } _COMMENT_CHARS = [ord(b"#"), ord(b";")] _WHITESPACE_CHARS = [ord(b"\t"), ord(b" ")] def _parse_string(value: bytes) -> bytes: value = bytearray(value.strip()) ret = bytearray() whitespace = bytearray() in_quotes = False i = 0 while i < len(value): c = value[i] if c == ord(b"\\"): i += 1 try: v = _ESCAPE_TABLE[value[i]] except IndexError as exc: raise ValueError( f"escape character in {value!r} at {i} before end of string" ) from exc except KeyError as exc: raise ValueError( f"escape character followed by unknown character {value[i]!r} at {i} in {value!r}" ) from exc if whitespace: ret.extend(whitespace) whitespace = bytearray() ret.append(v) elif c == ord(b'"'): in_quotes = not in_quotes elif c in _COMMENT_CHARS and not in_quotes: # the rest of the line is a comment break elif c in _WHITESPACE_CHARS: whitespace.append(c) else: if whitespace: ret.extend(whitespace) whitespace = bytearray() ret.append(c) i += 1 if in_quotes: raise ValueError("missing end quote") return bytes(ret) def _escape_value(value: bytes) -> bytes: """Escape a value.""" value = value.replace(b"\\", b"\\\\") value = value.replace(b"\r", b"\\r") value = value.replace(b"\n", b"\\n") value = value.replace(b"\t", b"\\t") value = value.replace(b'"', b'\\"') return value def _check_variable_name(name: bytes) -> bool: for i in range(len(name)): c = name[i : i + 1] if not c.isalnum() and c != b"-": return False return True def _check_section_name(name: bytes) -> bool: for i in range(len(name)): c = name[i : i + 1] if not c.isalnum() and c not in (b"-", b"."): return False return True def _strip_comments(line: bytes) -> bytes: comment_bytes = {ord(b"#"), ord(b";")} quote = ord(b'"') string_open = False # Normalize line to bytearray for simple 2/3 compatibility for i, character in enumerate(bytearray(line)): # Comment characters outside balanced quotes denote comment start if character == quote: string_open = not string_open elif not string_open and character in comment_bytes: return line[:i] return line def _parse_section_header_line(line: bytes) -> tuple[Section, bytes]: # Parse section header ("[bla]") line = _strip_comments(line).rstrip() in_quotes = False escaped = False for i, c in enumerate(line): if escaped: escaped = False continue if c == ord(b'"'): in_quotes = not in_quotes if c == ord(b"\\"): escaped = True if c == ord(b"]") and not in_quotes: last = i break else: raise ValueError("expected trailing ]") pts = line[1:last].split(b" ", 1) line = line[last + 1 :] section: Section if len(pts) == 2: if pts[1][:1] != b'"' or pts[1][-1:] != b'"': raise ValueError(f"Invalid subsection {pts[1]!r}") else: pts[1] = pts[1][1:-1] if not _check_section_name(pts[0]): raise ValueError(f"invalid section name {pts[0]!r}") section = (pts[0], pts[1]) else: if not _check_section_name(pts[0]): raise ValueError(f"invalid section name {pts[0]!r}") pts = pts[0].split(b".", 1) if len(pts) == 2: section = (pts[0], pts[1]) else: section = (pts[0],) return section, line class ConfigFile(ConfigDict): """A Git configuration file, like .git/config or ~/.gitconfig.""" def __init__( self, values: Union[ MutableMapping[Section, MutableMapping[Name, Value]], None ] = None, encoding: Union[str, None] = None, ) -> None: super().__init__(values=values, encoding=encoding) self.path: Optional[str] = None @classmethod def from_file(cls, f: BinaryIO) -> "ConfigFile": """Read configuration from a file-like object.""" ret = cls() section: Optional[Section] = None setting = None continuation = None for lineno, line in enumerate(f.readlines()): if lineno == 0 and line.startswith(b"\xef\xbb\xbf"): line = line[3:] line = line.lstrip() if setting is None: if len(line) > 0 and line[:1] == b"[": section, line = _parse_section_header_line(line) ret._values.setdefault(section) if _strip_comments(line).strip() == b"": continue if section is None: raise ValueError(f"setting {line!r} without section") try: setting, value = line.split(b"=", 1) except ValueError: setting = line value = b"true" setting = setting.strip() if not _check_variable_name(setting): raise ValueError(f"invalid variable name {setting!r}") if value.endswith(b"\\\n"): continuation = value[:-2] elif value.endswith(b"\\\r\n"): continuation = value[:-3] else: continuation = None value = _parse_string(value) ret._values[section][setting] = value setting = None else: # continuation line if line.endswith(b"\\\n"): continuation += line[:-2] elif line.endswith(b"\\\r\n"): continuation += line[:-3] else: continuation += line value = _parse_string(continuation) ret._values[section][setting] = value continuation = None setting = None return ret @classmethod def from_path(cls, path: str) -> "ConfigFile": """Read configuration from a file on disk.""" with GitFile(path, "rb") as f: ret = cls.from_file(f) ret.path = path return ret def write_to_path(self, path: Optional[str] = None) -> None: """Write configuration to a file on disk.""" if path is None: path = self.path with GitFile(path, "wb") as f: self.write_to_file(f) def write_to_file(self, f: BinaryIO) -> None: """Write configuration to a file-like object.""" for section, values in self._values.items(): try: section_name, subsection_name = section except ValueError: (section_name,) = section subsection_name = None if subsection_name is None: f.write(b"[" + section_name + b"]\n") else: f.write(b"[" + section_name + b' "' + subsection_name + b'"]\n') for key, value in values.items(): value = _format_string(value) f.write(b"\t" + key + b" = " + value + b"\n") def get_xdg_config_home_path(*path_segments): xdg_config_home = os.environ.get( "XDG_CONFIG_HOME", os.path.expanduser("~/.config/"), ) return os.path.join(xdg_config_home, *path_segments) def _find_git_in_win_path(): for exe in ("git.exe", "git.cmd"): for path in os.environ.get("PATH", "").split(";"): if os.path.exists(os.path.join(path, exe)): # in windows native shells (powershell/cmd) exe path is # .../Git/bin/git.exe or .../Git/cmd/git.exe # # in git-bash exe path is .../Git/mingw64/bin/git.exe git_dir, _bin_dir = os.path.split(path) yield git_dir parent_dir, basename = os.path.split(git_dir) if basename == "mingw32" or basename == "mingw64": yield parent_dir break def _find_git_in_win_reg(): import platform import winreg if platform.machine() == "AMD64": subkey = ( "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\" "CurrentVersion\\Uninstall\\Git_is1" ) else: subkey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" "Uninstall\\Git_is1" for key in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE): # type: ignore with suppress(OSError): with winreg.OpenKey(key, subkey) as k: # type: ignore val, typ = winreg.QueryValueEx(k, "InstallLocation") # type: ignore if typ == winreg.REG_SZ: # type: ignore yield val # There is no set standard for system config dirs on windows. We try the # following: # - %PROGRAMDATA%/Git/config - (deprecated) Windows config dir per CGit docs # - %PROGRAMFILES%/Git/etc/gitconfig - Git for Windows (msysgit) config dir # Used if CGit installation (Git/bin/git.exe) is found in PATH in the # system registry def get_win_system_paths(): if "PROGRAMDATA" in os.environ: yield os.path.join(os.environ["PROGRAMDATA"], "Git", "config") for git_dir in _find_git_in_win_path(): yield os.path.join(git_dir, "etc", "gitconfig") for git_dir in _find_git_in_win_reg(): yield os.path.join(git_dir, "etc", "gitconfig") class StackedConfig(Config): """Configuration which reads from multiple config files..""" def __init__( self, backends: list[ConfigFile], writable: Optional[ConfigFile] = None ) -> None: self.backends = backends self.writable = writable def __repr__(self) -> str: return f"<{self.__class__.__name__} for {self.backends!r}>" @classmethod def default(cls) -> "StackedConfig": return cls(cls.default_backends()) @classmethod def default_backends(cls) -> list[ConfigFile]: """Retrieve the default configuration. See git-config(1) for details on the files searched. """ paths = [] paths.append(os.path.expanduser("~/.gitconfig")) paths.append(get_xdg_config_home_path("git", "config")) if "GIT_CONFIG_NOSYSTEM" not in os.environ: paths.append("/etc/gitconfig") if sys.platform == "win32": paths.extend(get_win_system_paths()) backends = [] for path in paths: try: cf = ConfigFile.from_path(path) except FileNotFoundError: continue backends.append(cf) return backends def get(self, section: SectionLike, name: NameLike) -> Value: if not isinstance(section, tuple): section = (section,) for backend in self.backends: try: return backend.get(section, name) except KeyError: pass raise KeyError(name) def get_multivar(self, section: SectionLike, name: NameLike) -> Iterator[Value]: if not isinstance(section, tuple): section = (section,) for backend in self.backends: try: yield from backend.get_multivar(section, name) except KeyError: pass def set( self, section: SectionLike, name: NameLike, value: Union[ValueLike, bool] ) -> None: if self.writable is None: raise NotImplementedError(self.set) return self.writable.set(section, name, value) def sections(self) -> Iterator[Section]: seen = set() for backend in self.backends: for section in backend.sections(): if section not in seen: seen.add(section) yield section def read_submodules(path: str) -> Iterator[tuple[bytes, bytes, bytes]]: """Read a .gitmodules file.""" cfg = ConfigFile.from_path(path) return parse_submodules(cfg) def parse_submodules(config: ConfigFile) -> Iterator[tuple[bytes, bytes, bytes]]: """Parse a gitmodules GitConfig file, returning submodules. Args: config: A `ConfigFile` Returns: list of tuples (submodule path, url, name), where name is quoted part of the section's name. """ for section in config.keys(): section_kind, section_name = section if section_kind == b"submodule": try: sm_path = config.get(section, b"path") sm_url = config.get(section, b"url") yield (sm_path, sm_url, section_name) except KeyError: # If either path or url is missing, just ignore this # submodule entry and move on to the next one. This is # how git itself handles malformed .gitmodule entries. pass def iter_instead_of(config: Config, push: bool = False) -> Iterable[tuple[str, str]]: """Iterate over insteadOf / pushInsteadOf values.""" for section in config.sections(): if section[0] != b"url": continue replacement = section[1] try: needles = list(config.get_multivar(section, "insteadOf")) except KeyError: needles = [] if push: try: needles += list(config.get_multivar(section, "pushInsteadOf")) except KeyError: pass for needle in needles: assert isinstance(needle, bytes) yield needle.decode("utf-8"), replacement.decode("utf-8") def apply_instead_of(config: Config, orig_url: str, push: bool = False) -> str: """Apply insteadOf / pushInsteadOf to a URL.""" longest_needle = "" updated_url = orig_url for needle, replacement in iter_instead_of(config, push): if not orig_url.startswith(needle): continue if len(longest_needle) < len(needle): longest_needle = needle updated_url = replacement + orig_url[len(needle) :] return updated_url ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9724476 dulwich-0.22.7/dulwich/contrib/0000755000175100002000000000000014731042565015737 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/contrib/__init__.py0000644000175100002000000000176614731042555020061 0ustar00runnerdocker# __init__.py -- Contrib module for Dulwich # Copyright (C) 2014 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/contrib/diffstat.py0000755000175100002000000003261114731042555020122 0ustar00runnerdocker#!/usr/bin/env python # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # SPDX-License-Identifier: MIT # Copyright (c) 2020 Kevin B. Hendricks, Stratford Ontario Canada # All rights reserved. # # This diffstat code was extracted and heavily modified from: # # https://github.com/techtonik/python-patch # Under the following license: # # Patch utility to apply unified diffs # Brute-force line-by-line non-recursive parsing # # Copyright (c) 2008-2016 anatoly techtonik # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import re import sys from typing import Optional # only needs to detect git style diffs as this is for # use with dulwich _git_header_name = re.compile(rb"diff --git a/(.*) b/(.*)") _GIT_HEADER_START = b"diff --git a/" _GIT_BINARY_START = b"Binary file" _GIT_RENAMEFROM_START = b"rename from" _GIT_RENAMETO_START = b"rename to" _GIT_CHUNK_START = b"@@" _GIT_ADDED_START = b"+" _GIT_DELETED_START = b"-" _GIT_UNCHANGED_START = b" " # emulate original full Patch class by just extracting # filename and minimal chunk added/deleted information to # properly interface with diffstat routine def _parse_patch( lines: list[bytes], ) -> tuple[list[bytes], list[bool], list[tuple[int, int]]]: """Parse a git style diff or patch to generate diff stats. Args: lines: list of byte string lines from the diff to be parsed Returns: A tuple (names, is_binary, counts) of three lists """ names = [] nametypes = [] counts = [] in_patch_chunk = in_git_header = binaryfile = False currentfile: Optional[bytes] = None added = deleted = 0 for line in lines: if line.startswith(_GIT_HEADER_START): if currentfile is not None: names.append(currentfile) nametypes.append(binaryfile) counts.append((added, deleted)) m = _git_header_name.search(line) assert m currentfile = m.group(2) binaryfile = False added = deleted = 0 in_git_header = True in_patch_chunk = False elif line.startswith(_GIT_BINARY_START) and in_git_header: binaryfile = True in_git_header = False elif line.startswith(_GIT_RENAMEFROM_START) and in_git_header: currentfile = line[12:] elif line.startswith(_GIT_RENAMETO_START) and in_git_header: assert currentfile currentfile += b" => %s" % line[10:] elif line.startswith(_GIT_CHUNK_START) and (in_patch_chunk or in_git_header): in_patch_chunk = True in_git_header = False elif line.startswith(_GIT_ADDED_START) and in_patch_chunk: added += 1 elif line.startswith(_GIT_DELETED_START) and in_patch_chunk: deleted += 1 elif not line.startswith(_GIT_UNCHANGED_START) and in_patch_chunk: in_patch_chunk = False # handle end of input if currentfile is not None: names.append(currentfile) nametypes.append(binaryfile) counts.append((added, deleted)) return names, nametypes, counts # note must all done using bytes not string because on linux filenames # may not be encodable even to utf-8 def diffstat(lines, max_width=80): """Generate summary statistics from a git style diff ala (git diff tag1 tag2 --stat). Args: lines: list of byte string "lines" from the diff to be parsed max_width: maximum line length for generating the summary statistics (default 80) Returns: A byte string that lists the changed files with change counts and histogram. """ names, nametypes, counts = _parse_patch(lines) insert = [] delete = [] namelen = 0 maxdiff = 0 # max changes for any file used for histogram width calc for i, filename in enumerate(names): i, d = counts[i] insert.append(i) delete.append(d) namelen = max(namelen, len(filename)) maxdiff = max(maxdiff, i + d) output = b"" statlen = len(str(maxdiff)) # stats column width for i, n in enumerate(names): binaryfile = nametypes[i] # %-19s | %-4d %s # note b'%d' % namelen is not supported until Python 3.5 # To convert an int to a format width specifier for byte # strings use str(namelen).encode('ascii') format = ( b" %-" + str(namelen).encode("ascii") + b"s | %" + str(statlen).encode("ascii") + b"s %s\n" ) binformat = b" %-" + str(namelen).encode("ascii") + b"s | %s\n" if not binaryfile: hist = b"" # -- calculating histogram -- width = len(format % (b"", b"", b"")) histwidth = max(2, max_width - width) if maxdiff < histwidth: hist = b"+" * insert[i] + b"-" * delete[i] else: iratio = (float(insert[i]) / maxdiff) * histwidth dratio = (float(delete[i]) / maxdiff) * histwidth iwidth = dwidth = 0 # make sure every entry that had actual insertions gets # at least one + if insert[i] > 0: iwidth = int(iratio) if iwidth == 0 and 0 < iratio < 1: iwidth = 1 # make sure every entry that had actual deletions gets # at least one - if delete[i] > 0: dwidth = int(dratio) if dwidth == 0 and 0 < dratio < 1: dwidth = 1 hist = b"+" * int(iwidth) + b"-" * int(dwidth) output += format % ( bytes(names[i]), str(insert[i] + delete[i]).encode("ascii"), hist, ) else: output += binformat % (bytes(names[i]), b"Bin") output += b" %d files changed, %d insertions(+), %d deletions(-)" % ( len(names), sum(insert), sum(delete), ) return output def main() -> int: argv = sys.argv # allow diffstat.py to also be used from the command line if len(sys.argv) > 1: diffpath = argv[1] data = b"" with open(diffpath, "rb") as f: data = f.read() lines = data.split(b"\n") result = diffstat(lines) print(result.decode("utf-8")) return 0 # if no path argument to a diff file is passed in, run # a self test. The test case includes tricky things like # a diff of diff, binary files, renames with further changes # added files and removed files. # All extracted from Sigil-Ebook/Sigil's github repo with # full permission to use under this license. selftest = b""" diff --git a/docs/qt512.7_remove_bad_workaround.patch b/docs/qt512.7_remove_bad_workaround.patch new file mode 100644 index 00000000..64e34192 --- /dev/null +++ b/docs/qt512.7_remove_bad_workaround.patch @@ -0,0 +1,15 @@ +--- qtbase/src/gui/kernel/qwindow.cpp.orig 2019-12-12 09:15:59.000000000 -0500 ++++ qtbase/src/gui/kernel/qwindow.cpp 2020-01-10 10:36:53.000000000 -0500 +@@ -218,12 +218,6 @@ + QGuiApplicationPrivate::window_list.removeAll(this); + if (!QGuiApplicationPrivate::is_app_closing) + QGuiApplicationPrivate::instance()->modalWindowList.removeOne(this); +- +- // focus_window is normally cleared in destroy(), but the window may in +- // some cases end up becoming the focus window again. Clear it again +- // here as a workaround. See QTBUG-75326. +- if (QGuiApplicationPrivate::focus_window == this) +- QGuiApplicationPrivate::focus_window = 0; + } + + void QWindowPrivate::init(QScreen *targetScreen) diff --git a/docs/testplugin_v017.zip b/docs/testplugin_v017.zip new file mode 100644 index 00000000..a4cf4c4c Binary files /dev/null and b/docs/testplugin_v017.zip differ diff --git a/ci_scripts/macgddeploy.py b/ci_scripts/gddeploy.py similarity index 73% rename from ci_scripts/macgddeploy.py rename to ci_scripts/gddeploy.py index a512d075..f9dacd33 100644 --- a/ci_scripts/macgddeploy.py +++ b/ci_scripts/gddeploy.py @@ -1,19 +1,32 @@ #!/usr/bin/env python3 import os +import sys import subprocess import datetime import shutil +import glob gparent = os.path.expandvars('$GDRIVE_DIR') grefresh_token = os.path.expandvars('$GDRIVE_REFRESH_TOKEN') -travis_branch = os.path.expandvars('$TRAVIS_BRANCH') -travis_commit = os.path.expandvars('$TRAVIS_COMMIT') -travis_build_number = os.path.expandvars('$TRAVIS_BUILD_NUMBER') +if sys.platform.lower().startswith('darwin'): + travis_branch = os.path.expandvars('$TRAVIS_BRANCH') + travis_commit = os.path.expandvars('$TRAVIS_COMMIT') + travis_build_number = os.path.expandvars('$TRAVIS_BUILD_NUMBER') + + origfilename = './bin/Sigil.tar.xz' + newfilename = './bin/Sigil-{}-{}-build_num-{}.tar.xz'.format(travis_branch, travis_commit[:7],travis_build_numbe\ r) +else: + appveyor_branch = os.path.expandvars('$APPVEYOR_REPO_BRANCH') + appveyor_commit = os.path.expandvars('$APPVEYOR_REPO_COMMIT') + appveyor_build_number = os.path.expandvars('$APPVEYOR_BUILD_NUMBER') + names = glob.glob('.\\installer\\Sigil-*-Setup.exe') + if not names: + exit(1) + origfilename = names[0] + newfilename = '.\\installer\\Sigil-{}-{}-build_num-{}-Setup.exe'.format(appveyor_branch, appveyor_commit[:7], ap\ pveyor_build_number) -origfilename = './bin/Sigil.tar.xz' -newfilename = './bin/Sigil-{}-{}-build_num-{}.tar.xz'.format(travis_branch, travis_commit[:7],travis_build_number) shutil.copy2(origfilename, newfilename) folder_name = datetime.date.today() diff --git a/docs/qt512.6_backport_009abcd_fix.patch b/docs/qt512.6_backport_009abcd_fix.patch deleted file mode 100644 index f4724347..00000000 --- a/docs/qt512.6_backport_009abcd_fix.patch +++ /dev/null @@ -1,26 +0,0 @@ ---- qtbase/src/widgets/kernel/qwidget.cpp.orig 2019-11-08 10:57:07.000000000 -0500 -+++ qtbase/src/widgets/kernel/qwidget.cpp 2019-12-11 12:32:24.000000000 -0500 -@@ -8934,6 +8934,23 @@ - } - } - switch (event->type()) { -+ case QEvent::PlatformSurface: { -+ // Sync up QWidget's view of whether or not the widget has been created -+ switch (static_cast(event)->surfaceEventType()) { -+ case QPlatformSurfaceEvent::SurfaceCreated: -+ if (!testAttribute(Qt::WA_WState_Created)) -+ create(); -+ break; -+ case QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed: -+ if (testAttribute(Qt::WA_WState_Created)) { -+ // Child windows have already been destroyed by QWindow, -+ // so we skip them here. -+ destroy(false, false); -+ } -+ break; -+ } -+ break; -+ } - case QEvent::MouseMove: - mouseMoveEvent((QMouseEvent*)event); - break; diff --git a/docs/Building_Sigil_On_MacOSX.txt b/docs/Building_Sigil_On_MacOSX.txt index 3b41fd80..64914c78 100644 --- a/docs/Building_Sigil_On_MacOSX.txt +++ b/docs/Building_Sigil_On_MacOSX.txt @@ -113,7 +113,7 @@ install_name_tool -add_rpath @loader_path/../../Frameworks ./bin/Sigil.app/Content # To test if the newly bundled python 3 version of Sigil is working properly ypou can do the following: -1. download testplugin_v014.zip from https://github.com/Sigil-Ebook/Sigil/tree/master/docs +1. download testplugin_v017.zip from https://github.com/Sigil-Ebook/Sigil/tree/master/docs 2. open Sigil.app to the normal nearly blank template epub it generates when opened 3. use Plugins->Manage Plugins menu and make sure the "Use Bundled Python" checkbox is checked 4. use the "Add Plugin" button to navigate to and add testplugin.zip and then hit "Okay" to exit the Manage Plugins Dialog """ testoutput = b""" docs/qt512.7_remove_bad_workaround.patch | 15 ++++++++++++ docs/testplugin_v017.zip | Bin ci_scripts/macgddeploy.py => ci_scripts/gddeploy.py | 0 docs/qt512.6_backport_009abcd_fix.patch | 26 --------------------- docs/Building_Sigil_On_MacOSX.txt | 2 +- 5 files changed, 16 insertions(+), 27 deletions(-)""" # return 0 on success otherwise return -1 result = diffstat(selftest.split(b"\n")) if result == testoutput: print("self test passed") return 0 print("self test failed") print("Received:") print(result.decode("utf-8")) print("Expected:") print(testoutput.decode("utf-8")) return -1 if __name__ == "__main__": sys.exit(main()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/contrib/paramiko_vendor.py0000644000175100002000000000720514731042555021474 0ustar00runnerdocker# paramiko_vendor.py -- paramiko implementation of the SSHVendor interface # Copyright (C) 2013 Aaron O'Mullan # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Paramiko SSH support for Dulwich. To use this implementation as the SSH implementation in Dulwich, override the dulwich.client.get_ssh_vendor attribute: >>> from dulwich import client as _mod_client >>> from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor >>> _mod_client.get_ssh_vendor = ParamikoSSHVendor This implementation is experimental and does not have any tests. """ import paramiko import paramiko.client class _ParamikoWrapper: def __init__(self, client, channel) -> None: self.client = client self.channel = channel # Channel must block self.channel.setblocking(True) @property def stderr(self): return self.channel.makefile_stderr("rb") def can_read(self): return self.channel.recv_ready() def write(self, data): return self.channel.sendall(data) def read(self, n=None): data = self.channel.recv(n) data_len = len(data) # Closed socket if not data: return b"" # Read more if needed if n and data_len < n: diff_len = n - data_len return data + self.read(diff_len) return data def close(self) -> None: self.channel.close() class ParamikoSSHVendor: # http://docs.paramiko.org/en/2.4/api/client.html def __init__(self, **kwargs) -> None: self.kwargs = kwargs def run_command( self, host, command, username=None, port=None, password=None, pkey=None, key_filename=None, protocol_version=None, **kwargs, ): client = paramiko.SSHClient() connection_kwargs = {"hostname": host} connection_kwargs.update(self.kwargs) if username: connection_kwargs["username"] = username if port: connection_kwargs["port"] = port if password: connection_kwargs["password"] = password if pkey: connection_kwargs["pkey"] = pkey if key_filename: connection_kwargs["key_filename"] = key_filename connection_kwargs.update(kwargs) policy = paramiko.client.MissingHostKeyPolicy() client.set_missing_host_key_policy(policy) client.connect(**connection_kwargs) # Open SSH session channel = client.get_transport().open_session() if protocol_version is None or protocol_version == 2: channel.set_environment_variable(name="GIT_PROTOCOL", value="version=2") # Run commands channel.exec_command(command) return _ParamikoWrapper(client, channel) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/contrib/release_robot.py0000644000175100002000000001237114731042555021141 0ustar00runnerdocker# release_robot.py # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Determine last version string from tags. Alternate to `Versioneer `_ using `Dulwich `_ to sort tags by time from newest to oldest. Copy the following into the package ``__init__.py`` module:: from dulwich.contrib.release_robot import get_current_version __version__ = get_current_version() This example assumes the tags have a leading "v" like "v0.3", and that the ``.git`` folder is in a project folder that contains the package folder. EG:: * project | * .git | +-* package | * __init__.py <-- put __version__ here """ import datetime import re import sys import time from ..repo import Repo # CONSTANTS PROJDIR = "." PATTERN = r"[ a-zA-Z_\-]*([\d\.]+[\-\w\.]*)" def get_recent_tags(projdir=PROJDIR): """Get list of tags in order from newest to oldest and their datetimes. Args: projdir: path to ``.git`` Returns: list of tags sorted by commit time from newest to oldest Each tag in the list contains the tag name, commit time, commit id, author and any tag meta. If a tag isn't annotated, then its tag meta is ``None``. Otherwise the tag meta is a tuple containing the tag time, tag id and tag name. Time is in UTC. """ with Repo(projdir) as project: # dulwich repository object refs = project.get_refs() # dictionary of refs and their SHA-1 values tags = {} # empty dictionary to hold tags, commits and datetimes # iterate over refs in repository for key, value in refs.items(): key = key.decode("utf-8") # compatible with Python-3 obj = project.get_object(value) # dulwich object from SHA-1 # don't just check if object is "tag" b/c it could be a "commit" # instead check if "tags" is in the ref-name if "tags" not in key: # skip ref if not a tag continue # strip the leading text from refs to get "tag name" _, tag = key.rsplit("/", 1) # check if tag object is "commit" or "tag" pointing to a "commit" try: commit = obj.object # a tuple (commit class, commit id) except AttributeError: commit = obj tag_meta = None else: tag_meta = ( datetime.datetime(*time.gmtime(obj.tag_time)[:6]), obj.id.decode("utf-8"), obj.name.decode("utf-8"), ) # compatible with Python-3 commit = project.get_object(commit[1]) # commit object # get tag commit datetime, but dulwich returns seconds since # beginning of epoch, so use Python time module to convert it to # timetuple then convert to datetime tags[tag] = [ datetime.datetime(*time.gmtime(commit.commit_time)[:6]), commit.id.decode("utf-8"), commit.author.decode("utf-8"), tag_meta, ] # compatible with Python-3 # return list of tags sorted by their datetimes from newest to oldest return sorted(tags.items(), key=lambda tag: tag[1][0], reverse=True) def get_current_version(projdir=PROJDIR, pattern=PATTERN, logger=None): """Return the most recent tag, using an options regular expression pattern. The default pattern will strip any characters preceding the first semantic version. *EG*: "Release-0.2.1-rc.1" will be come "0.2.1-rc.1". If no match is found, then the most recent tag is return without modification. Args: projdir: path to ``.git`` pattern: regular expression pattern with group that matches version logger: a Python logging instance to capture exception Returns: tag matching first group in regular expression pattern """ tags = get_recent_tags(projdir) try: tag = tags[0][0] except IndexError: return matches = re.match(pattern, tag) try: current_version = matches.group(1) except (IndexError, AttributeError) as err: if logger: logger.exception(err) return tag return current_version if __name__ == "__main__": if len(sys.argv) > 1: _PROJDIR = sys.argv[1] else: _PROJDIR = PROJDIR print(get_current_version(projdir=_PROJDIR)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/contrib/requests_vendor.py0000644000175100002000000001122614731042555021542 0ustar00runnerdocker# requests_vendor.py -- requests implementation of the AbstractHttpGitClient interface # Copyright (C) 2022 Eden Shalit # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. """Requests HTTP client support for Dulwich. To use this implementation as the HTTP implementation in Dulwich, override the dulwich.client.HttpGitClient attribute: >>> from dulwich import client as _mod_client >>> from dulwich.contrib.requests_vendor import RequestsHttpGitClient >>> _mod_client.HttpGitClient = RequestsHttpGitClient This implementation is experimental and does not have any tests. """ from io import BytesIO from requests import Session from ..client import ( AbstractHttpGitClient, HTTPProxyUnauthorized, HTTPUnauthorized, default_user_agent_string, ) from ..errors import GitProtocolError, NotGitRepository class RequestsHttpGitClient(AbstractHttpGitClient): def __init__( self, base_url, dumb=None, config=None, username=None, password=None, **kwargs ) -> None: self._username = username self._password = password self.session = get_session(config) if username is not None: self.session.auth = (username, password) super().__init__(base_url=base_url, dumb=dumb, **kwargs) def _http_request(self, url, headers=None, data=None, allow_compression=False): req_headers = self.session.headers.copy() if headers is not None: req_headers.update(headers) if allow_compression: req_headers["Accept-Encoding"] = "gzip" else: req_headers["Accept-Encoding"] = "identity" if data: resp = self.session.post(url, headers=req_headers, data=data) else: resp = self.session.get(url, headers=req_headers) if resp.status_code == 404: raise NotGitRepository if resp.status_code == 401: raise HTTPUnauthorized(resp.headers.get("WWW-Authenticate"), url) if resp.status_code == 407: raise HTTPProxyUnauthorized(resp.headers.get("Proxy-Authenticate"), url) if resp.status_code != 200: raise GitProtocolError(f"unexpected http resp {resp.status_code} for {url}") # Add required fields as stated in AbstractHttpGitClient._http_request resp.content_type = resp.headers.get("Content-Type") resp.redirect_location = "" if resp.history: resp.redirect_location = resp.url read = BytesIO(resp.content).read return resp, read def get_session(config): session = Session() session.headers.update({"Pragma": "no-cache"}) proxy_server = user_agent = ca_certs = ssl_verify = None if config is not None: try: proxy_server = config.get(b"http", b"proxy") if isinstance(proxy_server, bytes): proxy_server = proxy_server.decode() except KeyError: pass try: user_agent = config.get(b"http", b"useragent") if isinstance(user_agent, bytes): user_agent = user_agent.decode() except KeyError: pass try: ssl_verify = config.get_boolean(b"http", b"sslVerify") except KeyError: ssl_verify = True try: ca_certs = config.get(b"http", b"sslCAInfo") if isinstance(ca_certs, bytes): ca_certs = ca_certs.decode() except KeyError: ca_certs = None if user_agent is None: user_agent = default_user_agent_string() session.headers.update({"User-agent": user_agent}) if ca_certs: session.verify = ca_certs elif ssl_verify is False: session.verify = ssl_verify if proxy_server: session.proxies.update({"http": proxy_server, "https": proxy_server}) return session ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/contrib/swift.py0000644000175100002000000010134314731042555017446 0ustar00runnerdocker# swift.py -- Repo implementation atop OpenStack SWIFT # Copyright (C) 2013 eNovance SAS # # Author: Fabien Boucher # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Repo implementation atop OpenStack SWIFT.""" # TODO: Refactor to share more code with dulwich/repo.py. # TODO(fbo): Second attempt to _send() must be notified via real log # TODO(fbo): More logs for operations import json import os import posixpath import stat import sys import tempfile import urllib.parse as urlparse import zlib from configparser import ConfigParser from io import BytesIO from typing import Optional from geventhttpclient import HTTPClient from ..greenthreads import GreenThreadsMissingObjectFinder from ..lru_cache import LRUSizeCache from ..object_store import INFODIR, PACKDIR, PackBasedObjectStore from ..objects import S_ISGITLINK, Blob, Commit, Tag, Tree from ..pack import ( Pack, PackData, PackIndexer, PackStreamCopier, _compute_object_size, compute_file_sha, iter_sha1, load_pack_index_file, read_pack_header, unpack_object, write_pack_header, write_pack_index_v2, write_pack_object, ) from ..protocol import TCP_GIT_PORT from ..refs import InfoRefsContainer, read_info_refs, split_peeled_refs, write_info_refs from ..repo import OBJECTDIR, BaseRepo from ..server import Backend, TCPGitServer """ # Configuration file sample [swift] # Authentication URL (Keystone or Swift) auth_url = http://127.0.0.1:5000/v2.0 # Authentication version to use auth_ver = 2 # The tenant and username separated by a semicolon username = admin;admin # The user password password = pass # The Object storage region to use (auth v2) (Default RegionOne) region_name = RegionOne # The Object storage endpoint URL to use (auth v2) (Default internalURL) endpoint_type = internalURL # Concurrency to use for parallel tasks (Default 10) concurrency = 10 # Size of the HTTP pool (Default 10) http_pool_length = 10 # Timeout delay for HTTP connections (Default 20) http_timeout = 20 # Chunk size to read from pack (Bytes) (Default 12228) chunk_length = 12228 # Cache size (MBytes) (Default 20) cache_length = 20 """ class PackInfoMissingObjectFinder(GreenThreadsMissingObjectFinder): def next(self): while True: if not self.objects_to_send: return None (sha, name, leaf) = self.objects_to_send.pop() if sha not in self.sha_done: break if not leaf: info = self.object_store.pack_info_get(sha) if info[0] == Commit.type_num: self.add_todo([(info[2], "", False)]) elif info[0] == Tree.type_num: self.add_todo([tuple(i) for i in info[1]]) elif info[0] == Tag.type_num: self.add_todo([(info[1], None, False)]) if sha in self._tagged: self.add_todo([(self._tagged[sha], None, True)]) self.sha_done.add(sha) self.progress(f"counting objects: {len(self.sha_done)}\r") return (sha, name) def load_conf(path=None, file=None): """Load configuration in global var CONF. Args: path: The path to the configuration file file: If provided read instead the file like object """ conf = ConfigParser() if file: try: conf.read_file(file, path) except AttributeError: # read_file only exists in Python3 conf.readfp(file) return conf confpath = None if not path: try: confpath = os.environ["DULWICH_SWIFT_CFG"] except KeyError as exc: raise Exception("You need to specify a configuration file") from exc else: confpath = path if not os.path.isfile(confpath): raise Exception(f"Unable to read configuration file {confpath}") conf.read(confpath) return conf def swift_load_pack_index(scon, filename): """Read a pack index file from Swift. Args: scon: a `SwiftConnector` instance filename: Path to the index file objectise Returns: a `PackIndexer` instance """ with scon.get_object(filename) as f: return load_pack_index_file(filename, f) def pack_info_create(pack_data, pack_index): pack = Pack.from_objects(pack_data, pack_index) info = {} for obj in pack.iterobjects(): # Commit if obj.type_num == Commit.type_num: info[obj.id] = (obj.type_num, obj.parents, obj.tree) # Tree elif obj.type_num == Tree.type_num: shas = [ (s, n, not stat.S_ISDIR(m)) for n, m, s in obj.items() if not S_ISGITLINK(m) ] info[obj.id] = (obj.type_num, shas) # Blob elif obj.type_num == Blob.type_num: info[obj.id] = None # Tag elif obj.type_num == Tag.type_num: info[obj.id] = (obj.type_num, obj.object[1]) return zlib.compress(json.dumps(info)) def load_pack_info(filename, scon=None, file=None): if not file: f = scon.get_object(filename) else: f = file if not f: return None try: return json.loads(zlib.decompress(f.read())) finally: f.close() class SwiftException(Exception): pass class SwiftConnector: """A Connector to swift that manage authentication and errors catching.""" def __init__(self, root, conf) -> None: """Initialize a SwiftConnector. Args: root: The swift container that will act as Git bare repository conf: A ConfigParser Object """ self.conf = conf self.auth_ver = self.conf.get("swift", "auth_ver") if self.auth_ver not in ["1", "2"]: raise NotImplementedError("Wrong authentication version use either 1 or 2") self.auth_url = self.conf.get("swift", "auth_url") self.user = self.conf.get("swift", "username") self.password = self.conf.get("swift", "password") self.concurrency = self.conf.getint("swift", "concurrency") or 10 self.http_timeout = self.conf.getint("swift", "http_timeout") or 20 self.http_pool_length = self.conf.getint("swift", "http_pool_length") or 10 self.region_name = self.conf.get("swift", "region_name") or "RegionOne" self.endpoint_type = self.conf.get("swift", "endpoint_type") or "internalURL" self.cache_length = self.conf.getint("swift", "cache_length") or 20 self.chunk_length = self.conf.getint("swift", "chunk_length") or 12228 self.root = root block_size = 1024 * 12 # 12KB if self.auth_ver == "1": self.storage_url, self.token = self.swift_auth_v1() else: self.storage_url, self.token = self.swift_auth_v2() token_header = {"X-Auth-Token": str(self.token)} self.httpclient = HTTPClient.from_url( str(self.storage_url), concurrency=self.http_pool_length, block_size=block_size, connection_timeout=self.http_timeout, network_timeout=self.http_timeout, headers=token_header, ) self.base_path = str( posixpath.join(urlparse.urlparse(self.storage_url).path, self.root) ) def swift_auth_v1(self): self.user = self.user.replace(";", ":") auth_httpclient = HTTPClient.from_url( self.auth_url, connection_timeout=self.http_timeout, network_timeout=self.http_timeout, ) headers = {"X-Auth-User": self.user, "X-Auth-Key": self.password} path = urlparse.urlparse(self.auth_url).path ret = auth_httpclient.request("GET", path, headers=headers) # Should do something with redirections (301 in my case) if ret.status_code < 200 or ret.status_code >= 300: raise SwiftException( "AUTH v1.0 request failed on " + f"{self.auth_url} with error code {ret.status_code} ({ret.items()!s})" ) storage_url = ret["X-Storage-Url"] token = ret["X-Auth-Token"] return storage_url, token def swift_auth_v2(self): self.tenant, self.user = self.user.split(";") auth_dict = {} auth_dict["auth"] = { "passwordCredentials": { "username": self.user, "password": self.password, }, "tenantName": self.tenant, } auth_json = json.dumps(auth_dict) headers = {"Content-Type": "application/json"} auth_httpclient = HTTPClient.from_url( self.auth_url, connection_timeout=self.http_timeout, network_timeout=self.http_timeout, ) path = urlparse.urlparse(self.auth_url).path if not path.endswith("tokens"): path = posixpath.join(path, "tokens") ret = auth_httpclient.request("POST", path, body=auth_json, headers=headers) if ret.status_code < 200 or ret.status_code >= 300: raise SwiftException( "AUTH v2.0 request failed on " + f"{str(auth_httpclient.get_base_url()) + path} with error code {ret.status_code} ({ret.items()!s})" ) auth_ret_json = json.loads(ret.read()) token = auth_ret_json["access"]["token"]["id"] catalogs = auth_ret_json["access"]["serviceCatalog"] object_store = next( o_store for o_store in catalogs if o_store["type"] == "object-store" ) endpoints = object_store["endpoints"] endpoint = next( endp for endp in endpoints if endp["region"] == self.region_name ) return endpoint[self.endpoint_type], token def test_root_exists(self) -> Optional[bool]: """Check that Swift container exist. Returns: True if exist or None it not """ ret = self.httpclient.request("HEAD", self.base_path) if ret.status_code == 404: return None if ret.status_code < 200 or ret.status_code > 300: raise SwiftException( f"HEAD request failed with error code {ret.status_code}" ) return True def create_root(self) -> None: """Create the Swift container. Raises: SwiftException: if unable to create """ if not self.test_root_exists(): ret = self.httpclient.request("PUT", self.base_path) if ret.status_code < 200 or ret.status_code > 300: raise SwiftException( f"PUT request failed with error code {ret.status_code}" ) def get_container_objects(self): """Retrieve objects list in a container. Returns: A list of dict that describe objects or None if container does not exist """ qs = "?format=json" path = self.base_path + qs ret = self.httpclient.request("GET", path) if ret.status_code == 404: return None if ret.status_code < 200 or ret.status_code > 300: raise SwiftException( f"GET request failed with error code {ret.status_code}" ) content = ret.read() return json.loads(content) def get_object_stat(self, name): """Retrieve object stat. Args: name: The object name Returns: A dict that describe the object or None if object does not exist """ path = self.base_path + "/" + name ret = self.httpclient.request("HEAD", path) if ret.status_code == 404: return None if ret.status_code < 200 or ret.status_code > 300: raise SwiftException( f"HEAD request failed with error code {ret.status_code}" ) resp_headers = {} for header, value in ret.items(): resp_headers[header.lower()] = value return resp_headers def put_object(self, name, content) -> None: """Put an object. Args: name: The object name content: A file object Raises: SwiftException: if unable to create """ content.seek(0) data = content.read() path = self.base_path + "/" + name headers = {"Content-Length": str(len(data))} def _send(): ret = self.httpclient.request("PUT", path, body=data, headers=headers) return ret try: # Sometime got Broken Pipe - Dirty workaround ret = _send() except Exception: # Second attempt work ret = _send() if ret.status_code < 200 or ret.status_code > 300: raise SwiftException( f"PUT request failed with error code {ret.status_code}" ) def get_object(self, name, range=None): """Retrieve an object. Args: name: The object name range: A string range like "0-10" to retrieve specified bytes in object content Returns: A file like instance or bytestring if range is specified """ headers = {} if range: headers["Range"] = f"bytes={range}" path = self.base_path + "/" + name ret = self.httpclient.request("GET", path, headers=headers) if ret.status_code == 404: return None if ret.status_code < 200 or ret.status_code > 300: raise SwiftException( f"GET request failed with error code {ret.status_code}" ) content = ret.read() if range: return content return BytesIO(content) def del_object(self, name) -> None: """Delete an object. Args: name: The object name Raises: SwiftException: if unable to delete """ path = self.base_path + "/" + name ret = self.httpclient.request("DELETE", path) if ret.status_code < 200 or ret.status_code > 300: raise SwiftException( f"DELETE request failed with error code {ret.status_code}" ) def del_root(self) -> None: """Delete the root container by removing container content. Raises: SwiftException: if unable to delete """ for obj in self.get_container_objects(): self.del_object(obj["name"]) ret = self.httpclient.request("DELETE", self.base_path) if ret.status_code < 200 or ret.status_code > 300: raise SwiftException( f"DELETE request failed with error code {ret.status_code}" ) class SwiftPackReader: """A SwiftPackReader that mimic read and sync method. The reader allows to read a specified amount of bytes from a given offset of a Swift object. A read offset is kept internally. The reader will read from Swift a specified amount of data to complete its internal buffer. chunk_length specify the amount of data to read from Swift. """ def __init__(self, scon, filename, pack_length) -> None: """Initialize a SwiftPackReader. Args: scon: a `SwiftConnector` instance filename: the pack filename pack_length: The size of the pack object """ self.scon = scon self.filename = filename self.pack_length = pack_length self.offset = 0 self.base_offset = 0 self.buff = b"" self.buff_length = self.scon.chunk_length def _read(self, more=False) -> None: if more: self.buff_length = self.buff_length * 2 offset = self.base_offset r = min(self.base_offset + self.buff_length, self.pack_length) ret = self.scon.get_object(self.filename, range=f"{offset}-{r}") self.buff = ret def read(self, length): """Read a specified amount of Bytes form the pack object. Args: length: amount of bytes to read Returns: a bytestring """ end = self.offset + length if self.base_offset + end > self.pack_length: data = self.buff[self.offset :] self.offset = end return data if end > len(self.buff): # Need to read more from swift self._read(more=True) return self.read(length) data = self.buff[self.offset : end] self.offset = end return data def seek(self, offset) -> None: """Seek to a specified offset. Args: offset: the offset to seek to """ self.base_offset = offset self._read() self.offset = 0 def read_checksum(self): """Read the checksum from the pack. Returns: the checksum bytestring """ return self.scon.get_object(self.filename, range="-20") class SwiftPackData(PackData): """The data contained in a packfile. We use the SwiftPackReader to read bytes from packs stored in Swift using the Range header feature of Swift. """ def __init__(self, scon, filename) -> None: """Initialize a SwiftPackReader. Args: scon: a `SwiftConnector` instance filename: the pack filename """ self.scon = scon self._filename = filename self._header_size = 12 headers = self.scon.get_object_stat(self._filename) self.pack_length = int(headers["content-length"]) pack_reader = SwiftPackReader(self.scon, self._filename, self.pack_length) (version, self._num_objects) = read_pack_header(pack_reader.read) self._offset_cache = LRUSizeCache( 1024 * 1024 * self.scon.cache_length, compute_size=_compute_object_size, ) self.pack = None def get_object_at(self, offset): if offset in self._offset_cache: return self._offset_cache[offset] assert offset >= self._header_size pack_reader = SwiftPackReader(self.scon, self._filename, self.pack_length) pack_reader.seek(offset) unpacked, _ = unpack_object(pack_reader.read) return (unpacked.pack_type_num, unpacked._obj()) def get_stored_checksum(self): pack_reader = SwiftPackReader(self.scon, self._filename, self.pack_length) return pack_reader.read_checksum() def close(self) -> None: pass class SwiftPack(Pack): """A Git pack object. Same implementation as pack.Pack except that _idx_load and _data_load are bounded to Swift version of load_pack_index and PackData. """ def __init__(self, *args, **kwargs) -> None: self.scon = kwargs["scon"] del kwargs["scon"] super().__init__(*args, **kwargs) self._pack_info_path = self._basename + ".info" self._pack_info = None self._pack_info_load = lambda: load_pack_info(self._pack_info_path, self.scon) self._idx_load = lambda: swift_load_pack_index(self.scon, self._idx_path) self._data_load = lambda: SwiftPackData(self.scon, self._data_path) @property def pack_info(self): """The pack data object being used.""" if self._pack_info is None: self._pack_info = self._pack_info_load() return self._pack_info class SwiftObjectStore(PackBasedObjectStore): """A Swift Object Store. Allow to manage a bare Git repository from Openstack Swift. This object store only supports pack files and not loose objects. """ def __init__(self, scon) -> None: """Open a Swift object store. Args: scon: A `SwiftConnector` instance """ super().__init__() self.scon = scon self.root = self.scon.root self.pack_dir = posixpath.join(OBJECTDIR, PACKDIR) self._alternates = None def _update_pack_cache(self): objects = self.scon.get_container_objects() pack_files = [ o["name"].replace(".pack", "") for o in objects if o["name"].endswith(".pack") ] ret = [] for basename in pack_files: pack = SwiftPack(basename, scon=self.scon) self._pack_cache[basename] = pack ret.append(pack) return ret def _iter_loose_objects(self): """Loose objects are not supported by this repository.""" return [] def pack_info_get(self, sha): for pack in self.packs: if sha in pack: return pack.pack_info[sha] def _collect_ancestors(self, heads, common=set()): def _find_parents(commit): for pack in self.packs: if commit in pack: try: parents = pack.pack_info[commit][1] except KeyError: # Seems to have no parents return [] return parents bases = set() commits = set() queue = [] queue.extend(heads) while queue: e = queue.pop(0) if e in common: bases.add(e) elif e not in commits: commits.add(e) parents = _find_parents(e) queue.extend(parents) return (commits, bases) def add_pack(self): """Add a new pack to this object store. Returns: Fileobject to write to and a commit function to call when the pack is finished. """ f = BytesIO() def commit(): f.seek(0) pack = PackData(file=f, filename="") entries = pack.sorted_entries() if entries: basename = posixpath.join( self.pack_dir, f"pack-{iter_sha1(entry[0] for entry in entries)}", ) index = BytesIO() write_pack_index_v2(index, entries, pack.get_stored_checksum()) self.scon.put_object(basename + ".pack", f) f.close() self.scon.put_object(basename + ".idx", index) index.close() final_pack = SwiftPack(basename, scon=self.scon) final_pack.check_length_and_checksum() self._add_cached_pack(basename, final_pack) return final_pack else: return None def abort() -> None: pass return f, commit, abort def add_object(self, obj) -> None: self.add_objects( [ (obj, None), ] ) def _pack_cache_stale(self) -> bool: return False def _get_loose_object(self, sha) -> None: return None def add_thin_pack(self, read_all, read_some): """Read a thin pack. Read it from a stream and complete it in a temporary file. Then the pack and the corresponding index file are uploaded to Swift. """ fd, path = tempfile.mkstemp(prefix="tmp_pack_") f = os.fdopen(fd, "w+b") try: indexer = PackIndexer(f, resolve_ext_ref=self.get_raw) copier = PackStreamCopier(read_all, read_some, f, delta_iter=indexer) copier.verify() return self._complete_thin_pack(f, path, copier, indexer) finally: f.close() os.unlink(path) def _complete_thin_pack(self, f, path, copier, indexer): entries = list(indexer) # Update the header with the new number of objects. f.seek(0) write_pack_header(f, len(entries) + len(indexer.ext_refs())) # Must flush before reading (http://bugs.python.org/issue3207) f.flush() # Rescan the rest of the pack, computing the SHA with the new header. new_sha = compute_file_sha(f, end_ofs=-20) # Must reposition before writing (http://bugs.python.org/issue3207) f.seek(0, os.SEEK_CUR) # Complete the pack. for ext_sha in indexer.ext_refs(): assert len(ext_sha) == 20 type_num, data = self.get_raw(ext_sha) offset = f.tell() crc32 = write_pack_object(f, type_num, data, sha=new_sha) entries.append((ext_sha, offset, crc32)) pack_sha = new_sha.digest() f.write(pack_sha) f.flush() # Move the pack in. entries.sort() pack_base_name = posixpath.join( self.pack_dir, "pack-" + os.fsdecode(iter_sha1(e[0] for e in entries)), ) self.scon.put_object(pack_base_name + ".pack", f) # Write the index. filename = pack_base_name + ".idx" index_file = BytesIO() write_pack_index_v2(index_file, entries, pack_sha) self.scon.put_object(filename, index_file) # Write pack info. f.seek(0) pack_data = PackData(filename="", file=f) index_file.seek(0) pack_index = load_pack_index_file("", index_file) serialized_pack_info = pack_info_create(pack_data, pack_index) f.close() index_file.close() pack_info_file = BytesIO(serialized_pack_info) filename = pack_base_name + ".info" self.scon.put_object(filename, pack_info_file) pack_info_file.close() # Add the pack to the store and return it. final_pack = SwiftPack(pack_base_name, scon=self.scon) final_pack.check_length_and_checksum() self._add_cached_pack(pack_base_name, final_pack) return final_pack class SwiftInfoRefsContainer(InfoRefsContainer): """Manage references in info/refs object.""" def __init__(self, scon, store) -> None: self.scon = scon self.filename = "info/refs" self.store = store f = self.scon.get_object(self.filename) if not f: f = BytesIO(b"") super().__init__(f) def _load_check_ref(self, name, old_ref): self._check_refname(name) f = self.scon.get_object(self.filename) if not f: return {} refs = read_info_refs(f) (refs, peeled) = split_peeled_refs(refs) if old_ref is not None: if refs[name] != old_ref: return False return refs def _write_refs(self, refs) -> None: f = BytesIO() f.writelines(write_info_refs(refs, self.store)) self.scon.put_object(self.filename, f) def set_if_equals( self, name, old_ref, new_ref, committer=None, timestamp=None, timezone=None, message=None, ) -> bool: """Set a refname to new_ref only if it currently equals old_ref.""" if name == "HEAD": return True refs = self._load_check_ref(name, old_ref) if not isinstance(refs, dict): return False refs[name] = new_ref self._write_refs(refs) self._refs[name] = new_ref return True def remove_if_equals( self, name, old_ref, committer=None, timestamp=None, timezone=None, message=None ) -> bool: """Remove a refname only if it currently equals old_ref.""" if name == "HEAD": return True refs = self._load_check_ref(name, old_ref) if not isinstance(refs, dict): return False del refs[name] self._write_refs(refs) del self._refs[name] return True def allkeys(self): try: self._refs["HEAD"] = self._refs["refs/heads/master"] except KeyError: pass return self._refs.keys() class SwiftRepo(BaseRepo): def __init__(self, root, conf) -> None: """Init a Git bare Repository on top of a Swift container. References are managed in info/refs objects by `SwiftInfoRefsContainer`. The root attribute is the Swift container that contain the Git bare repository. Args: root: The container which contains the bare repo conf: A ConfigParser object """ self.root = root.lstrip("/") self.conf = conf self.scon = SwiftConnector(self.root, self.conf) objects = self.scon.get_container_objects() if not objects: raise Exception(f"There is not any GIT repo here : {self.root}") objects = [o["name"].split("/")[0] for o in objects] if OBJECTDIR not in objects: raise Exception(f"This repository ({self.root}) is not bare.") self.bare = True self._controldir = self.root object_store = SwiftObjectStore(self.scon) refs = SwiftInfoRefsContainer(self.scon, object_store) BaseRepo.__init__(self, object_store, refs) def _determine_file_mode(self) -> bool: """Probe the file-system to determine whether permissions can be trusted. Returns: True if permissions can be trusted, False otherwise. """ return False def _put_named_file(self, filename, contents) -> None: """Put an object in a Swift container. Args: filename: the path to the object to put on Swift contents: the content as bytestring """ with BytesIO() as f: f.write(contents) self.scon.put_object(filename, f) @classmethod def init_bare(cls, scon, conf): """Create a new bare repository. Args: scon: a `SwiftConnector` instance conf: a ConfigParser object Returns: a `SwiftRepo` instance """ scon.create_root() for obj in [ posixpath.join(OBJECTDIR, PACKDIR), posixpath.join(INFODIR, "refs"), ]: scon.put_object(obj, BytesIO(b"")) ret = cls(scon.root, conf) ret._init_files(True) return ret class SwiftSystemBackend(Backend): def __init__(self, logger, conf) -> None: self.conf = conf self.logger = logger def open_repository(self, path): self.logger.info("opening repository at %s", path) return SwiftRepo(path, self.conf) def cmd_daemon(args) -> None: """Entry point for starting a TCP git server.""" import optparse parser = optparse.OptionParser() parser.add_option( "-l", "--listen_address", dest="listen_address", default="127.0.0.1", help="Binding IP address.", ) parser.add_option( "-p", "--port", dest="port", type=int, default=TCP_GIT_PORT, help="Binding TCP port.", ) parser.add_option( "-c", "--swift_config", dest="swift_config", default="", help="Path to the configuration file for Swift backend.", ) options, args = parser.parse_args(args) try: import gevent import geventhttpclient # noqa: F401 except ImportError: print( "gevent and geventhttpclient libraries are mandatory " " for use the Swift backend." ) sys.exit(1) import gevent.monkey gevent.monkey.patch_socket() from dulwich import log_utils logger = log_utils.getLogger(__name__) conf = load_conf(options.swift_config) backend = SwiftSystemBackend(logger, conf) log_utils.default_logging_config() server = TCPGitServer(backend, options.listen_address, port=options.port) server.serve_forever() def cmd_init(args) -> None: import optparse parser = optparse.OptionParser() parser.add_option( "-c", "--swift_config", dest="swift_config", default="", help="Path to the configuration file for Swift backend.", ) options, args = parser.parse_args(args) conf = load_conf(options.swift_config) if args == []: parser.error("missing repository name") repo = args[0] scon = SwiftConnector(repo, conf) SwiftRepo.init_bare(scon, conf) def main(argv=sys.argv) -> None: commands = { "init": cmd_init, "daemon": cmd_daemon, } if len(sys.argv) < 2: print( "Usage: {} <{}> [OPTIONS...]".format(sys.argv[0], "|".join(commands.keys())) ) sys.exit(1) cmd = sys.argv[1] if cmd not in commands: print(f"No such subcommand: {cmd}") sys.exit(1) commands[cmd](sys.argv[2:]) if __name__ == "__main__": main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/credentials.py0000644000175100002000000000637114731042555017154 0ustar00runnerdocker# credentials.py -- support for git credential helpers # Copyright (C) 2022 Daniele Trifirò # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Support for git credential helpers. https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage """ import sys from collections.abc import Iterator from typing import Optional from urllib.parse import ParseResult, urlparse from .config import ConfigDict, SectionLike def match_urls(url: ParseResult, url_prefix: ParseResult) -> bool: base_match = ( url.scheme == url_prefix.scheme and url.hostname == url_prefix.hostname and url.port == url_prefix.port ) user_match = url.username == url_prefix.username if url_prefix.username else True path_match = url.path.rstrip("/").startswith(url_prefix.path.rstrip()) return base_match and user_match and path_match def match_partial_url(valid_url: ParseResult, partial_url: str) -> bool: """Matches a parsed url with a partial url (no scheme/netloc).""" if "://" not in partial_url: parsed = urlparse("scheme://" + partial_url) else: parsed = urlparse(partial_url) if valid_url.scheme != parsed.scheme: return False if any( ( (parsed.hostname and valid_url.hostname != parsed.hostname), (parsed.username and valid_url.username != parsed.username), (parsed.port and valid_url.port != parsed.port), (parsed.path and parsed.path.rstrip("/") != valid_url.path.rstrip("/")), ), ): return False return True def urlmatch_credential_sections( config: ConfigDict, url: Optional[str] ) -> Iterator[SectionLike]: """Returns credential sections from the config which match the given URL.""" encoding = config.encoding or sys.getdefaultencoding() parsed_url = urlparse(url or "") for config_section in config.sections(): if config_section[0] != b"credential": continue if len(config_section) < 2: yield config_section continue config_url = config_section[1].decode(encoding) parsed_config_url = urlparse(config_url) if parsed_config_url.scheme and parsed_config_url.netloc: is_match = match_urls(parsed_url, parsed_config_url) else: is_match = match_partial_url(parsed_url, config_url) if is_match: yield config_section ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/diff_tree.py0000644000175100002000000005544014731042555016607 0ustar00runnerdocker# diff_tree.py -- Utilities for diffing files and trees. # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Utilities for diffing files and trees.""" import stat from collections import defaultdict, namedtuple from io import BytesIO from itertools import chain from typing import Optional from .object_store import BaseObjectStore from .objects import S_ISGITLINK, ObjectID, ShaFile, Tree, TreeEntry # TreeChange type constants. CHANGE_ADD = "add" CHANGE_MODIFY = "modify" CHANGE_DELETE = "delete" CHANGE_RENAME = "rename" CHANGE_COPY = "copy" CHANGE_UNCHANGED = "unchanged" RENAME_CHANGE_TYPES = (CHANGE_RENAME, CHANGE_COPY) _NULL_ENTRY = TreeEntry(None, None, None) _MAX_SCORE = 100 RENAME_THRESHOLD = 60 MAX_FILES = 200 REWRITE_THRESHOLD = None class TreeChange(namedtuple("TreeChange", ["type", "old", "new"])): """Named tuple a single change between two trees.""" @classmethod def add(cls, new): return cls(CHANGE_ADD, _NULL_ENTRY, new) @classmethod def delete(cls, old): return cls(CHANGE_DELETE, old, _NULL_ENTRY) def _tree_entries(path: bytes, tree: Tree) -> list[TreeEntry]: result: list[TreeEntry] = [] if not tree: return result for entry in tree.iteritems(name_order=True): result.append(entry.in_path(path)) return result def _merge_entries( path: bytes, tree1: Tree, tree2: Tree ) -> list[tuple[TreeEntry, TreeEntry]]: """Merge the entries of two trees. Args: path: A path to prepend to all tree entry names. tree1: The first Tree object to iterate, or None. tree2: The second Tree object to iterate, or None. Returns: A list of pairs of TreeEntry objects for each pair of entries in the trees. If an entry exists in one tree but not the other, the other entry will have all attributes set to None. If neither entry's path is None, they are guaranteed to match. """ entries1 = _tree_entries(path, tree1) entries2 = _tree_entries(path, tree2) i1 = i2 = 0 len1 = len(entries1) len2 = len(entries2) result = [] while i1 < len1 and i2 < len2: entry1 = entries1[i1] entry2 = entries2[i2] if entry1.path < entry2.path: result.append((entry1, _NULL_ENTRY)) i1 += 1 elif entry1.path > entry2.path: result.append((_NULL_ENTRY, entry2)) i2 += 1 else: result.append((entry1, entry2)) i1 += 1 i2 += 1 for i in range(i1, len1): result.append((entries1[i], _NULL_ENTRY)) for i in range(i2, len2): result.append((_NULL_ENTRY, entries2[i])) return result def _is_tree(entry): mode = entry.mode if mode is None: return False return stat.S_ISDIR(mode) def walk_trees(store, tree1_id, tree2_id, prune_identical=False): """Recursively walk all the entries of two trees. Iteration is depth-first pre-order, as in e.g. os.walk. Args: store: An ObjectStore for looking up objects. tree1_id: The SHA of the first Tree object to iterate, or None. tree2_id: The SHA of the second Tree object to iterate, or None. prune_identical: If True, identical subtrees will not be walked. Returns: Iterator over Pairs of TreeEntry objects for each pair of entries in the trees and their subtrees recursively. If an entry exists in one tree but not the other, the other entry will have all attributes set to None. If neither entry's path is None, they are guaranteed to match. """ # This could be fairly easily generalized to >2 trees if we find a use # case. mode1 = (tree1_id and stat.S_IFDIR) or None mode2 = (tree2_id and stat.S_IFDIR) or None todo = [(TreeEntry(b"", mode1, tree1_id), TreeEntry(b"", mode2, tree2_id))] while todo: entry1, entry2 = todo.pop() is_tree1 = _is_tree(entry1) is_tree2 = _is_tree(entry2) if prune_identical and is_tree1 and is_tree2 and entry1 == entry2: continue tree1 = (is_tree1 and store[entry1.sha]) or None tree2 = (is_tree2 and store[entry2.sha]) or None path = entry1.path or entry2.path todo.extend(reversed(_merge_entries(path, tree1, tree2))) yield entry1, entry2 def _skip_tree(entry, include_trees): if entry.mode is None or (not include_trees and stat.S_ISDIR(entry.mode)): return _NULL_ENTRY return entry def tree_changes( store, tree1_id, tree2_id, want_unchanged=False, rename_detector=None, include_trees=False, change_type_same=False, ): """Find the differences between the contents of two trees. Args: store: An ObjectStore for looking up objects. tree1_id: The SHA of the source tree. tree2_id: The SHA of the target tree. want_unchanged: If True, include TreeChanges for unmodified entries as well. include_trees: Whether to include trees rename_detector: RenameDetector object for detecting renames. change_type_same: Whether to report change types in the same entry or as delete+add. Returns: Iterator over TreeChange instances for each change between the source and target tree. """ if rename_detector is not None and tree1_id is not None and tree2_id is not None: yield from rename_detector.changes_with_renames( tree1_id, tree2_id, want_unchanged=want_unchanged, include_trees=include_trees, ) return entries = walk_trees( store, tree1_id, tree2_id, prune_identical=(not want_unchanged) ) for entry1, entry2 in entries: if entry1 == entry2 and not want_unchanged: continue # Treat entries for trees as missing. entry1 = _skip_tree(entry1, include_trees) entry2 = _skip_tree(entry2, include_trees) if entry1 != _NULL_ENTRY and entry2 != _NULL_ENTRY: if ( stat.S_IFMT(entry1.mode) != stat.S_IFMT(entry2.mode) and not change_type_same ): # File type changed: report as delete/add. yield TreeChange.delete(entry1) entry1 = _NULL_ENTRY change_type = CHANGE_ADD elif entry1 == entry2: change_type = CHANGE_UNCHANGED else: change_type = CHANGE_MODIFY elif entry1 != _NULL_ENTRY: change_type = CHANGE_DELETE elif entry2 != _NULL_ENTRY: change_type = CHANGE_ADD else: # Both were None because at least one was a tree. continue yield TreeChange(change_type, entry1, entry2) def _all_eq(seq, key, value) -> bool: for e in seq: if key(e) != value: return False return True def _all_same(seq, key): return _all_eq(seq[1:], key, key(seq[0])) def tree_changes_for_merge( store: BaseObjectStore, parent_tree_ids: list[ObjectID], tree_id: ObjectID, rename_detector=None, ): """Get the tree changes for a merge tree relative to all its parents. Args: store: An ObjectStore for looking up objects. parent_tree_ids: An iterable of the SHAs of the parent trees. tree_id: The SHA of the merge tree. rename_detector: RenameDetector object for detecting renames. Returns: Iterator over lists of TreeChange objects, one per conflicted path in the merge. Each list contains one element per parent, with the TreeChange for that path relative to that parent. An element may be None if it never existed in one parent and was deleted in two others. A path is only included in the output if it is a conflict, i.e. its SHA in the merge tree is not found in any of the parents, or in the case of deletes, if not all of the old SHAs match. """ all_parent_changes = [ tree_changes(store, t, tree_id, rename_detector=rename_detector) for t in parent_tree_ids ] num_parents = len(parent_tree_ids) changes_by_path: dict[str, list[Optional[TreeChange]]] = defaultdict( lambda: [None] * num_parents ) # Organize by path. for i, parent_changes in enumerate(all_parent_changes): for change in parent_changes: if change.type == CHANGE_DELETE: path = change.old.path else: path = change.new.path changes_by_path[path][i] = change def old_sha(c): return c.old.sha def change_type(c): return c.type # Yield only conflicting changes. for _, changes in sorted(changes_by_path.items()): assert len(changes) == num_parents have = [c for c in changes if c is not None] if _all_eq(have, change_type, CHANGE_DELETE): if not _all_same(have, old_sha): yield changes elif not _all_same(have, change_type): yield changes elif None not in changes: # If no change was found relative to one parent, that means the SHA # must have matched the SHA in that parent, so it is not a # conflict. yield changes _BLOCK_SIZE = 64 def _count_blocks(obj: ShaFile) -> dict[int, int]: """Count the blocks in an object. Splits the data into blocks either on lines or <=64-byte chunks of lines. Args: obj: The object to count blocks for. Returns: A dict of block hashcode -> total bytes occurring. """ block_counts: dict[int, int] = defaultdict(int) block = BytesIO() n = 0 # Cache attrs as locals to avoid expensive lookups in the inner loop. block_write = block.write block_seek = block.seek block_truncate = block.truncate block_getvalue = block.getvalue for c in chain.from_iterable(obj.as_raw_chunks()): cb = c.to_bytes(1, "big") block_write(cb) n += 1 if cb == b"\n" or n == _BLOCK_SIZE: value = block_getvalue() block_counts[hash(value)] += len(value) block_seek(0) block_truncate() n = 0 if n > 0: last_block = block_getvalue() block_counts[hash(last_block)] += len(last_block) return block_counts def _common_bytes(blocks1, blocks2): """Count the number of common bytes in two block count dicts. Args: blocks1: The first dict of block hashcode -> total bytes. blocks2: The second dict of block hashcode -> total bytes. Returns: The number of bytes in common between blocks1 and blocks2. This is only approximate due to possible hash collisions. """ # Iterate over the smaller of the two dicts, since this is symmetrical. if len(blocks1) > len(blocks2): blocks1, blocks2 = blocks2, blocks1 score = 0 for block, count1 in blocks1.items(): count2 = blocks2.get(block) if count2: score += min(count1, count2) return score def _similarity_score(obj1, obj2, block_cache=None): """Compute a similarity score for two objects. Args: obj1: The first object to score. obj2: The second object to score. block_cache: An optional dict of SHA to block counts to cache results between calls. Returns: The similarity score between the two objects, defined as the number of bytes in common between the two objects divided by the maximum size, scaled to the range 0-100. """ if block_cache is None: block_cache = {} if obj1.id not in block_cache: block_cache[obj1.id] = _count_blocks(obj1) if obj2.id not in block_cache: block_cache[obj2.id] = _count_blocks(obj2) common_bytes = _common_bytes(block_cache[obj1.id], block_cache[obj2.id]) max_size = max(obj1.raw_length(), obj2.raw_length()) if not max_size: return _MAX_SCORE return int(float(common_bytes) * _MAX_SCORE / max_size) def _tree_change_key(entry): # Sort by old path then new path. If only one exists, use it for both keys. path1 = entry.old.path path2 = entry.new.path if path1 is None: path1 = path2 if path2 is None: path2 = path1 return (path1, path2) class RenameDetector: """Object for handling rename detection between two trees.""" _adds: list[TreeChange] _deletes: list[TreeChange] _changes: list[TreeChange] _candidates: list[tuple[int, TreeChange]] def __init__( self, store, rename_threshold=RENAME_THRESHOLD, max_files=MAX_FILES, rewrite_threshold=REWRITE_THRESHOLD, find_copies_harder=False, ) -> None: """Initialize the rename detector. Args: store: An ObjectStore for looking up objects. rename_threshold: The threshold similarity score for considering an add/delete pair to be a rename/copy; see _similarity_score. max_files: The maximum number of adds and deletes to consider, or None for no limit. The detector is guaranteed to compare no more than max_files ** 2 add/delete pairs. This limit is provided because rename detection can be quadratic in the project size. If the limit is exceeded, no content rename detection is attempted. rewrite_threshold: The threshold similarity score below which a modify should be considered a delete/add, or None to not break modifies; see _similarity_score. find_copies_harder: If True, consider unmodified files when detecting copies. """ self._store = store self._rename_threshold = rename_threshold self._rewrite_threshold = rewrite_threshold self._max_files = max_files self._find_copies_harder = find_copies_harder self._want_unchanged = False def _reset(self) -> None: self._adds = [] self._deletes = [] self._changes = [] def _should_split(self, change): if ( self._rewrite_threshold is None or change.type != CHANGE_MODIFY or change.old.sha == change.new.sha ): return False old_obj = self._store[change.old.sha] new_obj = self._store[change.new.sha] return _similarity_score(old_obj, new_obj) < self._rewrite_threshold def _add_change(self, change) -> None: if change.type == CHANGE_ADD: self._adds.append(change) elif change.type == CHANGE_DELETE: self._deletes.append(change) elif self._should_split(change): self._deletes.append(TreeChange.delete(change.old)) self._adds.append(TreeChange.add(change.new)) elif ( self._find_copies_harder and change.type == CHANGE_UNCHANGED ) or change.type == CHANGE_MODIFY: # Treat all modifies as potential deletes for rename detection, # but don't split them (to avoid spurious renames). Setting # find_copies_harder means we treat unchanged the same as # modified. self._deletes.append(change) else: self._changes.append(change) def _collect_changes(self, tree1_id, tree2_id) -> None: want_unchanged = self._find_copies_harder or self._want_unchanged for change in tree_changes( self._store, tree1_id, tree2_id, want_unchanged=want_unchanged, include_trees=self._include_trees, ): self._add_change(change) def _prune(self, add_paths, delete_paths) -> None: self._adds = [a for a in self._adds if a.new.path not in add_paths] self._deletes = [d for d in self._deletes if d.old.path not in delete_paths] def _find_exact_renames(self) -> None: add_map = defaultdict(list) for add in self._adds: add_map[add.new.sha].append(add.new) delete_map = defaultdict(list) for delete in self._deletes: # Keep track of whether the delete was actually marked as a delete. # If not, it needs to be marked as a copy. is_delete = delete.type == CHANGE_DELETE delete_map[delete.old.sha].append((delete.old, is_delete)) add_paths = set() delete_paths = set() for sha, sha_deletes in delete_map.items(): sha_adds = add_map[sha] for (old, is_delete), new in zip(sha_deletes, sha_adds): if stat.S_IFMT(old.mode) != stat.S_IFMT(new.mode): continue if is_delete: delete_paths.add(old.path) add_paths.add(new.path) new_type = (is_delete and CHANGE_RENAME) or CHANGE_COPY self._changes.append(TreeChange(new_type, old, new)) num_extra_adds = len(sha_adds) - len(sha_deletes) # TODO(dborowitz): Less arbitrary way of dealing with extra copies. old = sha_deletes[0][0] if num_extra_adds > 0: for new in sha_adds[-num_extra_adds:]: add_paths.add(new.path) self._changes.append(TreeChange(CHANGE_COPY, old, new)) self._prune(add_paths, delete_paths) def _should_find_content_renames(self): return len(self._adds) * len(self._deletes) <= self._max_files**2 def _rename_type(self, check_paths, delete, add): if check_paths and delete.old.path == add.new.path: # If the paths match, this must be a split modify, so make sure it # comes out as a modify. return CHANGE_MODIFY elif delete.type != CHANGE_DELETE: # If it's in deletes but not marked as a delete, it must have been # added due to find_copies_harder, and needs to be marked as a # copy. return CHANGE_COPY return CHANGE_RENAME def _find_content_rename_candidates(self) -> None: candidates = self._candidates = [] # TODO: Optimizations: # - Compare object sizes before counting blocks. # - Skip if delete's S_IFMT differs from all adds. # - Skip if adds or deletes is empty. # Match C git's behavior of not attempting to find content renames if # the matrix size exceeds the threshold. if not self._should_find_content_renames(): return block_cache = {} check_paths = self._rename_threshold is not None for delete in self._deletes: if S_ISGITLINK(delete.old.mode): continue # Git links don't exist in this repo. old_sha = delete.old.sha old_obj = self._store[old_sha] block_cache[old_sha] = _count_blocks(old_obj) for add in self._adds: if stat.S_IFMT(delete.old.mode) != stat.S_IFMT(add.new.mode): continue new_obj = self._store[add.new.sha] score = _similarity_score(old_obj, new_obj, block_cache=block_cache) if score > self._rename_threshold: new_type = self._rename_type(check_paths, delete, add) rename = TreeChange(new_type, delete.old, add.new) candidates.append((-score, rename)) def _choose_content_renames(self) -> None: # Sort scores from highest to lowest, but keep names in ascending # order. self._candidates.sort() delete_paths = set() add_paths = set() for _, change in self._candidates: new_path = change.new.path if new_path in add_paths: continue old_path = change.old.path orig_type = change.type if old_path in delete_paths: change = TreeChange(CHANGE_COPY, change.old, change.new) # If the candidate was originally a copy, that means it came from a # modified or unchanged path, so we don't want to prune it. if orig_type != CHANGE_COPY: delete_paths.add(old_path) add_paths.add(new_path) self._changes.append(change) self._prune(add_paths, delete_paths) def _join_modifies(self) -> None: if self._rewrite_threshold is None: return modifies = {} delete_map = {d.old.path: d for d in self._deletes} for add in self._adds: path = add.new.path delete = delete_map.get(path) if delete is not None and stat.S_IFMT(delete.old.mode) == stat.S_IFMT( add.new.mode ): modifies[path] = TreeChange(CHANGE_MODIFY, delete.old, add.new) self._adds = [a for a in self._adds if a.new.path not in modifies] self._deletes = [a for a in self._deletes if a.new.path not in modifies] self._changes += modifies.values() def _sorted_changes(self): result = [] result.extend(self._adds) result.extend(self._deletes) result.extend(self._changes) result.sort(key=_tree_change_key) return result def _prune_unchanged(self) -> None: if self._want_unchanged: return self._deletes = [d for d in self._deletes if d.type != CHANGE_UNCHANGED] def changes_with_renames( self, tree1_id, tree2_id, want_unchanged=False, include_trees=False ): """Iterate TreeChanges between two tree SHAs, with rename detection.""" self._reset() self._want_unchanged = want_unchanged self._include_trees = include_trees self._collect_changes(tree1_id, tree2_id) self._find_exact_renames() self._find_content_rename_candidates() self._choose_content_renames() self._join_modifies() self._prune_unchanged() return self._sorted_changes() # Hold on to the pure-python implementations for testing. _is_tree_py = _is_tree _merge_entries_py = _merge_entries _count_blocks_py = _count_blocks try: # Try to import Rust versions from dulwich._diff_tree import ( # type: ignore _count_blocks, _is_tree, _merge_entries, ) except ImportError: pass ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/errors.py0000644000175100002000000001304614731042555016170 0ustar00runnerdocker# errors.py -- errors for dulwich # Copyright (C) 2007 James Westby # Copyright (C) 2009-2012 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Dulwich-related exception classes and utility functions.""" # Please do not add more errors here, but instead add them close to the code # that raises the error. import binascii class ChecksumMismatch(Exception): """A checksum didn't match the expected contents.""" def __init__(self, expected, got, extra=None) -> None: if len(expected) == 20: expected = binascii.hexlify(expected) if len(got) == 20: got = binascii.hexlify(got) self.expected = expected self.got = got self.extra = extra if self.extra is None: Exception.__init__( self, f"Checksum mismatch: Expected {expected}, got {got}", ) else: Exception.__init__( self, f"Checksum mismatch: Expected {expected}, got {got}; {extra}", ) class WrongObjectException(Exception): """Baseclass for all the _ is not a _ exceptions on objects. Do not instantiate directly. Subclasses should define a type_name attribute that indicates what was expected if they were raised. """ type_name: str def __init__(self, sha, *args, **kwargs) -> None: Exception.__init__(self, f"{sha} is not a {self.type_name}") class NotCommitError(WrongObjectException): """Indicates that the sha requested does not point to a commit.""" type_name = "commit" class NotTreeError(WrongObjectException): """Indicates that the sha requested does not point to a tree.""" type_name = "tree" class NotTagError(WrongObjectException): """Indicates that the sha requested does not point to a tag.""" type_name = "tag" class NotBlobError(WrongObjectException): """Indicates that the sha requested does not point to a blob.""" type_name = "blob" class MissingCommitError(Exception): """Indicates that a commit was not found in the repository.""" def __init__(self, sha, *args, **kwargs) -> None: self.sha = sha Exception.__init__(self, f"{sha} is not in the revision store") class ObjectMissing(Exception): """Indicates that a requested object is missing.""" def __init__(self, sha, *args, **kwargs) -> None: Exception.__init__(self, f"{sha} is not in the pack") class ApplyDeltaError(Exception): """Indicates that applying a delta failed.""" def __init__(self, *args, **kwargs) -> None: Exception.__init__(self, *args, **kwargs) class NotGitRepository(Exception): """Indicates that no Git repository was found.""" def __init__(self, *args, **kwargs) -> None: Exception.__init__(self, *args, **kwargs) class GitProtocolError(Exception): """Git protocol exception.""" def __init__(self, *args, **kwargs) -> None: Exception.__init__(self, *args, **kwargs) def __eq__(self, other): return isinstance(self, type(other)) and self.args == other.args class SendPackError(GitProtocolError): """An error occurred during send_pack.""" class HangupException(GitProtocolError): """Hangup exception.""" def __init__(self, stderr_lines=None) -> None: if stderr_lines: super().__init__( "\n".join( [line.decode("utf-8", "surrogateescape") for line in stderr_lines] ) ) else: super().__init__("The remote server unexpectedly closed the connection.") self.stderr_lines = stderr_lines def __eq__(self, other): return isinstance(self, type(other)) and self.stderr_lines == other.stderr_lines class UnexpectedCommandError(GitProtocolError): """Unexpected command received in a proto line.""" def __init__(self, command) -> None: if command is None: command = "flush-pkt" else: command = f"command {command}" super().__init__(f"Protocol got unexpected {command}") class FileFormatException(Exception): """Base class for exceptions relating to reading git file formats.""" class PackedRefsException(FileFormatException): """Indicates an error parsing a packed-refs file.""" class ObjectFormatException(FileFormatException): """Indicates an error parsing an object.""" class NoIndexPresent(Exception): """No index is present.""" class CommitError(Exception): """An error occurred while performing a commit.""" class RefFormatError(Exception): """Indicates an invalid ref name.""" class HookError(Exception): """An error occurred while executing a hook.""" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/fastexport.py0000644000175100002000000002156114731042555017054 0ustar00runnerdocker# __init__.py -- Fast export/import functionality # Copyright (C) 2010-2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Fast export/import functionality.""" import stat from fastimport import commands, parser, processor from fastimport import errors as fastimport_errors from .index import commit_tree from .object_store import iter_tree_contents from .objects import ZERO_SHA, Blob, Commit, Tag def split_email(text): (name, email) = text.rsplit(b" <", 1) return (name, email.rstrip(b">")) class GitFastExporter: """Generate a fast-export output stream for Git objects.""" def __init__(self, outf, store) -> None: self.outf = outf self.store = store self.markers: dict[bytes, bytes] = {} self._marker_idx = 0 def print_cmd(self, cmd) -> None: self.outf.write(getattr(cmd, "__bytes__", cmd.__repr__)() + b"\n") def _allocate_marker(self): self._marker_idx += 1 return str(self._marker_idx).encode("ascii") def _export_blob(self, blob): marker = self._allocate_marker() self.markers[marker] = blob.id return (commands.BlobCommand(marker, blob.data), marker) def emit_blob(self, blob): (cmd, marker) = self._export_blob(blob) self.print_cmd(cmd) return marker def _iter_files(self, base_tree, new_tree): for ( (old_path, new_path), (old_mode, new_mode), (old_hexsha, new_hexsha), ) in self.store.tree_changes(base_tree, new_tree): if new_path is None: yield commands.FileDeleteCommand(old_path) continue if not stat.S_ISDIR(new_mode): blob = self.store[new_hexsha] marker = self.emit_blob(blob) if old_path != new_path and old_path is not None: yield commands.FileRenameCommand(old_path, new_path) if old_mode != new_mode or old_hexsha != new_hexsha: prefixed_marker = b":" + marker yield commands.FileModifyCommand( new_path, new_mode, prefixed_marker, None ) def _export_commit(self, commit, ref, base_tree=None): file_cmds = list(self._iter_files(base_tree, commit.tree)) marker = self._allocate_marker() if commit.parents: from_ = commit.parents[0] merges = commit.parents[1:] else: from_ = None merges = [] author, author_email = split_email(commit.author) committer, committer_email = split_email(commit.committer) cmd = commands.CommitCommand( ref, marker, (author, author_email, commit.author_time, commit.author_timezone), ( committer, committer_email, commit.commit_time, commit.commit_timezone, ), commit.message, from_, merges, file_cmds, ) return (cmd, marker) def emit_commit(self, commit, ref, base_tree=None): cmd, marker = self._export_commit(commit, ref, base_tree) self.print_cmd(cmd) return marker class GitImportProcessor(processor.ImportProcessor): """An import processor that imports into a Git repository using Dulwich.""" # FIXME: Batch creation of objects? def __init__(self, repo, params=None, verbose=False, outf=None) -> None: processor.ImportProcessor.__init__(self, params, verbose) self.repo = repo self.last_commit = ZERO_SHA self.markers: dict[bytes, bytes] = {} self._contents: dict[bytes, tuple[int, bytes]] = {} def lookup_object(self, objectish): if objectish.startswith(b":"): return self.markers[objectish[1:]] return objectish def import_stream(self, stream): p = parser.ImportParser(stream) self.process(p.iter_commands) return self.markers def blob_handler(self, cmd) -> None: """Process a BlobCommand.""" blob = Blob.from_string(cmd.data) self.repo.object_store.add_object(blob) if cmd.mark: self.markers[cmd.mark] = blob.id def checkpoint_handler(self, cmd) -> None: """Process a CheckpointCommand.""" def commit_handler(self, cmd) -> None: """Process a CommitCommand.""" commit = Commit() if cmd.author is not None: author = cmd.author else: author = cmd.committer (author_name, author_email, author_timestamp, author_timezone) = author ( committer_name, committer_email, commit_timestamp, commit_timezone, ) = cmd.committer commit.author = author_name + b" <" + author_email + b">" commit.author_timezone = author_timezone commit.author_time = int(author_timestamp) commit.committer = committer_name + b" <" + committer_email + b">" commit.commit_timezone = commit_timezone commit.commit_time = int(commit_timestamp) commit.message = cmd.message commit.parents = [] if cmd.from_: cmd.from_ = self.lookup_object(cmd.from_) self._reset_base(cmd.from_) for filecmd in cmd.iter_files(): if filecmd.name == b"filemodify": if filecmd.data is not None: blob = Blob.from_string(filecmd.data) self.repo.object_store.add(blob) blob_id = blob.id else: blob_id = self.lookup_object(filecmd.dataref) self._contents[filecmd.path] = (filecmd.mode, blob_id) elif filecmd.name == b"filedelete": del self._contents[filecmd.path] elif filecmd.name == b"filecopy": self._contents[filecmd.dest_path] = self._contents[filecmd.src_path] elif filecmd.name == b"filerename": self._contents[filecmd.new_path] = self._contents[filecmd.old_path] del self._contents[filecmd.old_path] elif filecmd.name == b"filedeleteall": self._contents = {} else: raise Exception(f"Command {filecmd.name} not supported") commit.tree = commit_tree( self.repo.object_store, ((path, hexsha, mode) for (path, (mode, hexsha)) in self._contents.items()), ) if self.last_commit != ZERO_SHA: commit.parents.append(self.last_commit) for merge in cmd.merges: commit.parents.append(self.lookup_object(merge)) self.repo.object_store.add_object(commit) self.repo[cmd.ref] = commit.id self.last_commit = commit.id if cmd.mark: self.markers[cmd.mark] = commit.id def progress_handler(self, cmd) -> None: """Process a ProgressCommand.""" def _reset_base(self, commit_id) -> None: if self.last_commit == commit_id: return self._contents = {} self.last_commit = commit_id if commit_id != ZERO_SHA: tree_id = self.repo[commit_id].tree for ( path, mode, hexsha, ) in iter_tree_contents(self.repo.object_store, tree_id): self._contents[path] = (mode, hexsha) def reset_handler(self, cmd) -> None: """Process a ResetCommand.""" if cmd.from_ is None: from_ = ZERO_SHA else: from_ = self.lookup_object(cmd.from_) self._reset_base(from_) self.repo.refs[cmd.ref] = from_ def tag_handler(self, cmd) -> None: """Process a TagCommand.""" tag = Tag() tag.tagger = cmd.tagger tag.message = cmd.message tag.name = cmd.tag self.repo.add_object(tag) self.repo.refs["refs/tags/" + tag.name] = tag.id def feature_handler(self, cmd): """Process a FeatureCommand.""" raise fastimport_errors.UnknownFeature(cmd.feature_name) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/file.py0000644000175100002000000001626314731042555015577 0ustar00runnerdocker# file.py -- Safe access to git files # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Safe access to git files.""" import os import sys import warnings from typing import ClassVar def ensure_dir_exists(dirname) -> None: """Ensure a directory exists, creating if necessary.""" try: os.makedirs(dirname) except FileExistsError: pass def _fancy_rename(oldname, newname) -> None: """Rename file with temporary backup file to rollback if rename fails.""" if not os.path.exists(newname): try: os.rename(oldname, newname) except OSError: raise return # Defer the tempfile import since it pulls in a lot of other things. import tempfile # destination file exists try: (fd, tmpfile) = tempfile.mkstemp(".tmp", prefix=oldname, dir=".") os.close(fd) os.remove(tmpfile) except OSError: # either file could not be created (e.g. permission problem) # or could not be deleted (e.g. rude virus scanner) raise try: os.rename(newname, tmpfile) except OSError: raise # no rename occurred try: os.rename(oldname, newname) except OSError: os.rename(tmpfile, newname) raise os.remove(tmpfile) def GitFile(filename, mode="rb", bufsize=-1, mask=0o644): """Create a file object that obeys the git file locking protocol. Returns: a builtin file object or a _GitFile object Note: See _GitFile for a description of the file locking protocol. Only read-only and write-only (binary) modes are supported; r+, w+, and a are not. To read and write from the same file, you can take advantage of the fact that opening a file for write does not actually open the file you request. The default file mask makes any created files user-writable and world-readable. """ if "a" in mode: raise OSError("append mode not supported for Git files") if "+" in mode: raise OSError("read/write mode not supported for Git files") if "b" not in mode: raise OSError("text mode not supported for Git files") if "w" in mode: return _GitFile(filename, mode, bufsize, mask) else: return open(filename, mode, bufsize) class FileLocked(Exception): """File is already locked.""" def __init__(self, filename, lockfilename) -> None: self.filename = filename self.lockfilename = lockfilename super().__init__(filename, lockfilename) class _GitFile: """File that follows the git locking protocol for writes. All writes to a file foo will be written into foo.lock in the same directory, and the lockfile will be renamed to overwrite the original file on close. Note: You *must* call close() or abort() on a _GitFile for the lock to be released. Typically this will happen in a finally block. """ PROXY_PROPERTIES: ClassVar[set[str]] = { "closed", "encoding", "errors", "mode", "name", "newlines", "softspace", } PROXY_METHODS: ClassVar[set[str]] = { "__iter__", "flush", "fileno", "isatty", "read", "readline", "readlines", "seek", "tell", "truncate", "write", "writelines", } def __init__(self, filename, mode, bufsize, mask) -> None: self._filename = filename if isinstance(self._filename, bytes): self._lockfilename = self._filename + b".lock" else: self._lockfilename = self._filename + ".lock" try: fd = os.open( self._lockfilename, os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0), mask, ) except FileExistsError as exc: raise FileLocked(filename, self._lockfilename) from exc self._file = os.fdopen(fd, mode, bufsize) self._closed = False for method in self.PROXY_METHODS: setattr(self, method, getattr(self._file, method)) def abort(self) -> None: """Close and discard the lockfile without overwriting the target. If the file is already closed, this is a no-op. """ if self._closed: return self._file.close() try: os.remove(self._lockfilename) self._closed = True except FileNotFoundError: # The file may have been removed already, which is ok. self._closed = True def close(self) -> None: """Close this file, saving the lockfile over the original. Note: If this method fails, it will attempt to delete the lockfile. However, it is not guaranteed to do so (e.g. if a filesystem becomes suddenly read-only), which will prevent future writes to this file until the lockfile is removed manually. Raises: OSError: if the original file could not be overwritten. The lock file is still closed, so further attempts to write to the same file object will raise ValueError. """ if self._closed: return self._file.flush() os.fsync(self._file.fileno()) self._file.close() try: if getattr(os, "replace", None) is not None: os.replace(self._lockfilename, self._filename) else: if sys.platform != "win32": os.rename(self._lockfilename, self._filename) else: # Windows versions prior to Vista don't support atomic # renames _fancy_rename(self._lockfilename, self._filename) finally: self.abort() def __del__(self) -> None: if not getattr(self, "_closed", True): warnings.warn(f"unclosed {self!r}", ResourceWarning, stacklevel=2) self.abort() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: self.abort() else: self.close() def __getattr__(self, name): """Proxy property calls to the underlying file.""" if name in self.PROXY_PROPERTIES: return getattr(self._file, name) raise AttributeError(name) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/graph.py0000644000175100002000000001713414731042555015757 0ustar00runnerdocker# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # Copyright (c) 2020 Kevin B. Hendricks, Stratford Ontario Canada # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. """Implementation of merge-base following the approach of git.""" from collections.abc import Iterator from heapq import heappop, heappush from typing import Generic, Optional, TypeVar from .lru_cache import LRUCache T = TypeVar("T") # priority queue using builtin python minheap tools # why they do not have a builtin maxheap is simply ridiculous but # liveable with integer time stamps using negation class WorkList(Generic[T]): def __init__(self) -> None: self.pq: list[tuple[int, T]] = [] def add(self, item: tuple[int, T]) -> None: dt, cmt = item heappush(self.pq, (-dt, cmt)) def get(self) -> Optional[tuple[int, T]]: item = heappop(self.pq) if item: pr, cmt = item return -pr, cmt return None def iter(self) -> Iterator[tuple[int, T]]: for pr, cmt in self.pq: yield (-pr, cmt) def _find_lcas(lookup_parents, c1, c2s, lookup_stamp, min_stamp=0): cands = [] cstates = {} # Flags to Record State _ANC_OF_1 = 1 # ancestor of commit 1 _ANC_OF_2 = 2 # ancestor of commit 2 _DNC = 4 # Do Not Consider _LCA = 8 # potential LCA (Lowest Common Ancestor) def _has_candidates(wlst, cstates) -> bool: for dt, cmt in wlst.iter(): if cmt in cstates: if not ((cstates[cmt] & _DNC) == _DNC): return True return False # initialize the working list states with ancestry info # note possibility of c1 being one of c2s should be handled wlst = WorkList() cstates[c1] = _ANC_OF_1 wlst.add((lookup_stamp(c1), c1)) for c2 in c2s: cflags = cstates.get(c2, 0) cstates[c2] = cflags | _ANC_OF_2 wlst.add((lookup_stamp(c2), c2)) # loop while at least one working list commit is still viable (not marked as _DNC) # adding any parents to the list in a breadth first manner while _has_candidates(wlst, cstates): dt, cmt = wlst.get() # Look only at ANCESTRY and _DNC flags so that already # found _LCAs can still be marked _DNC by lower _LCAS cflags = cstates[cmt] & (_ANC_OF_1 | _ANC_OF_2 | _DNC) if cflags == (_ANC_OF_1 | _ANC_OF_2): # potential common ancestor if not already in candidates add it if not (cstates[cmt] & _LCA) == _LCA: cstates[cmt] = cstates[cmt] | _LCA cands.append((dt, cmt)) # mark any parents of this node _DNC as all parents # would be one generation further removed common ancestors cflags = cflags | _DNC parents = lookup_parents(cmt) if parents: for pcmt in parents: pflags = cstates.get(pcmt, 0) # if this parent was already visited with no new ancestry/flag information # do not add it to the working list again if (pflags & cflags) == cflags: continue pdt = lookup_stamp(pcmt) if pdt < min_stamp: continue cstates[pcmt] = pflags | cflags wlst.add((pdt, pcmt)) # walk final candidates removing any superseded by _DNC by later lower _LCAs # remove any duplicates and sort it so that earliest is first results = [] for dt, cmt in cands: if not ((cstates[cmt] & _DNC) == _DNC) and (dt, cmt) not in results: results.append((dt, cmt)) results.sort(key=lambda x: x[0]) lcas = [cmt for dt, cmt in results] return lcas # actual git sorts these based on commit times def find_merge_base(repo, commit_ids): """Find lowest common ancestors of commit_ids[0] and *any* of commits_ids[1:]. Args: repo: Repository object commit_ids: list of commit ids Returns: list of lowest common ancestor commit_ids """ cmtcache = LRUCache(max_cache=128) parents_provider = repo.parents_provider() def lookup_stamp(cmtid): if cmtid not in cmtcache: cmtcache[cmtid] = repo.object_store[cmtid] return cmtcache[cmtid].commit_time def lookup_parents(cmtid): commit = None if cmtid in cmtcache: commit = cmtcache[cmtid] # must use parents provider to handle grafts and shallow return parents_provider.get_parents(cmtid, commit=commit) if not commit_ids: return [] c1 = commit_ids[0] if not len(commit_ids) > 1: return [c1] c2s = commit_ids[1:] if c1 in c2s: return [c1] lcas = _find_lcas(lookup_parents, c1, c2s, lookup_stamp) return lcas def find_octopus_base(repo, commit_ids): """Find lowest common ancestors of *all* provided commit_ids. Args: repo: Repository commit_ids: list of commit ids Returns: list of lowest common ancestor commit_ids """ cmtcache = LRUCache(max_cache=128) parents_provider = repo.parents_provider() def lookup_stamp(cmtid): if cmtid not in cmtcache: cmtcache[cmtid] = repo.object_store[cmtid] return cmtcache[cmtid].commit_time def lookup_parents(cmtid): commit = None if cmtid in cmtcache: commit = cmtcache[cmtid] # must use parents provider to handle grafts and shallow return parents_provider.get_parents(cmtid, commit=commit) if not commit_ids: return [] if len(commit_ids) <= 2: return find_merge_base(repo, commit_ids) lcas = [commit_ids[0]] others = commit_ids[1:] for cmt in others: next_lcas = [] for ca in lcas: res = _find_lcas(lookup_parents, cmt, [ca], lookup_stamp) next_lcas.extend(res) lcas = next_lcas[:] return lcas def can_fast_forward(repo, c1, c2): """Is it possible to fast-forward from c1 to c2? Args: repo: Repository to retrieve objects from c1: Commit id for first commit c2: Commit id for second commit """ cmtcache = LRUCache(max_cache=128) parents_provider = repo.parents_provider() def lookup_stamp(cmtid): if cmtid not in cmtcache: cmtcache[cmtid] = repo.object_store[cmtid] return cmtcache[cmtid].commit_time def lookup_parents(cmtid): commit = None if cmtid in cmtcache: commit = cmtcache[cmtid] # must use parents provider to handle grafts and shallow return parents_provider.get_parents(cmtid, commit=commit) if c1 == c2: return True # Algorithm: Find the common ancestor min_stamp = lookup_stamp(c1) lcas = _find_lcas(lookup_parents, c1, [c2], lookup_stamp, min_stamp=min_stamp) return lcas == [c1] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/greenthreads.py0000644000175100002000000001003614731042555017323 0ustar00runnerdocker# greenthreads.py -- Utility module for querying an ObjectStore with gevent # Copyright (C) 2013 eNovance SAS # # Author: Fabien Boucher # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Utility module for querying an ObjectStore with gevent.""" from typing import Optional import gevent from gevent import pool from .object_store import ( MissingObjectFinder, _collect_ancestors, _collect_filetree_revs, ) from .objects import Commit, ObjectID, Tag def _split_commits_and_tags(obj_store, lst, *, ignore_unknown=False, pool=None): """Split object id list into two list with commit SHA1s and tag SHA1s. Same implementation as object_store._split_commits_and_tags except we use gevent to parallelize object retrieval. """ commits = set() tags = set() def find_commit_type(sha) -> None: try: o = obj_store[sha] except KeyError: if not ignore_unknown: raise else: if isinstance(o, Commit): commits.add(sha) elif isinstance(o, Tag): tags.add(sha) commits.add(o.object[1]) else: raise KeyError(f"Not a commit or a tag: {sha}") jobs = [pool.spawn(find_commit_type, s) for s in lst] gevent.joinall(jobs) return (commits, tags) class GreenThreadsMissingObjectFinder(MissingObjectFinder): """Find the objects missing from another object store. Same implementation as object_store.MissingObjectFinder except we use gevent to parallelize object retrieval. """ def __init__( self, object_store, haves, wants, progress=None, get_tagged=None, concurrency=1, get_parents=None, ) -> None: def collect_tree_sha(sha) -> None: self.sha_done.add(sha) cmt = object_store[sha] _collect_filetree_revs(object_store, cmt.tree, self.sha_done) self.object_store = object_store p = pool.Pool(size=concurrency) have_commits, have_tags = _split_commits_and_tags( object_store, haves, ignore_unknown=True, pool=p ) want_commits, want_tags = _split_commits_and_tags( object_store, wants, ignore_unknown=False, pool=p ) all_ancestors: frozenset[ObjectID] = frozenset( _collect_ancestors(object_store, have_commits)[0] ) missing_commits, common_commits = _collect_ancestors( object_store, want_commits, all_ancestors ) self.sha_done = set() jobs = [p.spawn(collect_tree_sha, c) for c in common_commits] gevent.joinall(jobs) for t in have_tags: self.sha_done.add(t) missing_tags = want_tags.difference(have_tags) wants = missing_commits.union(missing_tags) self.objects_to_send: set[ tuple[ObjectID, Optional[bytes], Optional[int], bool] ] = {(w, None, 0, False) for w in wants} if progress is None: self.progress = lambda x: None else: self.progress = progress self._tagged = (get_tagged and get_tagged()) or {} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/hooks.py0000644000175100002000000001447014731042555016001 0ustar00runnerdocker# hooks.py -- for dealing with git hooks # Copyright (C) 2012-2013 Jelmer Vernooij and others. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Access to hooks.""" import os import subprocess from .errors import HookError class Hook: """Generic hook object.""" def execute(self, *args): """Execute the hook with the given args. Args: args: argument list to hook Raises: HookError: hook execution failure Returns: a hook may return a useful value """ raise NotImplementedError(self.execute) class ShellHook(Hook): """Hook by executable file. Implements standard githooks(5) [0]: [0] http://www.kernel.org/pub/software/scm/git/docs/githooks.html """ def __init__( self, name, path, numparam, pre_exec_callback=None, post_exec_callback=None, cwd=None, ) -> None: """Setup shell hook definition. Args: name: name of hook for error messages path: absolute path to executable file numparam: number of requirements parameters pre_exec_callback: closure for setup before execution Defaults to None. Takes in the variable argument list from the execute functions and returns a modified argument list for the shell hook. post_exec_callback: closure for cleanup after execution Defaults to None. Takes in a boolean for hook success and the modified argument list and returns the final hook return value if applicable cwd: working directory to switch to when executing the hook """ self.name = name self.filepath = path self.numparam = numparam self.pre_exec_callback = pre_exec_callback self.post_exec_callback = post_exec_callback self.cwd = cwd def execute(self, *args): """Execute the hook with given args.""" if len(args) != self.numparam: raise HookError( f"Hook {self.name} executed with wrong number of args. Expected {self.numparam}. Saw {len(args)}. args: {args}" ) if self.pre_exec_callback is not None: args = self.pre_exec_callback(*args) try: ret = subprocess.call( [os.path.relpath(self.filepath, self.cwd), *list(args)], cwd=self.cwd ) if ret != 0: if self.post_exec_callback is not None: self.post_exec_callback(0, *args) raise HookError(f"Hook {self.name} exited with non-zero status {ret}") if self.post_exec_callback is not None: return self.post_exec_callback(1, *args) except OSError: # no file. silent failure. if self.post_exec_callback is not None: self.post_exec_callback(0, *args) class PreCommitShellHook(ShellHook): """pre-commit shell hook.""" def __init__(self, cwd, controldir) -> None: filepath = os.path.join(controldir, "hooks", "pre-commit") ShellHook.__init__(self, "pre-commit", filepath, 0, cwd=cwd) class PostCommitShellHook(ShellHook): """post-commit shell hook.""" def __init__(self, controldir) -> None: filepath = os.path.join(controldir, "hooks", "post-commit") ShellHook.__init__(self, "post-commit", filepath, 0, cwd=controldir) class CommitMsgShellHook(ShellHook): """commit-msg shell hook.""" def __init__(self, controldir) -> None: filepath = os.path.join(controldir, "hooks", "commit-msg") def prepare_msg(*args): import tempfile (fd, path) = tempfile.mkstemp() with os.fdopen(fd, "wb") as f: f.write(args[0]) return (path,) def clean_msg(success, *args): if success: with open(args[0], "rb") as f: new_msg = f.read() os.unlink(args[0]) return new_msg os.unlink(args[0]) ShellHook.__init__( self, "commit-msg", filepath, 1, prepare_msg, clean_msg, controldir ) class PostReceiveShellHook(ShellHook): """post-receive shell hook.""" def __init__(self, controldir) -> None: self.controldir = controldir filepath = os.path.join(controldir, "hooks", "post-receive") ShellHook.__init__(self, "post-receive", path=filepath, numparam=0) def execute(self, client_refs): # do nothing if the script doesn't exist if not os.path.exists(self.filepath): return None try: env = os.environ.copy() env["GIT_DIR"] = self.controldir p = subprocess.Popen( self.filepath, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, ) # client_refs is a list of (oldsha, newsha, ref) in_data = b"\n".join([b" ".join(ref) for ref in client_refs]) out_data, err_data = p.communicate(in_data) if (p.returncode != 0) or err_data: err_fmt = b"post-receive exit code: %d\n" + b"stdout:\n%s\nstderr:\n%s" err_msg = err_fmt % (p.returncode, out_data, err_data) raise HookError(err_msg.decode("utf-8", "backslashreplace")) return out_data except OSError as err: raise HookError(repr(err)) from err ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/ignore.py0000644000175100002000000002676614731042555016154 0ustar00runnerdocker# Copyright (C) 2017 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Parsing of gitignore files. For details for the matching rules, see https://git-scm.com/docs/gitignore """ import os.path import re from collections.abc import Iterable from contextlib import suppress from typing import TYPE_CHECKING, BinaryIO, Optional, Union if TYPE_CHECKING: from .repo import Repo from .config import Config, get_xdg_config_home_path def _translate_segment(segment: bytes) -> bytes: if segment == b"*": return b"[^/]+" res = b"" i, n = 0, len(segment) while i < n: c = segment[i : i + 1] i = i + 1 if c == b"*": res += b"[^/]*" elif c == b"?": res += b"[^/]" elif c == b"\\": res += re.escape(segment[i : i + 1]) i += 1 elif c == b"[": j = i if j < n and segment[j : j + 1] == b"!": j = j + 1 if j < n and segment[j : j + 1] == b"]": j = j + 1 while j < n and segment[j : j + 1] != b"]": j = j + 1 if j >= n: res += b"\\[" else: stuff = segment[i:j].replace(b"\\", b"\\\\") i = j + 1 if stuff.startswith(b"!"): stuff = b"^" + stuff[1:] elif stuff.startswith(b"^"): stuff = b"\\" + stuff res += b"[" + stuff + b"]" else: res += re.escape(c) return res def translate(pat: bytes) -> bytes: """Translate a shell PATTERN to a regular expression. There is no way to quote meta-characters. Originally copied from fnmatch in Python 2.7, but modified for Dulwich to cope with features in Git ignore patterns. """ res = b"(?ms)" if b"/" not in pat[:-1]: # If there's no slash, this is a filename-based match res += b"(.*/)?" if pat.startswith(b"**/"): # Leading **/ pat = pat[2:] res += b"(.*/)?" if pat.startswith(b"/"): pat = pat[1:] for i, segment in enumerate(pat.split(b"/")): if segment == b"**": res += b"(/.*)?" continue else: res += (re.escape(b"/") if i > 0 else b"") + _translate_segment(segment) if not pat.endswith(b"/"): res += b"/?" return res + b"\\Z" def read_ignore_patterns(f: BinaryIO) -> Iterable[bytes]: """Read a git ignore file. Args: f: File-like object to read from Returns: List of patterns """ for line in f: line = line.rstrip(b"\r\n") # Ignore blank lines, they're used for readability. if not line.strip(): continue if line.startswith(b"#"): # Comment continue # Trailing spaces are ignored unless they are quoted with a backslash. while line.endswith(b" ") and not line.endswith(b"\\ "): line = line[:-1] line = line.replace(b"\\ ", b" ") yield line def match_pattern(path: bytes, pattern: bytes, ignorecase: bool = False) -> bool: """Match a gitignore-style pattern against a path. Args: path: Path to match pattern: Pattern to match ignorecase: Whether to do case-sensitive matching Returns: bool indicating whether the pattern matched """ return Pattern(pattern, ignorecase).match(path) class Pattern: """A single ignore pattern.""" def __init__(self, pattern: bytes, ignorecase: bool = False) -> None: self.pattern = pattern self.ignorecase = ignorecase if pattern[0:1] == b"!": self.is_exclude = False pattern = pattern[1:] else: if pattern[0:1] == b"\\": pattern = pattern[1:] self.is_exclude = True flags = 0 if self.ignorecase: flags = re.IGNORECASE self._re = re.compile(translate(pattern), flags) def __bytes__(self) -> bytes: return self.pattern def __str__(self) -> str: return os.fsdecode(self.pattern) def __eq__(self, other: object) -> bool: return ( isinstance(other, type(self)) and self.pattern == other.pattern and self.ignorecase == other.ignorecase ) def __repr__(self) -> str: return f"{type(self).__name__}({self.pattern!r}, {self.ignorecase!r})" def match(self, path: bytes) -> bool: """Try to match a path against this ignore pattern. Args: path: Path to match (relative to ignore location) Returns: boolean """ return bool(self._re.match(path)) class IgnoreFilter: def __init__( self, patterns: Iterable[bytes], ignorecase: bool = False, path=None ) -> None: self._patterns: list[Pattern] = [] self._ignorecase = ignorecase self._path = path for pattern in patterns: self.append_pattern(pattern) def append_pattern(self, pattern: bytes) -> None: """Add a pattern to the set.""" self._patterns.append(Pattern(pattern, self._ignorecase)) def find_matching(self, path: Union[bytes, str]) -> Iterable[Pattern]: """Yield all matching patterns for path. Args: path: Path to match Returns: Iterator over iterators """ if not isinstance(path, bytes): path = os.fsencode(path) for pattern in self._patterns: if pattern.match(path): yield pattern def is_ignored(self, path: bytes) -> Optional[bool]: """Check whether a path is ignored. For directories, include a trailing slash. Returns: status is None if file is not mentioned, True if it is included, False if it is explicitly excluded. """ status = None for pattern in self.find_matching(path): status = pattern.is_exclude return status @classmethod def from_path(cls, path, ignorecase: bool = False) -> "IgnoreFilter": with open(path, "rb") as f: return cls(read_ignore_patterns(f), ignorecase, path=path) def __repr__(self) -> str: path = getattr(self, "_path", None) if path is not None: return f"{type(self).__name__}.from_path({path!r})" else: return f"<{type(self).__name__}>" class IgnoreFilterStack: """Check for ignore status in multiple filters.""" def __init__(self, filters) -> None: self._filters = filters def is_ignored(self, path: str) -> Optional[bool]: """Check whether a path is explicitly included or excluded in ignores. Args: path: Path to check Returns: None if the file is not mentioned, True if it is included, False if it is explicitly excluded. """ status = None for filter in self._filters: status = filter.is_ignored(path) if status is not None: return status return status def default_user_ignore_filter_path(config: Config) -> str: """Return default user ignore filter path. Args: config: A Config object Returns: Path to a global ignore file """ try: value = config.get((b"core",), b"excludesFile") assert isinstance(value, bytes) return value.decode(encoding="utf-8") except KeyError: pass return get_xdg_config_home_path("git", "ignore") class IgnoreFilterManager: """Ignore file manager.""" def __init__( self, top_path: str, global_filters: list[IgnoreFilter], ignorecase: bool, ) -> None: self._path_filters: dict[str, Optional[IgnoreFilter]] = {} self._top_path = top_path self._global_filters = global_filters self._ignorecase = ignorecase def __repr__(self) -> str: return f"{type(self).__name__}({self._top_path}, {self._global_filters!r}, {self._ignorecase!r})" def _load_path(self, path: str) -> Optional[IgnoreFilter]: try: return self._path_filters[path] except KeyError: pass p = os.path.join(self._top_path, path, ".gitignore") try: self._path_filters[path] = IgnoreFilter.from_path(p, self._ignorecase) except OSError: self._path_filters[path] = None return self._path_filters[path] def find_matching(self, path: str) -> Iterable[Pattern]: """Find matching patterns for path. Args: path: Path to check Returns: Iterator over Pattern instances """ if os.path.isabs(path): raise ValueError(f"{path} is an absolute path") filters = [(0, f) for f in self._global_filters] if os.path.sep != "/": path = path.replace(os.path.sep, "/") parts = path.split("/") matches = [] for i in range(len(parts) + 1): dirname = "/".join(parts[:i]) for s, f in filters: relpath = "/".join(parts[s:i]) if i < len(parts): # Paths leading up to the final part are all directories, # so need a trailing slash. relpath += "/" matches += list(f.find_matching(relpath)) ignore_filter = self._load_path(dirname) if ignore_filter is not None: filters.insert(0, (i, ignore_filter)) return iter(matches) def is_ignored(self, path: str) -> Optional[bool]: """Check whether a path is explicitly included or excluded in ignores. Args: path: Path to check Returns: None if the file is not mentioned, True if it is included, False if it is explicitly excluded. """ matches = list(self.find_matching(path)) if matches: return matches[-1].is_exclude return None @classmethod def from_repo(cls, repo: "Repo") -> "IgnoreFilterManager": """Create a IgnoreFilterManager from a repository. Args: repo: Repository object Returns: A `IgnoreFilterManager` object """ global_filters = [] for p in [ os.path.join(repo.controldir(), "info", "exclude"), default_user_ignore_filter_path(repo.get_config_stack()), ]: with suppress(OSError): global_filters.append(IgnoreFilter.from_path(os.path.expanduser(p))) config = repo.get_config_stack() ignorecase = config.get_boolean((b"core"), (b"ignorecase"), False) return cls(repo.path, global_filters, ignorecase) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/index.py0000644000175100002000000010413514731042555015763 0ustar00runnerdocker# index.py -- File parser/writer for the git index file # Copyright (C) 2008-2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Parser for the git index file format.""" import os import stat import struct import sys from collections.abc import Iterable, Iterator from dataclasses import dataclass from enum import Enum from typing import ( Any, BinaryIO, Callable, Optional, Union, ) from .file import GitFile from .object_store import iter_tree_contents from .objects import ( S_IFGITLINK, S_ISGITLINK, Blob, ObjectID, Tree, hex_to_sha, sha_to_hex, ) from .pack import ObjectContainer, SHA1Reader, SHA1Writer # 2-bit stage (during merge) FLAG_STAGEMASK = 0x3000 FLAG_STAGESHIFT = 12 FLAG_NAMEMASK = 0x0FFF # assume-valid FLAG_VALID = 0x8000 # extended flag (must be zero in version 2) FLAG_EXTENDED = 0x4000 # used by sparse checkout EXTENDED_FLAG_SKIP_WORKTREE = 0x4000 # used by "git add -N" EXTENDED_FLAG_INTEND_TO_ADD = 0x2000 DEFAULT_VERSION = 2 class Stage(Enum): NORMAL = 0 MERGE_CONFLICT_ANCESTOR = 1 MERGE_CONFLICT_THIS = 2 MERGE_CONFLICT_OTHER = 3 @dataclass class SerializedIndexEntry: name: bytes ctime: Union[int, float, tuple[int, int]] mtime: Union[int, float, tuple[int, int]] dev: int ino: int mode: int uid: int gid: int size: int sha: bytes flags: int extended_flags: int def stage(self) -> Stage: return Stage((self.flags & FLAG_STAGEMASK) >> FLAG_STAGESHIFT) @dataclass class IndexEntry: ctime: Union[int, float, tuple[int, int]] mtime: Union[int, float, tuple[int, int]] dev: int ino: int mode: int uid: int gid: int size: int sha: bytes @classmethod def from_serialized(cls, serialized: SerializedIndexEntry) -> "IndexEntry": return cls( ctime=serialized.ctime, mtime=serialized.mtime, dev=serialized.dev, ino=serialized.ino, mode=serialized.mode, uid=serialized.uid, gid=serialized.gid, size=serialized.size, sha=serialized.sha, ) def serialize(self, name: bytes, stage: Stage) -> SerializedIndexEntry: return SerializedIndexEntry( name=name, ctime=self.ctime, mtime=self.mtime, dev=self.dev, ino=self.ino, mode=self.mode, uid=self.uid, gid=self.gid, size=self.size, sha=self.sha, flags=stage.value << FLAG_STAGESHIFT, extended_flags=0, ) class ConflictedIndexEntry: """Index entry that represents a conflict.""" ancestor: Optional[IndexEntry] this: Optional[IndexEntry] other: Optional[IndexEntry] def __init__( self, ancestor: Optional[IndexEntry] = None, this: Optional[IndexEntry] = None, other: Optional[IndexEntry] = None, ) -> None: self.ancestor = ancestor self.this = this self.other = other class UnmergedEntries(Exception): """Unmerged entries exist in the index.""" def pathsplit(path: bytes) -> tuple[bytes, bytes]: """Split a /-delimited path into a directory part and a basename. Args: path: The path to split. Returns: Tuple with directory name and basename """ try: (dirname, basename) = path.rsplit(b"/", 1) except ValueError: return (b"", path) else: return (dirname, basename) def pathjoin(*args): """Join a /-delimited path.""" return b"/".join([p for p in args if p]) def read_cache_time(f): """Read a cache time. Args: f: File-like object to read from Returns: Tuple with seconds and nanoseconds """ return struct.unpack(">LL", f.read(8)) def write_cache_time(f, t) -> None: """Write a cache time. Args: f: File-like object to write to t: Time to write (as int, float or tuple with secs and nsecs) """ if isinstance(t, int): t = (t, 0) elif isinstance(t, float): (secs, nsecs) = divmod(t, 1.0) t = (int(secs), int(nsecs * 1000000000)) elif not isinstance(t, tuple): raise TypeError(t) f.write(struct.pack(">LL", *t)) def read_cache_entry(f, version: int) -> SerializedIndexEntry: """Read an entry from a cache file. Args: f: File-like object to read from """ beginoffset = f.tell() ctime = read_cache_time(f) mtime = read_cache_time(f) ( dev, ino, mode, uid, gid, size, sha, flags, ) = struct.unpack(">LLLLLL20sH", f.read(20 + 4 * 6 + 2)) if flags & FLAG_EXTENDED: if version < 3: raise AssertionError("extended flag set in index with version < 3") (extended_flags,) = struct.unpack(">H", f.read(2)) else: extended_flags = 0 name = f.read(flags & FLAG_NAMEMASK) # Padding: if version < 4: real_size = (f.tell() - beginoffset + 8) & ~7 f.read((beginoffset + real_size) - f.tell()) return SerializedIndexEntry( name, ctime, mtime, dev, ino, mode, uid, gid, size, sha_to_hex(sha), flags & ~FLAG_NAMEMASK, extended_flags, ) def write_cache_entry(f, entry: SerializedIndexEntry, version: int) -> None: """Write an index entry to a file. Args: f: File object entry: IndexEntry to write, tuple with: """ beginoffset = f.tell() write_cache_time(f, entry.ctime) write_cache_time(f, entry.mtime) flags = len(entry.name) | (entry.flags & ~FLAG_NAMEMASK) if entry.extended_flags: flags |= FLAG_EXTENDED if flags & FLAG_EXTENDED and version is not None and version < 3: raise AssertionError("unable to use extended flags in version < 3") f.write( struct.pack( b">LLLLLL20sH", entry.dev & 0xFFFFFFFF, entry.ino & 0xFFFFFFFF, entry.mode, entry.uid, entry.gid, entry.size, hex_to_sha(entry.sha), flags, ) ) if flags & FLAG_EXTENDED: f.write(struct.pack(b">H", entry.extended_flags)) f.write(entry.name) if version < 4: real_size = (f.tell() - beginoffset + 8) & ~7 f.write(b"\0" * ((beginoffset + real_size) - f.tell())) class UnsupportedIndexFormat(Exception): """An unsupported index format was encountered.""" def __init__(self, version) -> None: self.index_format_version = version def read_index(f: BinaryIO) -> Iterator[SerializedIndexEntry]: """Read an index file, yielding the individual entries.""" header = f.read(4) if header != b"DIRC": raise AssertionError(f"Invalid index file header: {header!r}") (version, num_entries) = struct.unpack(b">LL", f.read(4 * 2)) if version not in (1, 2, 3): raise UnsupportedIndexFormat(version) for i in range(num_entries): yield read_cache_entry(f, version) def read_index_dict(f) -> dict[bytes, Union[IndexEntry, ConflictedIndexEntry]]: """Read an index file and return it as a dictionary. Dict Key is tuple of path and stage number, as path alone is not unique Args: f: File object to read fromls. """ ret: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]] = {} for entry in read_index(f): stage = entry.stage() if stage == Stage.NORMAL: ret[entry.name] = IndexEntry.from_serialized(entry) else: existing = ret.setdefault(entry.name, ConflictedIndexEntry()) if isinstance(existing, IndexEntry): raise AssertionError(f"Non-conflicted entry for {entry.name!r} exists") if stage == Stage.MERGE_CONFLICT_ANCESTOR: existing.ancestor = IndexEntry.from_serialized(entry) elif stage == Stage.MERGE_CONFLICT_THIS: existing.this = IndexEntry.from_serialized(entry) elif stage == Stage.MERGE_CONFLICT_OTHER: existing.other = IndexEntry.from_serialized(entry) return ret def write_index( f: BinaryIO, entries: list[SerializedIndexEntry], version: Optional[int] = None ) -> None: """Write an index file. Args: f: File-like object to write to version: Version number to write entries: Iterable over the entries to write """ if version is None: version = DEFAULT_VERSION f.write(b"DIRC") f.write(struct.pack(b">LL", version, len(entries))) for entry in entries: write_cache_entry(f, entry, version) def write_index_dict( f: BinaryIO, entries: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]], version: Optional[int] = None, ) -> None: """Write an index file based on the contents of a dictionary. being careful to sort by path and then by stage. """ entries_list = [] for key in sorted(entries): value = entries[key] if isinstance(value, ConflictedIndexEntry): if value.ancestor is not None: entries_list.append( value.ancestor.serialize(key, Stage.MERGE_CONFLICT_ANCESTOR) ) if value.this is not None: entries_list.append( value.this.serialize(key, Stage.MERGE_CONFLICT_THIS) ) if value.other is not None: entries_list.append( value.other.serialize(key, Stage.MERGE_CONFLICT_OTHER) ) else: entries_list.append(value.serialize(key, Stage.NORMAL)) write_index(f, entries_list, version=version) def cleanup_mode(mode: int) -> int: """Cleanup a mode value. This will return a mode that can be stored in a tree object. Args: mode: Mode to clean up. Returns: mode """ if stat.S_ISLNK(mode): return stat.S_IFLNK elif stat.S_ISDIR(mode): return stat.S_IFDIR elif S_ISGITLINK(mode): return S_IFGITLINK ret = stat.S_IFREG | 0o644 if mode & 0o100: ret |= 0o111 return ret class Index: """A Git Index file.""" _byname: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]] def __init__(self, filename: Union[bytes, str], read=True) -> None: """Create an index object associated with the given filename. Args: filename: Path to the index file read: Whether to initialize the index from the given file, should it exist. """ self._filename = filename # TODO(jelmer): Store the version returned by read_index self._version = None self.clear() if read: self.read() @property def path(self): return self._filename def __repr__(self) -> str: return f"{self.__class__.__name__}({self._filename!r})" def write(self) -> None: """Write current contents of index to disk.""" f = GitFile(self._filename, "wb") try: f = SHA1Writer(f) write_index_dict(f, self._byname, version=self._version) finally: f.close() def read(self) -> None: """Read current contents of index from disk.""" if not os.path.exists(self._filename): return f = GitFile(self._filename, "rb") try: f = SHA1Reader(f) self.update(read_index_dict(f)) # FIXME: Additional data? f.read(os.path.getsize(self._filename) - f.tell() - 20) f.check_sha() finally: f.close() def __len__(self) -> int: """Number of entries in this index file.""" return len(self._byname) def __getitem__(self, key: bytes) -> Union[IndexEntry, ConflictedIndexEntry]: """Retrieve entry by relative path and stage. Returns: Either a IndexEntry or a ConflictedIndexEntry Raises KeyError: if the entry does not exist """ return self._byname[key] def __iter__(self) -> Iterator[bytes]: """Iterate over the paths and stages in this index.""" return iter(self._byname) def __contains__(self, key) -> bool: return key in self._byname def get_sha1(self, path: bytes) -> bytes: """Return the (git object) SHA1 for the object at a path.""" value = self[path] if isinstance(value, ConflictedIndexEntry): raise UnmergedEntries return value.sha def get_mode(self, path: bytes) -> int: """Return the POSIX file mode for the object at a path.""" value = self[path] if isinstance(value, ConflictedIndexEntry): raise UnmergedEntries return value.mode def iterobjects(self) -> Iterable[tuple[bytes, bytes, int]]: """Iterate over path, sha, mode tuples for use with commit_tree.""" for path in self: entry = self[path] if isinstance(entry, ConflictedIndexEntry): raise UnmergedEntries yield path, entry.sha, cleanup_mode(entry.mode) def has_conflicts(self) -> bool: for value in self._byname.values(): if isinstance(value, ConflictedIndexEntry): return True return False def clear(self) -> None: """Remove all contents from this index.""" self._byname = {} def __setitem__( self, name: bytes, value: Union[IndexEntry, ConflictedIndexEntry] ) -> None: assert isinstance(name, bytes) self._byname[name] = value def __delitem__(self, name: bytes) -> None: del self._byname[name] def iteritems( self, ) -> Iterator[tuple[bytes, Union[IndexEntry, ConflictedIndexEntry]]]: return iter(self._byname.items()) def items(self) -> Iterator[tuple[bytes, Union[IndexEntry, ConflictedIndexEntry]]]: return iter(self._byname.items()) def update( self, entries: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]] ) -> None: for key, value in entries.items(): self[key] = value def paths(self): yield from self._byname.keys() def changes_from_tree( self, object_store, tree: ObjectID, want_unchanged: bool = False ): """Find the differences between the contents of this index and a tree. Args: object_store: Object store to use for retrieving tree contents tree: SHA1 of the root tree want_unchanged: Whether unchanged files should be reported Returns: Iterator over tuples with (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) """ def lookup_entry(path): entry = self[path] return entry.sha, cleanup_mode(entry.mode) yield from changes_from_tree( self.paths(), lookup_entry, object_store, tree, want_unchanged=want_unchanged, ) def commit(self, object_store): """Create a new tree from an index. Args: object_store: Object store to save the tree in Returns: Root tree SHA """ return commit_tree(object_store, self.iterobjects()) def commit_tree( object_store: ObjectContainer, blobs: Iterable[tuple[bytes, bytes, int]] ) -> bytes: """Commit a new tree. Args: object_store: Object store to add trees to blobs: Iterable over blob path, sha, mode entries Returns: SHA1 of the created tree. """ trees: dict[bytes, Any] = {b"": {}} def add_tree(path): if path in trees: return trees[path] dirname, basename = pathsplit(path) t = add_tree(dirname) assert isinstance(basename, bytes) newtree = {} t[basename] = newtree trees[path] = newtree return newtree for path, sha, mode in blobs: tree_path, basename = pathsplit(path) tree = add_tree(tree_path) tree[basename] = (mode, sha) def build_tree(path): tree = Tree() for basename, entry in trees[path].items(): if isinstance(entry, dict): mode = stat.S_IFDIR sha = build_tree(pathjoin(path, basename)) else: (mode, sha) = entry tree.add(basename, mode, sha) object_store.add_object(tree) return tree.id return build_tree(b"") def commit_index(object_store: ObjectContainer, index: Index) -> bytes: """Create a new tree from an index. Args: object_store: Object store to save the tree in index: Index file Note: This function is deprecated, use index.commit() instead. Returns: Root tree sha. """ return commit_tree(object_store, index.iterobjects()) def changes_from_tree( names: Iterable[bytes], lookup_entry: Callable[[bytes], tuple[bytes, int]], object_store: ObjectContainer, tree: Optional[bytes], want_unchanged=False, ) -> Iterable[ tuple[ tuple[Optional[bytes], Optional[bytes]], tuple[Optional[int], Optional[int]], tuple[Optional[bytes], Optional[bytes]], ] ]: """Find the differences between the contents of a tree and a working copy. Args: names: Iterable of names in the working copy lookup_entry: Function to lookup an entry in the working copy object_store: Object store to use for retrieving tree contents tree: SHA1 of the root tree, or None for an empty tree want_unchanged: Whether unchanged files should be reported Returns: Iterator over tuples with (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) """ # TODO(jelmer): Support a include_trees option other_names = set(names) if tree is not None: for name, mode, sha in iter_tree_contents(object_store, tree): try: (other_sha, other_mode) = lookup_entry(name) except KeyError: # Was removed yield ((name, None), (mode, None), (sha, None)) else: other_names.remove(name) if want_unchanged or other_sha != sha or other_mode != mode: yield ((name, name), (mode, other_mode), (sha, other_sha)) # Mention added files for name in other_names: try: (other_sha, other_mode) = lookup_entry(name) except KeyError: pass else: yield ((None, name), (None, other_mode), (None, other_sha)) def index_entry_from_stat( stat_val, hex_sha: bytes, mode: Optional[int] = None, ): """Create a new index entry from a stat value. Args: stat_val: POSIX stat_result instance hex_sha: Hex sha of the object """ if mode is None: mode = cleanup_mode(stat_val.st_mode) return IndexEntry( stat_val.st_ctime, stat_val.st_mtime, stat_val.st_dev, stat_val.st_ino, mode, stat_val.st_uid, stat_val.st_gid, stat_val.st_size, hex_sha, ) if sys.platform == "win32": # On Windows, creating symlinks either requires administrator privileges # or developer mode. Raise a more helpful error when we're unable to # create symlinks # https://github.com/jelmer/dulwich/issues/1005 class WindowsSymlinkPermissionError(PermissionError): def __init__(self, errno, msg, filename) -> None: super(PermissionError, self).__init__( errno, "Unable to create symlink; " f"do you have developer mode enabled? {msg}", filename, ) def symlink(src, dst, target_is_directory=False, *, dir_fd=None): try: return os.symlink( src, dst, target_is_directory=target_is_directory, dir_fd=dir_fd ) except PermissionError as e: raise WindowsSymlinkPermissionError(e.errno, e.strerror, e.filename) from e else: symlink = os.symlink def build_file_from_blob( blob: Blob, mode: int, target_path: bytes, *, honor_filemode=True, tree_encoding="utf-8", symlink_fn=None, ): """Build a file or symlink on disk based on a Git object. Args: blob: The git object mode: File mode target_path: Path to write to honor_filemode: An optional flag to honor core.filemode setting in config file, default is core.filemode=True, change executable bit symlink: Function to use for creating symlinks Returns: stat object for the file """ try: oldstat = os.lstat(target_path) except FileNotFoundError: oldstat = None contents = blob.as_raw_string() if stat.S_ISLNK(mode): if oldstat: os.unlink(target_path) if sys.platform == "win32": # os.readlink on Python3 on Windows requires a unicode string. contents = contents.decode(tree_encoding) # type: ignore target_path = target_path.decode(tree_encoding) # type: ignore (symlink_fn or symlink)(contents, target_path) else: if oldstat is not None and oldstat.st_size == len(contents): with open(target_path, "rb") as f: if f.read() == contents: return oldstat with open(target_path, "wb") as f: # Write out file f.write(contents) if honor_filemode: os.chmod(target_path, mode) return os.lstat(target_path) INVALID_DOTNAMES = (b".git", b".", b"..", b"") def validate_path_element_default(element: bytes) -> bool: return element.lower() not in INVALID_DOTNAMES def validate_path_element_ntfs(element: bytes) -> bool: stripped = element.rstrip(b". ").lower() if stripped in INVALID_DOTNAMES: return False if stripped == b"git~1": return False return True def validate_path(path: bytes, element_validator=validate_path_element_default) -> bool: """Default path validator that just checks for .git/.""" parts = path.split(b"/") for p in parts: if not element_validator(p): return False else: return True def build_index_from_tree( root_path: Union[str, bytes], index_path: Union[str, bytes], object_store: ObjectContainer, tree_id: bytes, honor_filemode: bool = True, validate_path_element=validate_path_element_default, symlink_fn=None, ) -> None: """Generate and materialize index from a tree. Args: tree_id: Tree to materialize root_path: Target dir for materialized index files index_path: Target path for generated index object_store: Non-empty object store holding tree contents honor_filemode: An optional flag to honor core.filemode setting in config file, default is core.filemode=True, change executable bit validate_path_element: Function to validate path elements to check out; default just refuses .git and .. directories. Note: existing index is wiped and contents are not merged in a working dir. Suitable only for fresh clones. """ index = Index(index_path, read=False) if not isinstance(root_path, bytes): root_path = os.fsencode(root_path) for entry in iter_tree_contents(object_store, tree_id): if not validate_path(entry.path, validate_path_element): continue full_path = _tree_to_fs_path(root_path, entry.path) if not os.path.exists(os.path.dirname(full_path)): os.makedirs(os.path.dirname(full_path)) # TODO(jelmer): Merge new index into working tree if S_ISGITLINK(entry.mode): if not os.path.isdir(full_path): os.mkdir(full_path) st = os.lstat(full_path) # TODO(jelmer): record and return submodule paths else: obj = object_store[entry.sha] assert isinstance(obj, Blob) st = build_file_from_blob( obj, entry.mode, full_path, honor_filemode=honor_filemode, symlink_fn=symlink_fn, ) # Add file to index if not honor_filemode or S_ISGITLINK(entry.mode): # we can not use tuple slicing to build a new tuple, # because on windows that will convert the times to # longs, which causes errors further along st_tuple = ( entry.mode, st.st_ino, st.st_dev, st.st_nlink, st.st_uid, st.st_gid, st.st_size, st.st_atime, st.st_mtime, st.st_ctime, ) st = st.__class__(st_tuple) # default to a stage 0 index entry (normal) # when reading from the filesystem index[entry.path] = index_entry_from_stat(st, entry.sha) index.write() def blob_from_path_and_mode(fs_path: bytes, mode: int, tree_encoding="utf-8"): """Create a blob from a path and a stat object. Args: fs_path: Full file system path to file mode: File mode Returns: A `Blob` object """ assert isinstance(fs_path, bytes) blob = Blob() if stat.S_ISLNK(mode): if sys.platform == "win32": # os.readlink on Python3 on Windows requires a unicode string. blob.data = os.readlink(os.fsdecode(fs_path)).encode(tree_encoding) else: blob.data = os.readlink(fs_path) else: with open(fs_path, "rb") as f: blob.data = f.read() return blob def blob_from_path_and_stat(fs_path: bytes, st, tree_encoding="utf-8"): """Create a blob from a path and a stat object. Args: fs_path: Full file system path to file st: A stat object Returns: A `Blob` object """ return blob_from_path_and_mode(fs_path, st.st_mode, tree_encoding) def read_submodule_head(path: Union[str, bytes]) -> Optional[bytes]: """Read the head commit of a submodule. Args: path: path to the submodule Returns: HEAD sha, None if not a valid head/repository """ from .errors import NotGitRepository from .repo import Repo # Repo currently expects a "str", so decode if necessary. # TODO(jelmer): Perhaps move this into Repo() ? if not isinstance(path, str): path = os.fsdecode(path) try: repo = Repo(path) except NotGitRepository: return None try: return repo.head() except KeyError: return None def _has_directory_changed(tree_path: bytes, entry) -> bool: """Check if a directory has changed after getting an error. When handling an error trying to create a blob from a path, call this function. It will check if the path is a directory. If it's a directory and a submodule, check the submodule head to see if it's has changed. If not, consider the file as changed as Git tracked a file and not a directory. Return true if the given path should be considered as changed and False otherwise or if the path is not a directory. """ # This is actually a directory if os.path.exists(os.path.join(tree_path, b".git")): # Submodule head = read_submodule_head(tree_path) if entry.sha != head: return True else: # The file was changed to a directory, so consider it removed. return True return False def get_unstaged_changes( index: Index, root_path: Union[str, bytes], filter_blob_callback=None ): """Walk through an index and check for differences against working tree. Args: index: index to check root_path: path in which to find files Returns: iterator over paths with unstaged changes """ # For each entry in the index check the sha1 & ensure not staged if not isinstance(root_path, bytes): root_path = os.fsencode(root_path) for tree_path, entry in index.iteritems(): full_path = _tree_to_fs_path(root_path, tree_path) if isinstance(entry, ConflictedIndexEntry): # Conflicted files are always unstaged yield tree_path continue try: st = os.lstat(full_path) if stat.S_ISDIR(st.st_mode): if _has_directory_changed(tree_path, entry): yield tree_path continue if not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode): continue blob = blob_from_path_and_stat(full_path, st) if filter_blob_callback is not None: blob = filter_blob_callback(blob, tree_path) except FileNotFoundError: # The file was removed, so we assume that counts as # different from whatever file used to exist. yield tree_path else: if blob.id != entry.sha: yield tree_path os_sep_bytes = os.sep.encode("ascii") def _tree_to_fs_path(root_path: bytes, tree_path: bytes): """Convert a git tree path to a file system path. Args: root_path: Root filesystem path tree_path: Git tree path as bytes Returns: File system path. """ assert isinstance(tree_path, bytes) if os_sep_bytes != b"/": sep_corrected_path = tree_path.replace(b"/", os_sep_bytes) else: sep_corrected_path = tree_path return os.path.join(root_path, sep_corrected_path) def _fs_to_tree_path(fs_path: Union[str, bytes]) -> bytes: """Convert a file system path to a git tree path. Args: fs_path: File system path. Returns: Git tree path as bytes """ if not isinstance(fs_path, bytes): fs_path_bytes = os.fsencode(fs_path) else: fs_path_bytes = fs_path if os_sep_bytes != b"/": tree_path = fs_path_bytes.replace(os_sep_bytes, b"/") else: tree_path = fs_path_bytes return tree_path def index_entry_from_directory(st, path: bytes) -> Optional[IndexEntry]: if os.path.exists(os.path.join(path, b".git")): head = read_submodule_head(path) if head is None: return None return index_entry_from_stat(st, head, mode=S_IFGITLINK) return None def index_entry_from_path( path: bytes, object_store: Optional[ObjectContainer] = None ) -> Optional[IndexEntry]: """Create an index from a filesystem path. This returns an index value for files, symlinks and tree references. for directories and non-existent files it returns None Args: path: Path to create an index entry for object_store: Optional object store to save new blobs in Returns: An index entry; None for directories """ assert isinstance(path, bytes) st = os.lstat(path) if stat.S_ISDIR(st.st_mode): return index_entry_from_directory(st, path) if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode): blob = blob_from_path_and_stat(path, st) if object_store is not None: object_store.add_object(blob) return index_entry_from_stat(st, blob.id) return None def iter_fresh_entries( paths: Iterable[bytes], root_path: bytes, object_store: Optional[ObjectContainer] = None, ) -> Iterator[tuple[bytes, Optional[IndexEntry]]]: """Iterate over current versions of index entries on disk. Args: paths: Paths to iterate over root_path: Root path to access from object_store: Optional store to save new blobs in Returns: Iterator over path, index_entry """ for path in paths: p = _tree_to_fs_path(root_path, path) try: entry = index_entry_from_path(p, object_store=object_store) except (FileNotFoundError, IsADirectoryError): entry = None yield path, entry def iter_fresh_objects( paths: Iterable[bytes], root_path: bytes, include_deleted=False, object_store=None ) -> Iterator[tuple[bytes, Optional[bytes], Optional[int]]]: """Iterate over versions of objects on disk referenced by index. Args: root_path: Root path to access from include_deleted: Include deleted entries with sha and mode set to None object_store: Optional object store to report new items to Returns: Iterator over path, sha, mode """ for path, entry in iter_fresh_entries(paths, root_path, object_store=object_store): if entry is None: if include_deleted: yield path, None, None else: yield path, entry.sha, cleanup_mode(entry.mode) def refresh_index(index: Index, root_path: bytes) -> None: """Refresh the contents of an index. This is the equivalent to running 'git commit -a'. Args: index: Index to update root_path: Root filesystem path """ for path, entry in iter_fresh_entries(index, root_path): if entry: index[path] = entry class locked_index: """Lock the index while making modifications. Works as a context manager. """ def __init__(self, path: Union[bytes, str]) -> None: self._path = path def __enter__(self): self._file = GitFile(self._path, "wb") self._index = Index(self._path) return self._index def __exit__(self, exc_type, exc_value, traceback): if exc_type is not None: self._file.abort() return try: f = SHA1Writer(self._file) write_index_dict(f, self._index._byname) except BaseException: self._file.abort() else: f.close() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/lfs.py0000644000175100002000000000500314731042555015432 0ustar00runnerdocker# lfs.py -- Implementation of the LFS # Copyright (C) 2020 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # import hashlib import os import tempfile class LFSStore: """Stores objects on disk, indexed by SHA256.""" def __init__(self, path) -> None: self.path = path @classmethod def create(cls, lfs_dir): if not os.path.isdir(lfs_dir): os.mkdir(lfs_dir) os.mkdir(os.path.join(lfs_dir, "tmp")) os.mkdir(os.path.join(lfs_dir, "objects")) return cls(lfs_dir) @classmethod def from_repo(cls, repo, create=False): lfs_dir = os.path.join(repo.controldir, "lfs") if create: return cls.create(lfs_dir) return cls(lfs_dir) def _sha_path(self, sha): return os.path.join(self.path, "objects", sha[0:2], sha[2:4], sha) def open_object(self, sha): """Open an object by sha.""" try: return open(self._sha_path(sha), "rb") except FileNotFoundError as exc: raise KeyError(sha) from exc def write_object(self, chunks): """Write an object. Returns: object SHA """ sha = hashlib.sha256() tmpdir = os.path.join(self.path, "tmp") with tempfile.NamedTemporaryFile(dir=tmpdir, mode="wb", delete=False) as f: for chunk in chunks: sha.update(chunk) f.write(chunk) f.flush() tmppath = f.name path = self._sha_path(sha.hexdigest()) if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) os.rename(tmppath, path) return sha.hexdigest() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/line_ending.py0000644000175100002000000002657714731042555017144 0ustar00runnerdocker# line_ending.py -- Line ending conversion functions # Copyright (C) 2018-2018 Boris Feld # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # r"""All line-ending related functions, from conversions to config processing. Line-ending normalization is a complex beast. Here is some notes and details about how it seems to work. The normalization is a two-fold process that happens at two moments: - When reading a file from the index and to the working directory. For example when doing a ``git clone`` or ``git checkout`` call. We call this process the read filter in this module. - When writing a file to the index from the working directory. For example when doing a ``git add`` call. We call this process the write filter in this module. Note that when checking status (getting unstaged changes), whether or not normalization is done on write depends on whether or not the file in the working dir has also been normalized on read: - For autocrlf=true all files are always normalized on both read and write. - For autocrlf=input files are only normalized on write if they are newly "added". Since files which are already committed are not normalized on checkout into the working tree, they are also left alone when staging modifications into the index. One thing to know is that Git does line-ending normalization only on text files. How does Git know that a file is text? We can either mark a file as a text file, a binary file or ask Git to automatically decides. Git has an heuristic to detect if a file is a text file or a binary file. It seems based on the percentage of non-printable characters in files. The code for this heuristic is here: https://git.kernel.org/pub/scm/git/git.git/tree/convert.c#n46 Dulwich have an implementation with a slightly different heuristic, the `dulwich.patch.is_binary` function. The binary detection heuristic implementation is close to the one in JGit: https://github.com/eclipse/jgit/blob/f6873ffe522bbc3536969a3a3546bf9a819b92bf/org.eclipse.jgit/src/org/eclipse/jgit/diff/RawText.java#L300 There is multiple variables that impact the normalization. First, a repository can contains a ``.gitattributes`` file (or more than one...) that can further customize the operation on some file patterns, for example: \*.txt text Force all ``.txt`` files to be treated as text files and to have their lines endings normalized. \*.jpg -text Force all ``.jpg`` files to be treated as binary files and to not have their lines endings converted. \*.vcproj text eol=crlf Force all ``.vcproj`` files to be treated as text files and to have their lines endings converted into ``CRLF`` in working directory no matter the native EOL of the platform. \*.sh text eol=lf Force all ``.sh`` files to be treated as text files and to have their lines endings converted into ``LF`` in working directory no matter the native EOL of the platform. If the ``eol`` attribute is not defined, Git uses the ``core.eol`` configuration value described later. \* text=auto Force all files to be scanned by the text file heuristic detection and to have their line endings normalized in case they are detected as text files. Git also have a obsolete attribute named ``crlf`` that can be translated to the corresponding text attribute value. Then there are some configuration option (that can be defined at the repository or user level): - core.autocrlf - core.eol ``core.autocrlf`` is taken into account for all files that doesn't have a ``text`` attribute defined in ``.gitattributes``; it takes three possible values: - ``true``: This forces all files on the working directory to have CRLF line-endings in the working directory and convert line-endings to LF when writing to the index. When autocrlf is set to true, eol value is ignored. - ``input``: Quite similar to the ``true`` value but only force the write filter, ie line-ending of new files added to the index will get their line-endings converted to LF. - ``false`` (default): No normalization is done. ``core.eol`` is the top-level configuration to define the line-ending to use when applying the read_filer. It takes three possible values: - ``lf``: When normalization is done, force line-endings to be ``LF`` in the working directory. - ``crlf``: When normalization is done, force line-endings to be ``CRLF`` in the working directory. - ``native`` (default): When normalization is done, force line-endings to be the platform's native line ending. One thing to remember is when line-ending normalization is done on a file, Git always normalize line-ending to ``LF`` when writing to the index. There are sources that seems to indicate that Git won't do line-ending normalization when a file contains mixed line-endings. I think this logic might be in text / binary detection heuristic but couldn't find it yet. Sources: - https://git-scm.com/docs/git-config#git-config-coreeol - https://git-scm.com/docs/git-config#git-config-coreautocrlf - https://git-scm.com/docs/gitattributes#_checking_out_and_checking_in - https://adaptivepatchwork.com/2012/03/01/mind-the-end-of-your-line/ """ from .object_store import iter_tree_contents from .objects import Blob from .patch import is_binary CRLF = b"\r\n" LF = b"\n" def convert_crlf_to_lf(text_hunk): """Convert CRLF in text hunk into LF. Args: text_hunk: A bytes string representing a text hunk Returns: The text hunk with the same type, with CRLF replaced into LF """ return text_hunk.replace(CRLF, LF) def convert_lf_to_crlf(text_hunk): """Convert LF in text hunk into CRLF. Args: text_hunk: A bytes string representing a text hunk Returns: The text hunk with the same type, with LF replaced into CRLF """ # TODO find a more efficient way of doing it intermediary = text_hunk.replace(CRLF, LF) return intermediary.replace(LF, CRLF) def get_checkout_filter(core_eol, core_autocrlf, git_attributes): """Returns the correct checkout filter based on the passed arguments.""" # TODO this function should process the git_attributes for the path and if # the text attribute is not defined, fallback on the # get_checkout_filter_autocrlf function with the autocrlf value return get_checkout_filter_autocrlf(core_autocrlf) def get_checkin_filter(core_eol, core_autocrlf, git_attributes): """Returns the correct checkin filter based on the passed arguments.""" # TODO this function should process the git_attributes for the path and if # the text attribute is not defined, fallback on the # get_checkin_filter_autocrlf function with the autocrlf value return get_checkin_filter_autocrlf(core_autocrlf) def get_checkout_filter_autocrlf(core_autocrlf): """Returns the correct checkout filter base on autocrlf value. Args: core_autocrlf: The bytes configuration value of core.autocrlf. Valid values are: b'true', b'false' or b'input'. Returns: Either None if no filter has to be applied or a function accepting a single argument, a binary text hunk """ if core_autocrlf == b"true": return convert_lf_to_crlf return None def get_checkin_filter_autocrlf(core_autocrlf): """Returns the correct checkin filter base on autocrlf value. Args: core_autocrlf: The bytes configuration value of core.autocrlf. Valid values are: b'true', b'false' or b'input'. Returns: Either None if no filter has to be applied or a function accepting a single argument, a binary text hunk """ if core_autocrlf == b"true" or core_autocrlf == b"input": return convert_crlf_to_lf # Checking filter should never be `convert_lf_to_crlf` return None class BlobNormalizer: """An object to store computation result of which filter to apply based on configuration, gitattributes, path and operation (checkin or checkout). """ def __init__(self, config_stack, gitattributes) -> None: self.config_stack = config_stack self.gitattributes = gitattributes # Compute which filters we needs based on parameters try: core_eol = config_stack.get("core", "eol") except KeyError: core_eol = "native" try: core_autocrlf = config_stack.get("core", "autocrlf").lower() except KeyError: core_autocrlf = False self.fallback_read_filter = get_checkout_filter( core_eol, core_autocrlf, self.gitattributes ) self.fallback_write_filter = get_checkin_filter( core_eol, core_autocrlf, self.gitattributes ) def checkin_normalize(self, blob, tree_path): """Normalize a blob during a checkin operation.""" if self.fallback_write_filter is not None: return normalize_blob( blob, self.fallback_write_filter, binary_detection=True ) return blob def checkout_normalize(self, blob, tree_path): """Normalize a blob during a checkout operation.""" if self.fallback_read_filter is not None: return normalize_blob( blob, self.fallback_read_filter, binary_detection=True ) return blob def normalize_blob(blob, conversion, binary_detection): """Takes a blob as input returns either the original blob if binary_detection is True and the blob content looks like binary, else return a new blob with converted data. """ # Read the original blob data = blob.data # If we need to detect if a file is binary and the file is detected as # binary, do not apply the conversion function and return the original # chunked text if binary_detection is True: if is_binary(data): return blob # Now apply the conversion converted_data = conversion(data) new_blob = Blob() new_blob.data = converted_data return new_blob class TreeBlobNormalizer(BlobNormalizer): def __init__(self, config_stack, git_attributes, object_store, tree=None) -> None: super().__init__(config_stack, git_attributes) if tree: self.existing_paths = { name for name, _, _ in iter_tree_contents(object_store, tree) } else: self.existing_paths = set() def checkin_normalize(self, blob, tree_path): # Existing files should only be normalized on checkin if it was # previously normalized on checkout if ( self.fallback_read_filter is not None or tree_path not in self.existing_paths ): return super().checkin_normalize(blob, tree_path) return blob ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/log_utils.py0000644000175100002000000000514114731042555016652 0ustar00runnerdocker# log_utils.py -- Logging utilities for Dulwich # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Logging utilities for Dulwich. Any module that uses logging needs to do compile-time initialization to set up the logging environment. Since Dulwich is also used as a library, clients may not want to see any logging output. In that case, we need to use a special handler to suppress spurious warnings like "No handlers could be found for logger dulwich.foo". For details on the _NullHandler approach, see: http://docs.python.org/library/logging.html#configuring-logging-for-a-library For many modules, the only function from the logging module they need is getLogger; this module exports that function for convenience. If a calling module needs something else, it can import the standard logging module directly. """ import logging import sys getLogger = logging.getLogger class _NullHandler(logging.Handler): """No-op logging handler to avoid unexpected logging warnings.""" def emit(self, record) -> None: pass _NULL_HANDLER = _NullHandler() _DULWICH_LOGGER = getLogger("dulwich") _DULWICH_LOGGER.addHandler(_NULL_HANDLER) def default_logging_config() -> None: """Set up the default Dulwich loggers.""" remove_null_handler() logging.basicConfig( level=logging.INFO, stream=sys.stderr, format="%(asctime)s %(levelname)s: %(message)s", ) def remove_null_handler() -> None: """Remove the null handler from the Dulwich loggers. If a caller wants to set up logging using something other than default_logging_config, calling this function first is a minor optimization to avoid the overhead of using the _NullHandler. """ _DULWICH_LOGGER.removeHandler(_NULL_HANDLER) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/lru_cache.py0000644000175100002000000003654314731042555016610 0ustar00runnerdocker# lru_cache.py -- Simple LRU cache for dulwich # Copyright (C) 2006, 2008 Canonical Ltd # Copyright (C) 2022 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """A simple least-recently-used (LRU) cache.""" from collections.abc import Iterable, Iterator from typing import Callable, Generic, Optional, TypeVar _null_key = object() K = TypeVar("K") V = TypeVar("V") class _LRUNode(Generic[K, V]): """This maintains the linked-list which is the lru internals.""" __slots__ = ("cleanup", "key", "next_key", "prev", "size", "value") prev: Optional["_LRUNode[K, V]"] next_key: K size: Optional[int] def __init__(self, key: K, value: V, cleanup=None) -> None: self.prev = None self.next_key = _null_key # type: ignore self.key = key self.value = value self.cleanup = cleanup # TODO: We could compute this 'on-the-fly' like we used to, and remove # one pointer from this object, we just need to decide if it # actually costs us much of anything in normal usage self.size = None def __repr__(self) -> str: if self.prev is None: prev_key = None else: prev_key = self.prev.key return f"{self.__class__.__name__}({self.key!r} n:{self.next_key!r} p:{prev_key!r})" def run_cleanup(self) -> None: if self.cleanup is not None: self.cleanup(self.key, self.value) self.cleanup = None # Just make sure to break any refcycles, etc del self.value class LRUCache(Generic[K, V]): """A class which manages a cache of entries, removing unused ones.""" _least_recently_used: Optional[_LRUNode[K, V]] _most_recently_used: Optional[_LRUNode[K, V]] def __init__( self, max_cache: int = 100, after_cleanup_count: Optional[int] = None ) -> None: self._cache: dict[K, _LRUNode[K, V]] = {} # The "HEAD" of the lru linked list self._most_recently_used = None # The "TAIL" of the lru linked list self._least_recently_used = None self._update_max_cache(max_cache, after_cleanup_count) def __contains__(self, key: K) -> bool: return key in self._cache def __getitem__(self, key: K) -> V: cache = self._cache node = cache[key] # Inlined from _record_access to decrease the overhead of __getitem__ # We also have more knowledge about structure if __getitem__ is # succeeding, then we know that self._most_recently_used must not be # None, etc. mru = self._most_recently_used if node is mru: # Nothing to do, this node is already at the head of the queue return node.value # Remove this node from the old location node_prev = node.prev next_key = node.next_key # benchmarking shows that the lookup of _null_key in globals is faster # than the attribute lookup for (node is self._least_recently_used) if next_key is _null_key: # 'node' is the _least_recently_used, because it doesn't have a # 'next' item. So move the current lru to the previous node. self._least_recently_used = node_prev else: node_next = cache[next_key] node_next.prev = node_prev assert node_prev assert mru node_prev.next_key = next_key # Insert this node at the front of the list node.next_key = mru.key mru.prev = node self._most_recently_used = node node.prev = None return node.value def __len__(self) -> int: return len(self._cache) def _walk_lru(self) -> Iterator[_LRUNode[K, V]]: """Walk the LRU list, only meant to be used in tests.""" node = self._most_recently_used if node is not None: if node.prev is not None: raise AssertionError( "the _most_recently_used entry is not" " supposed to have a previous entry" f" {node}" ) while node is not None: if node.next_key is _null_key: if node is not self._least_recently_used: raise AssertionError( "only the last node should have" f" no next value: {node}" ) node_next = None else: node_next = self._cache[node.next_key] if node_next.prev is not node: raise AssertionError( "inconsistency found, node.next.prev" f" != node: {node}" ) if node.prev is None: if node is not self._most_recently_used: raise AssertionError( "only the _most_recently_used should" f" not have a previous node: {node}" ) else: if node.prev.next_key != node.key: raise AssertionError( "inconsistency found, node.prev.next" f" != node: {node}" ) yield node node = node_next def add( self, key: K, value: V, cleanup: Optional[Callable[[K, V], None]] = None ) -> None: """Add a new value to the cache. Also, if the entry is ever removed from the cache, call cleanup(key, value). Args: key: The key to store it under value: The object to store cleanup: None or a function taking (key, value) to indicate 'value' should be cleaned up. """ if key is _null_key: raise ValueError("cannot use _null_key as a key") if key in self._cache: node = self._cache[key] node.run_cleanup() node.value = value node.cleanup = cleanup else: node = _LRUNode(key, value, cleanup=cleanup) self._cache[key] = node self._record_access(node) if len(self._cache) > self._max_cache: # Trigger the cleanup self.cleanup() def cache_size(self) -> int: """Get the number of entries we will cache.""" return self._max_cache def get(self, key: K, default: Optional[V] = None) -> Optional[V]: node = self._cache.get(key, None) if node is None: return default self._record_access(node) return node.value def keys(self) -> Iterable[K]: """Get the list of keys currently cached. Note that values returned here may not be available by the time you request them later. This is simply meant as a peak into the current state. Returns: An unordered list of keys that are currently cached. """ return self._cache.keys() def items(self) -> dict[K, V]: """Get the key:value pairs as a dict.""" return {k: n.value for k, n in self._cache.items()} def cleanup(self) -> None: """Clear the cache until it shrinks to the requested size. This does not completely wipe the cache, just makes sure it is under the after_cleanup_count. """ # Make sure the cache is shrunk to the correct size while len(self._cache) > self._after_cleanup_count: self._remove_lru() def __setitem__(self, key: K, value: V) -> None: """Add a value to the cache, there will be no cleanup function.""" self.add(key, value, cleanup=None) def _record_access(self, node: _LRUNode[K, V]) -> None: """Record that key was accessed.""" # Move 'node' to the front of the queue if self._most_recently_used is None: self._most_recently_used = node self._least_recently_used = node return elif node is self._most_recently_used: # Nothing to do, this node is already at the head of the queue return # We've taken care of the tail pointer, remove the node, and insert it # at the front # REMOVE if node is self._least_recently_used: self._least_recently_used = node.prev if node.prev is not None: node.prev.next_key = node.next_key if node.next_key is not _null_key: node_next = self._cache[node.next_key] node_next.prev = node.prev # INSERT node.next_key = self._most_recently_used.key self._most_recently_used.prev = node self._most_recently_used = node node.prev = None def _remove_node(self, node: _LRUNode[K, V]) -> None: if node is self._least_recently_used: self._least_recently_used = node.prev self._cache.pop(node.key) # If we have removed all entries, remove the head pointer as well if self._least_recently_used is None: self._most_recently_used = None node.run_cleanup() # Now remove this node from the linked list if node.prev is not None: node.prev.next_key = node.next_key if node.next_key is not _null_key: node_next = self._cache[node.next_key] node_next.prev = node.prev # And remove this node's pointers node.prev = None node.next_key = _null_key # type: ignore def _remove_lru(self) -> None: """Remove one entry from the lru, and handle consequences. If there are no more references to the lru, then this entry should be removed from the cache. """ assert self._least_recently_used self._remove_node(self._least_recently_used) def clear(self) -> None: """Clear out all of the cache.""" # Clean up in LRU order while self._cache: self._remove_lru() def resize(self, max_cache: int, after_cleanup_count: Optional[int] = None) -> None: """Change the number of entries that will be cached.""" self._update_max_cache(max_cache, after_cleanup_count=after_cleanup_count) def _update_max_cache(self, max_cache, after_cleanup_count=None) -> None: self._max_cache = max_cache if after_cleanup_count is None: self._after_cleanup_count = self._max_cache * 8 / 10 else: self._after_cleanup_count = min(after_cleanup_count, self._max_cache) self.cleanup() class LRUSizeCache(LRUCache[K, V]): """An LRUCache that removes things based on the size of the values. This differs in that it doesn't care how many actual items there are, it just restricts the cache to be cleaned up after so much data is stored. The size of items added will be computed using compute_size(value), which defaults to len() if not supplied. """ _compute_size: Callable[[V], int] def __init__( self, max_size: int = 1024 * 1024, after_cleanup_size: Optional[int] = None, compute_size: Optional[Callable[[V], int]] = None, ) -> None: """Create a new LRUSizeCache. Args: max_size: The max number of bytes to store before we start clearing out entries. after_cleanup_size: After cleaning up, shrink everything to this size. compute_size: A function to compute the size of the values. We use a function here, so that you can pass 'len' if you are just using simple strings, or a more complex function if you are using something like a list of strings, or even a custom object. The function should take the form "compute_size(value) => integer". If not supplied, it defaults to 'len()' """ self._value_size = 0 if compute_size is None: self._compute_size = len # type: ignore else: self._compute_size = compute_size self._update_max_size(max_size, after_cleanup_size=after_cleanup_size) LRUCache.__init__(self, max_cache=max(int(max_size / 512), 1)) def add( self, key: K, value: V, cleanup: Optional[Callable[[K, V], None]] = None ) -> None: """Add a new value to the cache. Also, if the entry is ever removed from the cache, call cleanup(key, value). Args: key: The key to store it under value: The object to store cleanup: None or a function taking (key, value) to indicate 'value' should be cleaned up. """ if key is _null_key: raise ValueError("cannot use _null_key as a key") node = self._cache.get(key, None) value_len = self._compute_size(value) if value_len >= self._after_cleanup_size: # The new value is 'too big to fit', as it would fill up/overflow # the cache all by itself if node is not None: # We won't be replacing the old node, so just remove it self._remove_node(node) if cleanup is not None: cleanup(key, value) return if node is None: node = _LRUNode(key, value, cleanup=cleanup) self._cache[key] = node else: assert node.size is not None self._value_size -= node.size node.size = value_len self._value_size += value_len self._record_access(node) if self._value_size > self._max_size: # Time to cleanup self.cleanup() def cleanup(self) -> None: """Clear the cache until it shrinks to the requested size. This does not completely wipe the cache, just makes sure it is under the after_cleanup_size. """ # Make sure the cache is shrunk to the correct size while self._value_size > self._after_cleanup_size: self._remove_lru() def _remove_node(self, node: _LRUNode[K, V]) -> None: assert node.size is not None self._value_size -= node.size LRUCache._remove_node(self, node) def resize(self, max_size: int, after_cleanup_size: Optional[int] = None) -> None: """Change the number of bytes that will be cached.""" self._update_max_size(max_size, after_cleanup_size=after_cleanup_size) max_cache = max(int(max_size / 512), 1) self._update_max_cache(max_cache) def _update_max_size( self, max_size: int, after_cleanup_size: Optional[int] = None ) -> None: self._max_size = max_size if after_cleanup_size is None: self._after_cleanup_size = self._max_size * 8 // 10 else: self._after_cleanup_size = min(after_cleanup_size, self._max_size) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/mailmap.py0000644000175100002000000001010414731042555016264 0ustar00runnerdocker# mailmap.py -- Mailmap reader # Copyright (C) 2018 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Mailmap file reader.""" from typing import Optional def parse_identity(text): # TODO(jelmer): Integrate this with dulwich.fastexport.split_email and # dulwich.repo.check_user_identity (name, email) = text.rsplit(b"<", 1) name = name.strip() email = email.rstrip(b">").strip() if not name: name = None if not email: email = None return (name, email) def read_mailmap(f): """Read a mailmap. Args: f: File-like object to read from Returns: Iterator over ((canonical_name, canonical_email), (from_name, from_email)) tuples """ for line in f: # Remove comments line = line.split(b"#")[0] line = line.strip() if not line: continue (canonical_identity, from_identity) = line.split(b">", 1) canonical_identity += b">" if from_identity.strip(): parsed_from_identity = parse_identity(from_identity) else: parsed_from_identity = None parsed_canonical_identity = parse_identity(canonical_identity) yield parsed_canonical_identity, parsed_from_identity class Mailmap: """Class for accessing a mailmap file.""" def __init__(self, map=None) -> None: self._table: dict[tuple[Optional[str], Optional[str]], tuple[str, str]] = {} if map: for canonical_identity, from_identity in map: self.add_entry(canonical_identity, from_identity) def add_entry(self, canonical_identity, from_identity=None) -> None: """Add an entry to the mail mail. Any of the fields can be None, but at least one of them needs to be set. Args: canonical_identity: The canonical identity (tuple) from_identity: The from identity (tuple) """ if from_identity is None: from_name, from_email = None, None else: (from_name, from_email) = from_identity (canonical_name, canonical_email) = canonical_identity if from_name is None and from_email is None: self._table[canonical_name, None] = canonical_identity self._table[None, canonical_email] = canonical_identity else: self._table[from_name, from_email] = canonical_identity def lookup(self, identity): """Lookup an identity in this mailmail.""" if not isinstance(identity, tuple): was_tuple = False identity = parse_identity(identity) else: was_tuple = True for query in [identity, (None, identity[1]), (identity[0], None)]: canonical_identity = self._table.get(query) if canonical_identity is not None: identity = ( canonical_identity[0] or identity[0], canonical_identity[1] or identity[1], ) break if was_tuple: return identity else: return identity[0] + b" <" + identity[1] + b">" @classmethod def from_path(cls, path): with open(path, "rb") as f: return cls(read_mailmap(f)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/object_store.py0000644000175100002000000016532014731042555017341 0ustar00runnerdocker# object_store.py -- Object store for git objects # Copyright (C) 2008-2013 Jelmer Vernooij # and others # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Git object store interfaces and implementation.""" import binascii import os import stat import sys import warnings from collections.abc import Iterable, Iterator, Sequence from contextlib import suppress from io import BytesIO from typing import ( Callable, Optional, Protocol, cast, ) from .errors import NotTreeError from .file import GitFile from .objects import ( S_ISGITLINK, ZERO_SHA, Blob, Commit, ObjectID, ShaFile, Tag, Tree, TreeEntry, hex_to_filename, hex_to_sha, object_class, sha_to_hex, valid_hexsha, ) from .pack import ( PACK_SPOOL_FILE_MAX_SIZE, ObjectContainer, Pack, PackData, PackedObjectContainer, PackFileDisappeared, PackHint, PackIndexer, PackInflater, PackStreamCopier, UnpackedObject, extend_pack, full_unpacked_object, generate_unpacked_objects, iter_sha1, load_pack_index_file, pack_objects_to_data, write_pack_data, write_pack_index, ) from .protocol import DEPTH_INFINITE from .refs import PEELED_TAG_SUFFIX, Ref INFODIR = "info" PACKDIR = "pack" # use permissions consistent with Git; just readable by everyone # TODO: should packs also be non-writable on Windows? if so, that # would requite some rather significant adjustments to the test suite PACK_MODE = 0o444 if sys.platform != "win32" else 0o644 class PackContainer(Protocol): def add_pack(self) -> tuple[BytesIO, Callable[[], None], Callable[[], None]]: """Add a new pack.""" class BaseObjectStore: """Object store interface.""" def determine_wants_all( self, refs: dict[Ref, ObjectID], depth: Optional[int] = None ) -> list[ObjectID]: def _want_deepen(sha): if not depth: return False if depth == DEPTH_INFINITE: return True return depth > self._get_depth(sha) return [ sha for (ref, sha) in refs.items() if (sha not in self or _want_deepen(sha)) and not ref.endswith(PEELED_TAG_SUFFIX) and not sha == ZERO_SHA ] def contains_loose(self, sha) -> bool: """Check if a particular object is present by SHA1 and is loose.""" raise NotImplementedError(self.contains_loose) def __contains__(self, sha1: bytes) -> bool: """Check if a particular object is present by SHA1. This method makes no distinction between loose and packed objects. """ return self.contains_loose(sha1) @property def packs(self): """Iterable of pack objects.""" raise NotImplementedError def get_raw(self, name) -> tuple[int, bytes]: """Obtain the raw text for an object. Args: name: sha for the object. Returns: tuple with numeric type and object contents. """ raise NotImplementedError(self.get_raw) def __getitem__(self, sha1: ObjectID) -> ShaFile: """Obtain an object by SHA1.""" type_num, uncomp = self.get_raw(sha1) return ShaFile.from_raw_string(type_num, uncomp, sha=sha1) def __iter__(self): """Iterate over the SHAs that are present in this store.""" raise NotImplementedError(self.__iter__) def add_object(self, obj) -> None: """Add a single object to this object store.""" raise NotImplementedError(self.add_object) def add_objects(self, objects, progress=None) -> None: """Add a set of objects to this object store. Args: objects: Iterable over a list of (object, path) tuples """ raise NotImplementedError(self.add_objects) def tree_changes( self, source, target, want_unchanged=False, include_trees=False, change_type_same=False, rename_detector=None, ): """Find the differences between the contents of two trees. Args: source: SHA1 of the source tree target: SHA1 of the target tree want_unchanged: Whether unchanged files should be reported include_trees: Whether to include trees change_type_same: Whether to report files changing type in the same entry. Returns: Iterator over tuples with (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) """ from .diff_tree import tree_changes for change in tree_changes( self, source, target, want_unchanged=want_unchanged, include_trees=include_trees, change_type_same=change_type_same, rename_detector=rename_detector, ): yield ( (change.old.path, change.new.path), (change.old.mode, change.new.mode), (change.old.sha, change.new.sha), ) def iter_tree_contents(self, tree_id, include_trees=False): """Iterate the contents of a tree and all subtrees. Iteration is depth-first pre-order, as in e.g. os.walk. Args: tree_id: SHA1 of the tree. include_trees: If True, include tree objects in the iteration. Returns: Iterator over TreeEntry namedtuples for all the objects in a tree. """ warnings.warn( "Please use dulwich.object_store.iter_tree_contents", DeprecationWarning, stacklevel=2, ) return iter_tree_contents(self, tree_id, include_trees=include_trees) def iterobjects_subset( self, shas: Iterable[bytes], *, allow_missing: bool = False ) -> Iterator[ShaFile]: for sha in shas: try: yield self[sha] except KeyError: if not allow_missing: raise def find_missing_objects( self, haves, wants, shallow=None, progress=None, get_tagged=None, get_parents=lambda commit: commit.parents, ): """Find the missing objects required for a set of revisions. Args: haves: Iterable over SHAs already in common. wants: Iterable over SHAs of objects to fetch. shallow: Set of shallow commit SHA1s to skip progress: Simple progress function that will be called with updated progress strings. get_tagged: Function that returns a dict of pointed-to sha -> tag sha for including tags. get_parents: Optional function for getting the parents of a commit. Returns: Iterator over (sha, path) pairs. """ warnings.warn("Please use MissingObjectFinder(store)", DeprecationWarning) finder = MissingObjectFinder( self, haves=haves, wants=wants, shallow=shallow, progress=progress, get_tagged=get_tagged, get_parents=get_parents, ) return iter(finder) def find_common_revisions(self, graphwalker): """Find which revisions this store has in common using graphwalker. Args: graphwalker: A graphwalker object. Returns: List of SHAs that are in common """ haves = [] sha = next(graphwalker) while sha: if sha in self: haves.append(sha) graphwalker.ack(sha) sha = next(graphwalker) return haves def generate_pack_data( self, have, want, shallow=None, progress=None, ofs_delta=True ) -> tuple[int, Iterator[UnpackedObject]]: """Generate pack data objects for a set of wants/haves. Args: have: List of SHA1s of objects that should not be sent want: List of SHA1s of objects that should be sent shallow: Set of shallow commit SHA1s to skip ofs_delta: Whether OFS deltas can be included progress: Optional progress reporting method """ # Note that the pack-specific implementation below is more efficient, # as it reuses deltas missing_objects = MissingObjectFinder( self, haves=have, wants=want, shallow=shallow, progress=progress ) object_ids = list(missing_objects) return pack_objects_to_data( [(self[oid], path) for oid, path in object_ids], ofs_delta=ofs_delta, progress=progress, ) def peel_sha(self, sha): """Peel all tags from a SHA. Args: sha: The object SHA to peel. Returns: The fully-peeled SHA1 of a tag object, after peeling all intermediate tags; if the original ref does not point to a tag, this will equal the original SHA1. """ warnings.warn( "Please use dulwich.object_store.peel_sha()", DeprecationWarning, stacklevel=2, ) return peel_sha(self, sha)[1] def _get_depth( self, head, get_parents=lambda commit: commit.parents, max_depth=None, ): """Return the current available depth for the given head. For commits with multiple parents, the largest possible depth will be returned. Args: head: commit to start from get_parents: optional function for getting the parents of a commit max_depth: maximum depth to search """ if head not in self: return 0 current_depth = 1 queue = [(head, current_depth)] while queue and (max_depth is None or current_depth < max_depth): e, depth = queue.pop(0) current_depth = max(current_depth, depth) cmt = self[e] if isinstance(cmt, Tag): _cls, sha = cmt.object cmt = self[sha] queue.extend( (parent, depth + 1) for parent in get_parents(cmt) if parent in self ) return current_depth def close(self) -> None: """Close any files opened by this object store.""" # Default implementation is a NO-OP def iter_prefix(self, prefix: bytes) -> Iterator[ObjectID]: """Iterate over all SHA1s that start with a given prefix. The default implementation is a naive iteration over all objects. However, subclasses may override this method with more efficient implementations. """ for sha in self: if sha.startswith(prefix): yield sha class PackBasedObjectStore(BaseObjectStore): def __init__(self, pack_compression_level=-1) -> None: self._pack_cache: dict[str, Pack] = {} self.pack_compression_level = pack_compression_level def add_pack(self) -> tuple[BytesIO, Callable[[], None], Callable[[], None]]: """Add a new pack to this object store.""" raise NotImplementedError(self.add_pack) def add_pack_data( self, count: int, unpacked_objects: Iterator[UnpackedObject], progress=None ) -> None: """Add pack data to this object store. Args: count: Number of items to add pack_data: Iterator over pack data tuples """ if count == 0: # Don't bother writing an empty pack file return f, commit, abort = self.add_pack() try: write_pack_data( f.write, unpacked_objects, num_records=count, progress=progress, compression_level=self.pack_compression_level, ) except BaseException: abort() raise else: return commit() @property def alternates(self): return [] def contains_packed(self, sha) -> bool: """Check if a particular object is present by SHA1 and is packed. This does not check alternates. """ for pack in self.packs: try: if sha in pack: return True except PackFileDisappeared: pass return False def __contains__(self, sha) -> bool: """Check if a particular object is present by SHA1. This method makes no distinction between loose and packed objects. """ if self.contains_packed(sha) or self.contains_loose(sha): return True for alternate in self.alternates: if sha in alternate: return True return False def _add_cached_pack(self, base_name, pack) -> None: """Add a newly appeared pack to the cache by path.""" prev_pack = self._pack_cache.get(base_name) if prev_pack is not pack: self._pack_cache[base_name] = pack if prev_pack: prev_pack.close() def generate_pack_data( self, have, want, shallow=None, progress=None, ofs_delta=True ) -> tuple[int, Iterator[UnpackedObject]]: """Generate pack data objects for a set of wants/haves. Args: have: List of SHA1s of objects that should not be sent want: List of SHA1s of objects that should be sent shallow: Set of shallow commit SHA1s to skip ofs_delta: Whether OFS deltas can be included progress: Optional progress reporting method """ missing_objects = MissingObjectFinder( self, haves=have, wants=want, shallow=shallow, progress=progress ) remote_has = missing_objects.get_remote_has() object_ids = list(missing_objects) return len(object_ids), generate_unpacked_objects( cast(PackedObjectContainer, self), object_ids, progress=progress, ofs_delta=ofs_delta, other_haves=remote_has, ) def _clear_cached_packs(self) -> None: pack_cache = self._pack_cache self._pack_cache = {} while pack_cache: (name, pack) = pack_cache.popitem() pack.close() def _iter_cached_packs(self): return self._pack_cache.values() def _update_pack_cache(self) -> list[Pack]: raise NotImplementedError(self._update_pack_cache) def close(self) -> None: self._clear_cached_packs() @property def packs(self): """List with pack objects.""" return list(self._iter_cached_packs()) + list(self._update_pack_cache()) def _iter_alternate_objects(self): """Iterate over the SHAs of all the objects in alternate stores.""" for alternate in self.alternates: yield from alternate def _iter_loose_objects(self): """Iterate over the SHAs of all loose objects.""" raise NotImplementedError(self._iter_loose_objects) def _get_loose_object(self, sha) -> Optional[ShaFile]: raise NotImplementedError(self._get_loose_object) def _remove_loose_object(self, sha) -> None: raise NotImplementedError(self._remove_loose_object) def _remove_pack(self, name) -> None: raise NotImplementedError(self._remove_pack) def pack_loose_objects(self): """Pack loose objects. Returns: Number of objects packed """ objects = set() for sha in self._iter_loose_objects(): objects.add((self._get_loose_object(sha), None)) self.add_objects(list(objects)) for obj, path in objects: self._remove_loose_object(obj.id) return len(objects) def repack(self): """Repack the packs in this repository. Note that this implementation is fairly naive and currently keeps all objects in memory while it repacks. """ loose_objects = set() for sha in self._iter_loose_objects(): loose_objects.add(self._get_loose_object(sha)) objects = {(obj, None) for obj in loose_objects} old_packs = {p.name(): p for p in self.packs} for name, pack in old_packs.items(): objects.update((obj, None) for obj in pack.iterobjects()) # The name of the consolidated pack might match the name of a # pre-existing pack. Take care not to remove the newly created # consolidated pack. consolidated = self.add_objects(objects) old_packs.pop(consolidated.name(), None) for obj in loose_objects: self._remove_loose_object(obj.id) for name, pack in old_packs.items(): self._remove_pack(pack) self._update_pack_cache() return len(objects) def __iter__(self): """Iterate over the SHAs that are present in this store.""" self._update_pack_cache() for pack in self._iter_cached_packs(): try: yield from pack except PackFileDisappeared: pass yield from self._iter_loose_objects() yield from self._iter_alternate_objects() def contains_loose(self, sha): """Check if a particular object is present by SHA1 and is loose. This does not check alternates. """ return self._get_loose_object(sha) is not None def get_raw(self, name): """Obtain the raw fulltext for an object. Args: name: sha for the object. Returns: tuple with numeric type and object contents. """ if name == ZERO_SHA: raise KeyError(name) if len(name) == 40: sha = hex_to_sha(name) hexsha = name elif len(name) == 20: sha = name hexsha = None else: raise AssertionError(f"Invalid object name {name!r}") for pack in self._iter_cached_packs(): try: return pack.get_raw(sha) except (KeyError, PackFileDisappeared): pass if hexsha is None: hexsha = sha_to_hex(name) ret = self._get_loose_object(hexsha) if ret is not None: return ret.type_num, ret.as_raw_string() # Maybe something else has added a pack with the object # in the mean time? for pack in self._update_pack_cache(): try: return pack.get_raw(sha) except KeyError: pass for alternate in self.alternates: try: return alternate.get_raw(hexsha) except KeyError: pass raise KeyError(hexsha) def iter_unpacked_subset( self, shas, *, include_comp=False, allow_missing: bool = False, convert_ofs_delta: bool = True, ) -> Iterator[ShaFile]: todo: set[bytes] = set(shas) for p in self._iter_cached_packs(): for unpacked in p.iter_unpacked_subset( todo, include_comp=include_comp, allow_missing=True, convert_ofs_delta=convert_ofs_delta, ): yield unpacked hexsha = sha_to_hex(unpacked.sha()) todo.remove(hexsha) # Maybe something else has added a pack with the object # in the mean time? for p in self._update_pack_cache(): for unpacked in p.iter_unpacked_subset( todo, include_comp=include_comp, allow_missing=True, convert_ofs_delta=convert_ofs_delta, ): yield unpacked hexsha = sha_to_hex(unpacked.sha()) todo.remove(hexsha) for alternate in self.alternates: for unpacked in alternate.iter_unpacked_subset( todo, include_comp=include_comp, allow_missing=True, convert_ofs_delta=convert_ofs_delta, ): yield unpacked hexsha = sha_to_hex(unpacked.sha()) todo.remove(hexsha) def iterobjects_subset( self, shas: Iterable[bytes], *, allow_missing: bool = False ) -> Iterator[ShaFile]: todo: set[bytes] = set(shas) for p in self._iter_cached_packs(): for o in p.iterobjects_subset(todo, allow_missing=True): yield o todo.remove(o.id) # Maybe something else has added a pack with the object # in the mean time? for p in self._update_pack_cache(): for o in p.iterobjects_subset(todo, allow_missing=True): yield o todo.remove(o.id) for alternate in self.alternates: for o in alternate.iterobjects_subset(todo, allow_missing=True): yield o todo.remove(o.id) for oid in todo: o = self._get_loose_object(oid) if o is not None: yield o elif not allow_missing: raise KeyError(oid) def get_unpacked_object( self, sha1: bytes, *, include_comp: bool = False ) -> UnpackedObject: """Obtain the unpacked object. Args: sha1: sha for the object. """ if sha1 == ZERO_SHA: raise KeyError(sha1) if len(sha1) == 40: sha = hex_to_sha(sha1) hexsha = sha1 elif len(sha1) == 20: sha = sha1 hexsha = None else: raise AssertionError(f"Invalid object sha1 {sha1!r}") for pack in self._iter_cached_packs(): try: return pack.get_unpacked_object(sha, include_comp=include_comp) except (KeyError, PackFileDisappeared): pass if hexsha is None: hexsha = sha_to_hex(sha1) # Maybe something else has added a pack with the object # in the mean time? for pack in self._update_pack_cache(): try: return pack.get_unpacked_object(sha, include_comp=include_comp) except KeyError: pass for alternate in self.alternates: try: return alternate.get_unpacked_object(hexsha, include_comp=include_comp) except KeyError: pass raise KeyError(hexsha) def add_objects( self, objects: Sequence[tuple[ShaFile, Optional[str]]], progress: Optional[Callable[[str], None]] = None, ) -> None: """Add a set of objects to this object store. Args: objects: Iterable over (object, path) tuples, should support __len__. Returns: Pack object of the objects written. """ count = len(objects) record_iter = (full_unpacked_object(o) for (o, p) in objects) return self.add_pack_data(count, record_iter, progress=progress) class DiskObjectStore(PackBasedObjectStore): """Git-style object store that exists on disk.""" def __init__( self, path, loose_compression_level=-1, pack_compression_level=-1 ) -> None: """Open an object store. Args: path: Path of the object store. loose_compression_level: zlib compression level for loose objects pack_compression_level: zlib compression level for pack objects """ super().__init__(pack_compression_level=pack_compression_level) self.path = path self.pack_dir = os.path.join(self.path, PACKDIR) self._alternates = None self.loose_compression_level = loose_compression_level self.pack_compression_level = pack_compression_level def __repr__(self) -> str: return f"<{self.__class__.__name__}({self.path!r})>" @classmethod def from_config(cls, path, config): try: default_compression_level = int( config.get((b"core",), b"compression").decode() ) except KeyError: default_compression_level = -1 try: loose_compression_level = int( config.get((b"core",), b"looseCompression").decode() ) except KeyError: loose_compression_level = default_compression_level try: pack_compression_level = int( config.get((b"core",), "packCompression").decode() ) except KeyError: pack_compression_level = default_compression_level return cls(path, loose_compression_level, pack_compression_level) @property def alternates(self): if self._alternates is not None: return self._alternates self._alternates = [] for path in self._read_alternate_paths(): self._alternates.append(DiskObjectStore(path)) return self._alternates def _read_alternate_paths(self): try: f = GitFile(os.path.join(self.path, INFODIR, "alternates"), "rb") except FileNotFoundError: return with f: for line in f.readlines(): line = line.rstrip(b"\n") if line.startswith(b"#"): continue if os.path.isabs(line): yield os.fsdecode(line) else: yield os.fsdecode(os.path.join(os.fsencode(self.path), line)) def add_alternate_path(self, path) -> None: """Add an alternate path to this object store.""" try: os.mkdir(os.path.join(self.path, INFODIR)) except FileExistsError: pass alternates_path = os.path.join(self.path, INFODIR, "alternates") with GitFile(alternates_path, "wb") as f: try: orig_f = open(alternates_path, "rb") except FileNotFoundError: pass else: with orig_f: f.write(orig_f.read()) f.write(os.fsencode(path) + b"\n") if not os.path.isabs(path): path = os.path.join(self.path, path) self.alternates.append(DiskObjectStore(path)) def _update_pack_cache(self): """Read and iterate over new pack files and cache them.""" try: pack_dir_contents = os.listdir(self.pack_dir) except FileNotFoundError: self.close() return [] pack_files = set() for name in pack_dir_contents: if name.startswith("pack-") and name.endswith(".pack"): # verify that idx exists first (otherwise the pack was not yet # fully written) idx_name = os.path.splitext(name)[0] + ".idx" if idx_name in pack_dir_contents: pack_name = name[: -len(".pack")] pack_files.add(pack_name) # Open newly appeared pack files new_packs = [] for f in pack_files: if f not in self._pack_cache: pack = Pack(os.path.join(self.pack_dir, f)) new_packs.append(pack) self._pack_cache[f] = pack # Remove disappeared pack files for f in set(self._pack_cache) - pack_files: self._pack_cache.pop(f).close() return new_packs def _get_shafile_path(self, sha): # Check from object dir return hex_to_filename(self.path, sha) def _iter_loose_objects(self): for base in os.listdir(self.path): if len(base) != 2: continue for rest in os.listdir(os.path.join(self.path, base)): sha = os.fsencode(base + rest) if not valid_hexsha(sha): continue yield sha def _get_loose_object(self, sha): path = self._get_shafile_path(sha) try: return ShaFile.from_path(path) except FileNotFoundError: return None def _remove_loose_object(self, sha) -> None: os.remove(self._get_shafile_path(sha)) def _remove_pack(self, pack) -> None: try: del self._pack_cache[os.path.basename(pack._basename)] except KeyError: pass pack.close() os.remove(pack.data.path) os.remove(pack.index.path) def _get_pack_basepath(self, entries): suffix = iter_sha1(entry[0] for entry in entries) # TODO: Handle self.pack_dir being bytes suffix = suffix.decode("ascii") return os.path.join(self.pack_dir, "pack-" + suffix) def _complete_pack(self, f, path, num_objects, indexer, progress=None): """Move a specific file containing a pack into the pack directory. Note: The file should be on the same file system as the packs directory. Args: f: Open file object for the pack. path: Path to the pack file. indexer: A PackIndexer for indexing the pack. """ entries = [] for i, entry in enumerate(indexer): if progress is not None: progress(f"generating index: {i}/{num_objects}\r".encode("ascii")) entries.append(entry) pack_sha, extra_entries = extend_pack( f, indexer.ext_refs(), get_raw=self.get_raw, compression_level=self.pack_compression_level, progress=progress, ) f.flush() try: fileno = f.fileno() except AttributeError: pass else: os.fsync(fileno) f.close() entries.extend(extra_entries) # Move the pack in. entries.sort() pack_base_name = self._get_pack_basepath(entries) for pack in self.packs: if pack._basename == pack_base_name: return pack target_pack_path = pack_base_name + ".pack" target_index_path = pack_base_name + ".idx" if sys.platform == "win32": # Windows might have the target pack file lingering. Attempt # removal, silently passing if the target does not exist. with suppress(FileNotFoundError): os.remove(target_pack_path) os.rename(path, target_pack_path) # Write the index. with GitFile(target_index_path, "wb", mask=PACK_MODE) as index_file: write_pack_index(index_file, entries, pack_sha) # Add the pack to the store and return it. final_pack = Pack(pack_base_name) final_pack.check_length_and_checksum() self._add_cached_pack(pack_base_name, final_pack) return final_pack def add_thin_pack(self, read_all, read_some, progress=None): """Add a new thin pack to this object store. Thin packs are packs that contain deltas with parents that exist outside the pack. They should never be placed in the object store directly, and always indexed and completed as they are copied. Args: read_all: Read function that blocks until the number of requested bytes are read. read_some: Read function that returns at least one byte, but may not return the number of bytes requested. Returns: A Pack object pointing at the now-completed thin pack in the objects/pack directory. """ import tempfile fd, path = tempfile.mkstemp(dir=self.path, prefix="tmp_pack_") with os.fdopen(fd, "w+b") as f: os.chmod(path, PACK_MODE) indexer = PackIndexer(f, resolve_ext_ref=self.get_raw) copier = PackStreamCopier(read_all, read_some, f, delta_iter=indexer) copier.verify(progress=progress) return self._complete_pack(f, path, len(copier), indexer, progress=progress) def add_pack(self): """Add a new pack to this object store. Returns: Fileobject to write to, a commit function to call when the pack is finished and an abort function. """ import tempfile fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack") f = os.fdopen(fd, "w+b") os.chmod(path, PACK_MODE) def commit(): if f.tell() > 0: f.seek(0) with PackData(path, f) as pd: indexer = PackIndexer.for_pack_data( pd, resolve_ext_ref=self.get_raw ) return self._complete_pack(f, path, len(pd), indexer) else: f.close() os.remove(path) return None def abort() -> None: f.close() os.remove(path) return f, commit, abort def add_object(self, obj) -> None: """Add a single object to this object store. Args: obj: Object to add """ path = self._get_shafile_path(obj.id) dir = os.path.dirname(path) try: os.mkdir(dir) except FileExistsError: pass if os.path.exists(path): return # Already there, no need to write again with GitFile(path, "wb", mask=PACK_MODE) as f: f.write( obj.as_legacy_object(compression_level=self.loose_compression_level) ) @classmethod def init(cls, path): try: os.mkdir(path) except FileExistsError: pass os.mkdir(os.path.join(path, "info")) os.mkdir(os.path.join(path, PACKDIR)) return cls(path) def iter_prefix(self, prefix): if len(prefix) < 2: yield from super().iter_prefix(prefix) return seen = set() dir = prefix[:2].decode() rest = prefix[2:].decode() try: for name in os.listdir(os.path.join(self.path, dir)): if name.startswith(rest): sha = os.fsencode(dir + name) if sha not in seen: seen.add(sha) yield sha except FileNotFoundError: pass for p in self.packs: bin_prefix = ( binascii.unhexlify(prefix) if len(prefix) % 2 == 0 else binascii.unhexlify(prefix[:-1]) ) for sha in p.index.iter_prefix(bin_prefix): sha = sha_to_hex(sha) if sha.startswith(prefix) and sha not in seen: seen.add(sha) yield sha for alternate in self.alternates: for sha in alternate.iter_prefix(prefix): if sha not in seen: seen.add(sha) yield sha class MemoryObjectStore(BaseObjectStore): """Object store that keeps all objects in memory.""" def __init__(self) -> None: super().__init__() self._data: dict[str, ShaFile] = {} self.pack_compression_level = -1 def _to_hexsha(self, sha): if len(sha) == 40: return sha elif len(sha) == 20: return sha_to_hex(sha) else: raise ValueError(f"Invalid sha {sha!r}") def contains_loose(self, sha): """Check if a particular object is present by SHA1 and is loose.""" return self._to_hexsha(sha) in self._data def contains_packed(self, sha) -> bool: """Check if a particular object is present by SHA1 and is packed.""" return False def __iter__(self): """Iterate over the SHAs that are present in this store.""" return iter(self._data.keys()) @property def packs(self): """List with pack objects.""" return [] def get_raw(self, name: ObjectID): """Obtain the raw text for an object. Args: name: sha for the object. Returns: tuple with numeric type and object contents. """ obj = self[self._to_hexsha(name)] return obj.type_num, obj.as_raw_string() def __getitem__(self, name: ObjectID): return self._data[self._to_hexsha(name)].copy() def __delitem__(self, name: ObjectID) -> None: """Delete an object from this store, for testing only.""" del self._data[self._to_hexsha(name)] def add_object(self, obj) -> None: """Add a single object to this object store.""" self._data[obj.id] = obj.copy() def add_objects(self, objects, progress=None) -> None: """Add a set of objects to this object store. Args: objects: Iterable over a list of (object, path) tuples """ for obj, path in objects: self.add_object(obj) def add_pack(self): """Add a new pack to this object store. Because this object store doesn't support packs, we extract and add the individual objects. Returns: Fileobject to write to and a commit function to call when the pack is finished. """ from tempfile import SpooledTemporaryFile f = SpooledTemporaryFile(max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-") def commit() -> None: size = f.tell() if size > 0: f.seek(0) p = PackData.from_file(f, size) for obj in PackInflater.for_pack_data(p, self.get_raw): self.add_object(obj) p.close() else: f.close() def abort() -> None: f.close() return f, commit, abort def add_pack_data( self, count: int, unpacked_objects: Iterator[UnpackedObject], progress=None ) -> None: """Add pack data to this object store. Args: count: Number of items to add pack_data: Iterator over pack data tuples """ for unpacked_object in unpacked_objects: self.add_object(unpacked_object.sha_file()) def add_thin_pack(self, read_all, read_some, progress=None) -> None: """Add a new thin pack to this object store. Thin packs are packs that contain deltas with parents that exist outside the pack. Because this object store doesn't support packs, we extract and add the individual objects. Args: read_all: Read function that blocks until the number of requested bytes are read. read_some: Read function that returns at least one byte, but may not return the number of bytes requested. """ f, commit, abort = self.add_pack() try: copier = PackStreamCopier(read_all, read_some, f) copier.verify() except BaseException: abort() raise else: commit() class ObjectIterator(Protocol): """Interface for iterating over objects.""" def iterobjects(self) -> Iterator[ShaFile]: raise NotImplementedError(self.iterobjects) def tree_lookup_path(lookup_obj, root_sha, path): """Look up an object in a Git tree. Args: lookup_obj: Callback for retrieving object by SHA1 root_sha: SHA1 of the root tree path: Path to lookup Returns: A tuple of (mode, SHA) of the resulting path. """ tree = lookup_obj(root_sha) if not isinstance(tree, Tree): raise NotTreeError(root_sha) return tree.lookup_path(lookup_obj, path) def _collect_filetree_revs( obj_store: ObjectContainer, tree_sha: ObjectID, kset: set[ObjectID] ) -> None: """Collect SHA1s of files and directories for specified tree. Args: obj_store: Object store to get objects by SHA from tree_sha: tree reference to walk kset: set to fill with references to files and directories """ filetree = obj_store[tree_sha] assert isinstance(filetree, Tree) for name, mode, sha in filetree.iteritems(): if not S_ISGITLINK(mode) and sha not in kset: kset.add(sha) if stat.S_ISDIR(mode): _collect_filetree_revs(obj_store, sha, kset) def _split_commits_and_tags( obj_store: ObjectContainer, lst, *, ignore_unknown=False ) -> tuple[set[bytes], set[bytes], set[bytes]]: """Split object id list into three lists with commit, tag, and other SHAs. Commits referenced by tags are included into commits list as well. Only SHA1s known in this repository will get through, and unless ignore_unknown argument is True, KeyError is thrown for SHA1 missing in the repository Args: obj_store: Object store to get objects by SHA1 from lst: Collection of commit and tag SHAs ignore_unknown: True to skip SHA1 missing in the repository silently. Returns: A tuple of (commits, tags, others) SHA1s """ commits: set[bytes] = set() tags: set[bytes] = set() others: set[bytes] = set() for e in lst: try: o = obj_store[e] except KeyError: if not ignore_unknown: raise else: if isinstance(o, Commit): commits.add(e) elif isinstance(o, Tag): tags.add(e) tagged = o.object[1] c, t, os = _split_commits_and_tags( obj_store, [tagged], ignore_unknown=ignore_unknown ) commits |= c tags |= t others |= os else: others.add(e) return (commits, tags, others) class MissingObjectFinder: """Find the objects missing from another object store. Args: object_store: Object store containing at least all objects to be sent haves: SHA1s of commits not to send (already present in target) wants: SHA1s of commits to send progress: Optional function to report progress to. get_tagged: Function that returns a dict of pointed-to sha -> tag sha for including tags. get_parents: Optional function for getting the parents of a commit. tagged: dict of pointed-to sha -> tag sha for including tags """ def __init__( self, object_store, haves, wants, *, shallow=None, progress=None, get_tagged=None, get_parents=lambda commit: commit.parents, ) -> None: self.object_store = object_store if shallow is None: shallow = set() self._get_parents = get_parents # process Commits and Tags differently # Note, while haves may list commits/tags not available locally, # and such SHAs would get filtered out by _split_commits_and_tags, # wants shall list only known SHAs, and otherwise # _split_commits_and_tags fails with KeyError have_commits, have_tags, have_others = _split_commits_and_tags( object_store, haves, ignore_unknown=True ) want_commits, want_tags, want_others = _split_commits_and_tags( object_store, wants, ignore_unknown=False ) # all_ancestors is a set of commits that shall not be sent # (complete repository up to 'haves') all_ancestors = _collect_ancestors( object_store, have_commits, shallow=shallow, get_parents=self._get_parents )[0] # all_missing - complete set of commits between haves and wants # common - commits from all_ancestors we hit into while # traversing parent hierarchy of wants missing_commits, common_commits = _collect_ancestors( object_store, want_commits, all_ancestors, shallow=shallow, get_parents=self._get_parents, ) self.remote_has: set[bytes] = set() # Now, fill sha_done with commits and revisions of # files and directories known to be both locally # and on target. Thus these commits and files # won't get selected for fetch for h in common_commits: self.remote_has.add(h) cmt = object_store[h] _collect_filetree_revs(object_store, cmt.tree, self.remote_has) # record tags we have as visited, too for t in have_tags: self.remote_has.add(t) self.sha_done = set(self.remote_has) # in fact, what we 'want' is commits, tags, and others # we've found missing self.objects_to_send: set[ tuple[ObjectID, Optional[bytes], Optional[int], bool] ] = {(w, None, Commit.type_num, False) for w in missing_commits} missing_tags = want_tags.difference(have_tags) self.objects_to_send.update( {(w, None, Tag.type_num, False) for w in missing_tags} ) missing_others = want_others.difference(have_others) self.objects_to_send.update({(w, None, None, False) for w in missing_others}) if progress is None: self.progress = lambda x: None else: self.progress = progress self._tagged = (get_tagged and get_tagged()) or {} def get_remote_has(self): return self.remote_has def add_todo( self, entries: Iterable[tuple[ObjectID, Optional[bytes], Optional[int], bool]] ) -> None: self.objects_to_send.update([e for e in entries if e[0] not in self.sha_done]) def __next__(self) -> tuple[bytes, Optional[PackHint]]: while True: if not self.objects_to_send: self.progress( f"counting objects: {len(self.sha_done)}, done.\n".encode("ascii") ) raise StopIteration (sha, name, type_num, leaf) = self.objects_to_send.pop() if sha not in self.sha_done: break if not leaf: o = self.object_store[sha] if isinstance(o, Commit): self.add_todo([(o.tree, b"", Tree.type_num, False)]) elif isinstance(o, Tree): self.add_todo( [ ( s, n, (Blob.type_num if stat.S_ISREG(m) else Tree.type_num), not stat.S_ISDIR(m), ) for n, m, s in o.iteritems() if not S_ISGITLINK(m) ] ) elif isinstance(o, Tag): self.add_todo([(o.object[1], None, o.object[0].type_num, False)]) if sha in self._tagged: self.add_todo([(self._tagged[sha], None, None, True)]) self.sha_done.add(sha) if len(self.sha_done) % 1000 == 0: self.progress(f"counting objects: {len(self.sha_done)}\r".encode("ascii")) if type_num is None: pack_hint = None else: pack_hint = (type_num, name) return (sha, pack_hint) def __iter__(self): return self class ObjectStoreGraphWalker: """Graph walker that finds what commits are missing from an object store. Attributes: heads: Revisions without descendants in the local repo get_parents: Function to retrieve parents in the local repo """ def __init__(self, local_heads, get_parents, shallow=None) -> None: """Create a new instance. Args: local_heads: Heads to start search with get_parents: Function for finding the parents of a SHA1. """ self.heads = set(local_heads) self.get_parents = get_parents self.parents: dict[ObjectID, Optional[list[ObjectID]]] = {} if shallow is None: shallow = set() self.shallow = shallow def nak(self) -> None: """Nothing in common was found.""" def ack(self, sha) -> None: """Ack that a revision and its ancestors are present in the source.""" if len(sha) != 40: raise ValueError(f"unexpected sha {sha!r} received") ancestors = {sha} # stop if we run out of heads to remove while self.heads: for a in ancestors: if a in self.heads: self.heads.remove(a) # collect all ancestors new_ancestors = set() for a in ancestors: ps = self.parents.get(a) if ps is not None: new_ancestors.update(ps) self.parents[a] = None # no more ancestors; stop if not new_ancestors: break ancestors = new_ancestors def next(self): """Iterate over ancestors of heads in the target.""" if self.heads: ret = self.heads.pop() try: ps = self.get_parents(ret) except KeyError: return None self.parents[ret] = ps self.heads.update([p for p in ps if p not in self.parents]) return ret return None __next__ = next def commit_tree_changes(object_store, tree, changes): """Commit a specified set of changes to a tree structure. This will apply a set of changes on top of an existing tree, storing new objects in object_store. changes are a list of tuples with (path, mode, object_sha). Paths can be both blobs and trees. See the mode and object sha to None deletes the path. This method works especially well if there are only a small number of changes to a big tree. For a large number of changes to a large tree, use e.g. commit_tree. Args: object_store: Object store to store new objects in and retrieve old ones from. tree: Original tree root changes: changes to apply Returns: New tree root object """ # TODO(jelmer): Save up the objects and add them using .add_objects # rather than with individual calls to .add_object. nested_changes = {} for path, new_mode, new_sha in changes: try: (dirname, subpath) = path.split(b"/", 1) except ValueError: if new_sha is None: del tree[path] else: tree[path] = (new_mode, new_sha) else: nested_changes.setdefault(dirname, []).append((subpath, new_mode, new_sha)) for name, subchanges in nested_changes.items(): try: orig_subtree = object_store[tree[name][1]] except KeyError: orig_subtree = Tree() subtree = commit_tree_changes(object_store, orig_subtree, subchanges) if len(subtree) == 0: del tree[name] else: tree[name] = (stat.S_IFDIR, subtree.id) object_store.add_object(tree) return tree class OverlayObjectStore(BaseObjectStore): """Object store that can overlay multiple object stores.""" def __init__(self, bases, add_store=None) -> None: self.bases = bases self.add_store = add_store def add_object(self, object): if self.add_store is None: raise NotImplementedError(self.add_object) return self.add_store.add_object(object) def add_objects(self, objects, progress=None): if self.add_store is None: raise NotImplementedError(self.add_object) return self.add_store.add_objects(objects, progress) @property def packs(self): ret = [] for b in self.bases: ret.extend(b.packs) return ret def __iter__(self): done = set() for b in self.bases: for o_id in b: if o_id not in done: yield o_id done.add(o_id) def iterobjects_subset( self, shas: Iterable[bytes], *, allow_missing: bool = False ) -> Iterator[ShaFile]: todo = set(shas) for b in self.bases: for o in b.iterobjects_subset(todo, allow_missing=True): yield o todo.remove(o.id) if todo and not allow_missing: raise KeyError(o.id) def iter_unpacked_subset( self, shas: Iterable[bytes], *, include_comp=False, allow_missing: bool = False, convert_ofs_delta=True, ) -> Iterator[ShaFile]: todo = set(shas) for b in self.bases: for o in b.iter_unpacked_subset( todo, include_comp=include_comp, allow_missing=True, convert_ofs_delta=convert_ofs_delta, ): yield o todo.remove(o.id) if todo and not allow_missing: raise KeyError(o.id) def get_raw(self, sha_id): for b in self.bases: try: return b.get_raw(sha_id) except KeyError: pass raise KeyError(sha_id) def contains_packed(self, sha) -> bool: for b in self.bases: if b.contains_packed(sha): return True return False def contains_loose(self, sha) -> bool: for b in self.bases: if b.contains_loose(sha): return True return False def read_packs_file(f): """Yield the packs listed in a packs file.""" for line in f.read().splitlines(): if not line: continue (kind, name) = line.split(b" ", 1) if kind != b"P": continue yield os.fsdecode(name) class BucketBasedObjectStore(PackBasedObjectStore): """Object store implementation that uses a bucket store like S3 as backend.""" def _iter_loose_objects(self): """Iterate over the SHAs of all loose objects.""" return iter([]) def _get_loose_object(self, sha) -> None: return None def _remove_loose_object(self, sha) -> None: # Doesn't exist.. pass def _remove_pack(self, name) -> None: raise NotImplementedError(self._remove_pack) def _iter_pack_names(self) -> Iterator[str]: raise NotImplementedError(self._iter_pack_names) def _get_pack(self, name) -> Pack: raise NotImplementedError(self._get_pack) def _update_pack_cache(self): pack_files = set(self._iter_pack_names()) # Open newly appeared pack files new_packs = [] for f in pack_files: if f not in self._pack_cache: pack = self._get_pack(f) new_packs.append(pack) self._pack_cache[f] = pack # Remove disappeared pack files for f in set(self._pack_cache) - pack_files: self._pack_cache.pop(f).close() return new_packs def _upload_pack(self, basename, pack_file, index_file) -> None: raise NotImplementedError def add_pack(self): """Add a new pack to this object store. Returns: Fileobject to write to, a commit function to call when the pack is finished and an abort function. """ import tempfile pf = tempfile.SpooledTemporaryFile( max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-" ) def commit(): if pf.tell() == 0: pf.close() return None pf.seek(0) p = PackData(pf.name, pf) entries = p.sorted_entries() basename = iter_sha1(entry[0] for entry in entries).decode("ascii") idxf = tempfile.SpooledTemporaryFile( max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-" ) checksum = p.get_stored_checksum() write_pack_index(idxf, entries, checksum) idxf.seek(0) idx = load_pack_index_file(basename + ".idx", idxf) for pack in self.packs: if pack.get_stored_checksum() == p.get_stored_checksum(): p.close() idx.close() return pack pf.seek(0) idxf.seek(0) self._upload_pack(basename, pf, idxf) final_pack = Pack.from_objects(p, idx) self._add_cached_pack(basename, final_pack) return final_pack return pf, commit, pf.close def _collect_ancestors( store: ObjectContainer, heads, common: frozenset[ObjectID] = frozenset(), shallow: frozenset[ObjectID] = frozenset(), get_parents=lambda commit: commit.parents, ): """Collect all ancestors of heads up to (excluding) those in common. Args: heads: commits to start from common: commits to end at, or empty set to walk repository completely get_parents: Optional function for getting the parents of a commit. Returns: a tuple (A, B) where A - all commits reachable from heads but not present in common, B - common (shared) elements that are directly reachable from heads """ bases = set() commits = set() queue = [] queue.extend(heads) while queue: e = queue.pop(0) if e in common: bases.add(e) elif e not in commits: commits.add(e) if e in shallow: continue cmt = store[e] queue.extend(get_parents(cmt)) return (commits, bases) def iter_tree_contents( store: ObjectContainer, tree_id: Optional[ObjectID], *, include_trees: bool = False ): """Iterate the contents of a tree and all subtrees. Iteration is depth-first pre-order, as in e.g. os.walk. Args: tree_id: SHA1 of the tree. include_trees: If True, include tree objects in the iteration. Returns: Iterator over TreeEntry namedtuples for all the objects in a tree. """ if tree_id is None: return # This could be fairly easily generalized to >2 trees if we find a use # case. todo = [TreeEntry(b"", stat.S_IFDIR, tree_id)] while todo: entry = todo.pop() if stat.S_ISDIR(entry.mode): extra = [] tree = store[entry.sha] assert isinstance(tree, Tree) for subentry in tree.iteritems(name_order=True): extra.append(subentry.in_path(entry.path)) todo.extend(reversed(extra)) if not stat.S_ISDIR(entry.mode) or include_trees: yield entry def peel_sha(store: ObjectContainer, sha: bytes) -> tuple[ShaFile, ShaFile]: """Peel all tags from a SHA. Args: sha: The object SHA to peel. Returns: The fully-peeled SHA1 of a tag object, after peeling all intermediate tags; if the original ref does not point to a tag, this will equal the original SHA1. """ unpeeled = obj = store[sha] obj_class = object_class(obj.type_name) while obj_class is Tag: assert isinstance(obj, Tag) obj_class, sha = obj.object obj = store[sha] return unpeeled, obj ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/objects.py0000644000175100002000000015343314731042555016312 0ustar00runnerdocker# objects.py -- Access to base git objects # Copyright (C) 2007 James Westby # Copyright (C) 2008-2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Access to base git objects.""" import binascii import os import posixpath import stat import warnings import zlib from collections import namedtuple from collections.abc import Callable, Iterable, Iterator from hashlib import sha1 from io import BytesIO from typing import ( TYPE_CHECKING, BinaryIO, Optional, Union, ) from .errors import ( ChecksumMismatch, FileFormatException, NotBlobError, NotCommitError, NotTagError, NotTreeError, ObjectFormatException, ) from .file import GitFile if TYPE_CHECKING: from _hashlib import HASH ZERO_SHA = b"0" * 40 # Header fields for commits _TREE_HEADER = b"tree" _PARENT_HEADER = b"parent" _AUTHOR_HEADER = b"author" _COMMITTER_HEADER = b"committer" _ENCODING_HEADER = b"encoding" _MERGETAG_HEADER = b"mergetag" _GPGSIG_HEADER = b"gpgsig" # Header fields for objects _OBJECT_HEADER = b"object" _TYPE_HEADER = b"type" _TAG_HEADER = b"tag" _TAGGER_HEADER = b"tagger" S_IFGITLINK = 0o160000 MAX_TIME = 9223372036854775807 # (2**63) - 1 - signed long int max BEGIN_PGP_SIGNATURE = b"-----BEGIN PGP SIGNATURE-----" ObjectID = bytes class EmptyFileException(FileFormatException): """An unexpectedly empty file was encountered.""" def S_ISGITLINK(m): """Check if a mode indicates a submodule. Args: m: Mode to check Returns: a ``boolean`` """ return stat.S_IFMT(m) == S_IFGITLINK def _decompress(string): dcomp = zlib.decompressobj() dcomped = dcomp.decompress(string) dcomped += dcomp.flush() return dcomped def sha_to_hex(sha): """Takes a string and returns the hex of the sha within.""" hexsha = binascii.hexlify(sha) assert len(hexsha) == 40, f"Incorrect length of sha1 string: {hexsha!r}" return hexsha def hex_to_sha(hex): """Takes a hex sha and returns a binary sha.""" assert len(hex) == 40, f"Incorrect length of hexsha: {hex}" try: return binascii.unhexlify(hex) except TypeError as exc: if not isinstance(hex, bytes): raise raise ValueError(exc.args[0]) from exc def valid_hexsha(hex) -> bool: if len(hex) != 40: return False try: binascii.unhexlify(hex) except (TypeError, binascii.Error): return False else: return True def hex_to_filename(path, hex): """Takes a hex sha and returns its filename relative to the given path.""" # os.path.join accepts bytes or unicode, but all args must be of the same # type. Make sure that hex which is expected to be bytes, is the same type # as path. if type(path) is not type(hex) and getattr(path, "encode", None) is not None: hex = hex.decode("ascii") dir = hex[:2] file = hex[2:] # Check from object dir return os.path.join(path, dir, file) def filename_to_hex(filename): """Takes an object filename and returns its corresponding hex sha.""" # grab the last (up to) two path components names = filename.rsplit(os.path.sep, 2)[-2:] errmsg = f"Invalid object filename: {filename}" assert len(names) == 2, errmsg base, rest = names assert len(base) == 2 and len(rest) == 38, errmsg hex = (base + rest).encode("ascii") hex_to_sha(hex) return hex def object_header(num_type: int, length: int) -> bytes: """Return an object header for the given numeric type and text length.""" cls = object_class(num_type) if cls is None: raise AssertionError(f"unsupported class type num: {num_type}") return cls.type_name + b" " + str(length).encode("ascii") + b"\0" def serializable_property(name: str, docstring: Optional[str] = None): """A property that helps tracking whether serialization is necessary.""" def set(obj, value) -> None: setattr(obj, "_" + name, value) obj._needs_serialization = True def get(obj): return getattr(obj, "_" + name) return property(get, set, doc=docstring) def object_class(type: Union[bytes, int]) -> Optional[type["ShaFile"]]: """Get the object class corresponding to the given type. Args: type: Either a type name string or a numeric type. Returns: The ShaFile subclass corresponding to the given type, or None if type is not a valid type name/number. """ return _TYPE_MAP.get(type, None) def check_hexsha(hex, error_msg) -> None: """Check if a string is a valid hex sha string. Args: hex: Hex string to check error_msg: Error message to use in exception Raises: ObjectFormatException: Raised when the string is not valid """ if not valid_hexsha(hex): raise ObjectFormatException(f"{error_msg} {hex}") def check_identity(identity: Optional[bytes], error_msg: str) -> None: """Check if the specified identity is valid. This will raise an exception if the identity is not valid. Args: identity: Identity string error_msg: Error message to use in exception """ if identity is None: raise ObjectFormatException(error_msg) email_start = identity.find(b"<") email_end = identity.find(b">") if not all( [ email_start >= 1, identity[email_start - 1] == b" "[0], identity.find(b"<", email_start + 1) == -1, email_end == len(identity) - 1, b"\0" not in identity, b"\n" not in identity, ] ): raise ObjectFormatException(error_msg) def check_time(time_seconds) -> None: """Check if the specified time is not prone to overflow error. This will raise an exception if the time is not valid. Args: time_seconds: time in seconds """ # Prevent overflow error if time_seconds > MAX_TIME: raise ObjectFormatException(f"Date field should not exceed {MAX_TIME}") def git_line(*items): """Formats items into a space separated line.""" return b" ".join(items) + b"\n" class FixedSha: """SHA object that behaves like hashlib's but is given a fixed value.""" __slots__ = ("_hexsha", "_sha") def __init__(self, hexsha) -> None: if getattr(hexsha, "encode", None) is not None: hexsha = hexsha.encode("ascii") if not isinstance(hexsha, bytes): raise TypeError(f"Expected bytes for hexsha, got {hexsha!r}") self._hexsha = hexsha self._sha = hex_to_sha(hexsha) def digest(self) -> bytes: """Return the raw SHA digest.""" return self._sha def hexdigest(self) -> str: """Return the hex SHA digest.""" return self._hexsha.decode("ascii") class ShaFile: """A git SHA file.""" __slots__ = ("_chunked_text", "_needs_serialization", "_sha") _needs_serialization: bool type_name: bytes type_num: int _chunked_text: Optional[list[bytes]] _sha: Union[FixedSha, None, "HASH"] @staticmethod def _parse_legacy_object_header(magic, f: BinaryIO) -> "ShaFile": """Parse a legacy object, creating it but not reading the file.""" bufsize = 1024 decomp = zlib.decompressobj() header = decomp.decompress(magic) start = 0 end = -1 while end < 0: extra = f.read(bufsize) header += decomp.decompress(extra) magic += extra end = header.find(b"\0", start) start = len(header) header = header[:end] type_name, size = header.split(b" ", 1) try: int(size) # sanity check except ValueError as exc: raise ObjectFormatException(f"Object size not an integer: {exc}") from exc obj_class = object_class(type_name) if not obj_class: raise ObjectFormatException( "Not a known type: {}".format(type_name.decode("ascii")) ) return obj_class() def _parse_legacy_object(self, map) -> None: """Parse a legacy object, setting the raw string.""" text = _decompress(map) header_end = text.find(b"\0") if header_end < 0: raise ObjectFormatException("Invalid object header, no \\0") self.set_raw_string(text[header_end + 1 :]) def as_legacy_object_chunks(self, compression_level: int = -1) -> Iterator[bytes]: """Return chunks representing the object in the experimental format. Returns: List of strings """ compobj = zlib.compressobj(compression_level) yield compobj.compress(self._header()) for chunk in self.as_raw_chunks(): yield compobj.compress(chunk) yield compobj.flush() def as_legacy_object(self, compression_level: int = -1) -> bytes: """Return string representing the object in the experimental format.""" return b"".join( self.as_legacy_object_chunks(compression_level=compression_level) ) def as_raw_chunks(self) -> list[bytes]: """Return chunks with serialization of the object. Returns: List of strings, not necessarily one per line """ if self._needs_serialization: self._sha = None self._chunked_text = self._serialize() self._needs_serialization = False return self._chunked_text # type: ignore def as_raw_string(self) -> bytes: """Return raw string with serialization of the object. Returns: String object """ return b"".join(self.as_raw_chunks()) def __bytes__(self) -> bytes: """Return raw string serialization of this object.""" return self.as_raw_string() def __hash__(self) -> int: """Return unique hash for this object.""" return hash(self.id) def as_pretty_string(self) -> str: """Return a string representing this object, fit for display.""" return self.as_raw_string().decode("utf-8", "replace") def set_raw_string(self, text: bytes, sha: Optional[ObjectID] = None) -> None: """Set the contents of this object from a serialized string.""" if not isinstance(text, bytes): raise TypeError(f"Expected bytes for text, got {text!r}") self.set_raw_chunks([text], sha) def set_raw_chunks( self, chunks: list[bytes], sha: Optional[ObjectID] = None ) -> None: """Set the contents of this object from a list of chunks.""" self._chunked_text = chunks self._deserialize(chunks) if sha is None: self._sha = None else: self._sha = FixedSha(sha) # type: ignore self._needs_serialization = False @staticmethod def _parse_object_header(magic, f): """Parse a new style object, creating it but not reading the file.""" num_type = (ord(magic[0:1]) >> 4) & 7 obj_class = object_class(num_type) if not obj_class: raise ObjectFormatException(f"Not a known type {num_type}") return obj_class() def _parse_object(self, map) -> None: """Parse a new style object, setting self._text.""" # skip type and size; type must have already been determined, and # we trust zlib to fail if it's otherwise corrupted byte = ord(map[0:1]) used = 1 while (byte & 0x80) != 0: byte = ord(map[used : used + 1]) used += 1 raw = map[used:] self.set_raw_string(_decompress(raw)) @classmethod def _is_legacy_object(cls, magic: bytes) -> bool: b0 = ord(magic[0:1]) b1 = ord(magic[1:2]) word = (b0 << 8) + b1 return (b0 & 0x8F) == 0x08 and (word % 31) == 0 @classmethod def _parse_file(cls, f): map = f.read() if not map: raise EmptyFileException("Corrupted empty file detected") if cls._is_legacy_object(map): obj = cls._parse_legacy_object_header(map, f) obj._parse_legacy_object(map) else: obj = cls._parse_object_header(map, f) obj._parse_object(map) return obj def __init__(self) -> None: """Don't call this directly.""" self._sha = None self._chunked_text = [] self._needs_serialization = True def _deserialize(self, chunks: list[bytes]) -> None: raise NotImplementedError(self._deserialize) def _serialize(self) -> list[bytes]: raise NotImplementedError(self._serialize) @classmethod def from_path(cls, path): """Open a SHA file from disk.""" with GitFile(path, "rb") as f: return cls.from_file(f) @classmethod def from_file(cls, f): """Get the contents of a SHA file on disk.""" try: obj = cls._parse_file(f) obj._sha = None return obj except (IndexError, ValueError) as exc: raise ObjectFormatException("invalid object header") from exc @staticmethod def from_raw_string( type_num, string: bytes, sha: Optional[ObjectID] = None ) -> "ShaFile": """Creates an object of the indicated type from the raw string given. Args: type_num: The numeric type of the object. string: The raw uncompressed contents. sha: Optional known sha for the object """ cls = object_class(type_num) if cls is None: raise AssertionError(f"unsupported class type num: {type_num}") obj = cls() obj.set_raw_string(string, sha) return obj @staticmethod def from_raw_chunks( type_num: int, chunks: list[bytes], sha: Optional[ObjectID] = None ): """Creates an object of the indicated type from the raw chunks given. Args: type_num: The numeric type of the object. chunks: An iterable of the raw uncompressed contents. sha: Optional known sha for the object """ cls = object_class(type_num) if cls is None: raise AssertionError(f"unsupported class type num: {type_num}") obj = cls() obj.set_raw_chunks(chunks, sha) return obj @classmethod def from_string(cls, string): """Create a ShaFile from a string.""" obj = cls() obj.set_raw_string(string) return obj def _check_has_member(self, member, error_msg) -> None: """Check that the object has a given member variable. Args: member: the member variable to check for error_msg: the message for an error if the member is missing Raises: ObjectFormatException: with the given error_msg if member is missing or is None """ if getattr(self, member, None) is None: raise ObjectFormatException(error_msg) def check(self) -> None: """Check this object for internal consistency. Raises: ObjectFormatException: if the object is malformed in some way ChecksumMismatch: if the object was created with a SHA that does not match its contents """ # TODO: if we find that error-checking during object parsing is a # performance bottleneck, those checks should be moved to the class's # check() method during optimization so we can still check the object # when necessary. old_sha = self.id try: self._deserialize(self.as_raw_chunks()) self._sha = None new_sha = self.id except Exception as exc: raise ObjectFormatException(exc) from exc if old_sha != new_sha: raise ChecksumMismatch(new_sha, old_sha) def _header(self): return object_header(self.type_num, self.raw_length()) def raw_length(self) -> int: """Returns the length of the raw string of this object.""" return sum(map(len, self.as_raw_chunks())) def sha(self) -> "HASH": """The SHA1 object that is the name of this object.""" if self._sha is None or self._needs_serialization: # this is a local because as_raw_chunks() overwrites self._sha new_sha = sha1() new_sha.update(self._header()) for chunk in self.as_raw_chunks(): new_sha.update(chunk) self._sha = new_sha return self._sha def copy(self) -> "ShaFile": """Create a new copy of this SHA1 object from its raw string.""" obj_class = object_class(self.type_num) if obj_class is None: raise AssertionError(f"invalid type num {self.type_num}") return obj_class.from_raw_string(self.type_num, self.as_raw_string(), self.id) @property def id(self): """The hex SHA of this object.""" return self.sha().hexdigest().encode("ascii") def __repr__(self) -> str: return f"<{self.__class__.__name__} {self.id}>" def __ne__(self, other) -> bool: """Check whether this object does not match the other.""" return not isinstance(other, ShaFile) or self.id != other.id def __eq__(self, other) -> bool: """Return True if the SHAs of the two objects match.""" return isinstance(other, ShaFile) and self.id == other.id def __lt__(self, other) -> bool: """Return whether SHA of this object is less than the other.""" if not isinstance(other, ShaFile): raise TypeError return self.id < other.id def __le__(self, other) -> bool: """Check whether SHA of this object is less than or equal to the other.""" if not isinstance(other, ShaFile): raise TypeError return self.id <= other.id class Blob(ShaFile): """A Git Blob object.""" __slots__ = () type_name = b"blob" type_num = 3 _chunked_text: list[bytes] def __init__(self) -> None: super().__init__() self._chunked_text = [] self._needs_serialization = False def _get_data(self): return self.as_raw_string() def _set_data(self, data) -> None: self.set_raw_string(data) data = property( _get_data, _set_data, doc="The text contained within the blob object." ) def _get_chunked(self): return self._chunked_text def _set_chunked(self, chunks: list[bytes]) -> None: self._chunked_text = chunks def _serialize(self): return self._chunked_text def _deserialize(self, chunks) -> None: self._chunked_text = chunks chunked = property( _get_chunked, _set_chunked, doc="The text in the blob object, as chunks (not necessarily lines)", ) @classmethod def from_path(cls, path): blob = ShaFile.from_path(path) if not isinstance(blob, cls): raise NotBlobError(path) return blob def check(self) -> None: """Check this object for internal consistency. Raises: ObjectFormatException: if the object is malformed in some way """ super().check() def splitlines(self) -> list[bytes]: """Return list of lines in this blob. This preserves the original line endings. """ chunks = self.chunked if not chunks: return [] if len(chunks) == 1: return chunks[0].splitlines(True) remaining = None ret = [] for chunk in chunks: lines = chunk.splitlines(True) if len(lines) > 1: ret.append((remaining or b"") + lines[0]) ret.extend(lines[1:-1]) remaining = lines[-1] elif len(lines) == 1: if remaining is None: remaining = lines.pop() else: remaining += lines.pop() if remaining is not None: ret.append(remaining) return ret def _parse_message( chunks: Iterable[bytes], ) -> Iterator[Union[tuple[None, None], tuple[Optional[bytes], bytes]]]: """Parse a message with a list of fields and a body. Args: chunks: the raw chunks of the tag or commit object. Returns: iterator of tuples of (field, value), one per header line, in the order read from the text, possibly including duplicates. Includes a field named None for the freeform tag/commit text. """ f = BytesIO(b"".join(chunks)) k = None v = b"" eof = False def _strip_last_newline(value): """Strip the last newline from value.""" if value and value.endswith(b"\n"): return value[:-1] return value # Parse the headers # # Headers can contain newlines. The next line is indented with a space. # We store the latest key as 'k', and the accumulated value as 'v'. for line in f: if line.startswith(b" "): # Indented continuation of the previous line v += line[1:] else: if k is not None: # We parsed a new header, return its value yield (k, _strip_last_newline(v)) if line == b"\n": # Empty line indicates end of headers break (k, v) = line.split(b" ", 1) else: # We reached end of file before the headers ended. We still need to # return the previous header, then we need to return a None field for # the text. eof = True if k is not None: yield (k, _strip_last_newline(v)) yield (None, None) if not eof: # We didn't reach the end of file while parsing headers. We can return # the rest of the file as a message. yield (None, f.read()) f.close() def _format_message(headers, body): for field, value in headers: lines = value.split(b"\n") yield git_line(field, lines[0]) for line in lines[1:]: yield b" " + line + b"\n" yield b"\n" # There must be a new line after the headers if body: yield body class Tag(ShaFile): """A Git Tag object.""" type_name = b"tag" type_num = 4 __slots__ = ( "_message", "_name", "_object_class", "_object_sha", "_signature", "_tag_time", "_tag_timezone", "_tag_timezone_neg_utc", "_tagger", ) _tagger: Optional[bytes] def __init__(self) -> None: super().__init__() self._tagger = None self._tag_time = None self._tag_timezone = None self._tag_timezone_neg_utc = False self._signature: Optional[bytes] = None @classmethod def from_path(cls, filename): tag = ShaFile.from_path(filename) if not isinstance(tag, cls): raise NotTagError(filename) return tag def check(self) -> None: """Check this object for internal consistency. Raises: ObjectFormatException: if the object is malformed in some way """ super().check() assert self._chunked_text is not None self._check_has_member("_object_sha", "missing object sha") self._check_has_member("_object_class", "missing object type") self._check_has_member("_name", "missing tag name") if not self._name: raise ObjectFormatException("empty tag name") check_hexsha(self._object_sha, "invalid object sha") if self._tagger is not None: check_identity(self._tagger, "invalid tagger") self._check_has_member("_tag_time", "missing tag time") check_time(self._tag_time) last = None for field, _ in _parse_message(self._chunked_text): if field == _OBJECT_HEADER and last is not None: raise ObjectFormatException("unexpected object") elif field == _TYPE_HEADER and last != _OBJECT_HEADER: raise ObjectFormatException("unexpected type") elif field == _TAG_HEADER and last != _TYPE_HEADER: raise ObjectFormatException("unexpected tag name") elif field == _TAGGER_HEADER and last != _TAG_HEADER: raise ObjectFormatException("unexpected tagger") last = field def _serialize(self): headers = [] headers.append((_OBJECT_HEADER, self._object_sha)) headers.append((_TYPE_HEADER, self._object_class.type_name)) headers.append((_TAG_HEADER, self._name)) if self._tagger: if self._tag_time is None: headers.append((_TAGGER_HEADER, self._tagger)) else: headers.append( ( _TAGGER_HEADER, format_time_entry( self._tagger, self._tag_time, (self._tag_timezone, self._tag_timezone_neg_utc), ), ) ) if self.message is None and self._signature is None: body = None else: body = (self.message or b"") + (self._signature or b"") return list(_format_message(headers, body)) def _deserialize(self, chunks) -> None: """Grab the metadata attached to the tag.""" self._tagger = None self._tag_time = None self._tag_timezone = None self._tag_timezone_neg_utc = False for field, value in _parse_message(chunks): if field == _OBJECT_HEADER: self._object_sha = value elif field == _TYPE_HEADER: assert isinstance(value, bytes) obj_class = object_class(value) if not obj_class: raise ObjectFormatException(f"Not a known type: {value!r}") self._object_class = obj_class elif field == _TAG_HEADER: self._name = value elif field == _TAGGER_HEADER: ( self._tagger, self._tag_time, (self._tag_timezone, self._tag_timezone_neg_utc), ) = parse_time_entry(value) elif field is None: if value is None: self._message = None self._signature = None else: try: sig_idx = value.index(BEGIN_PGP_SIGNATURE) except ValueError: self._message = value self._signature = None else: self._message = value[:sig_idx] self._signature = value[sig_idx:] else: raise ObjectFormatException( f"Unknown field {field.decode('ascii', 'replace')}" ) def _get_object(self): """Get the object pointed to by this tag. Returns: tuple of (object class, sha). """ return (self._object_class, self._object_sha) def _set_object(self, value) -> None: (self._object_class, self._object_sha) = value self._needs_serialization = True object = property(_get_object, _set_object) name = serializable_property("name", "The name of this tag") tagger = serializable_property( "tagger", "Returns the name of the person who created this tag" ) tag_time = serializable_property( "tag_time", "The creation timestamp of the tag. As the number of seconds " "since the epoch", ) tag_timezone = serializable_property( "tag_timezone", "The timezone that tag_time is in." ) message = serializable_property("message", "the message attached to this tag") signature = serializable_property("signature", "Optional detached GPG signature") def sign(self, keyid: Optional[str] = None) -> None: import gpg with gpg.Context(armor=True) as c: if keyid is not None: key = c.get_key(keyid) with gpg.Context(armor=True, signers=[key]) as ctx: self.signature, unused_result = ctx.sign( self.as_raw_string(), mode=gpg.constants.sig.mode.DETACH, ) else: self.signature, unused_result = c.sign( self.as_raw_string(), mode=gpg.constants.sig.mode.DETACH ) def raw_without_sig(self) -> bytes: """Return raw string serialization without the GPG/SSH signature. self.signature is a signature for the returned raw byte string serialization. """ ret = self.as_raw_string() if self._signature: ret = ret[: -len(self._signature)] return ret def verify(self, keyids: Optional[Iterable[str]] = None) -> None: """Verify GPG signature for this tag (if it is signed). Args: keyids: Optional iterable of trusted keyids for this tag. If this tag is not signed by any key in keyids verification will fail. If not specified, this function only verifies that the tag has a valid signature. Raises: gpg.errors.BadSignatures: if GPG signature verification fails gpg.errors.MissingSignatures: if tag was not signed by a key specified in keyids """ if self._signature is None: return import gpg with gpg.Context() as ctx: data, result = ctx.verify( self.raw_without_sig(), signature=self._signature, ) if keyids: keys = [ctx.get_key(key) for key in keyids] for key in keys: for subkey in keys: for sig in result.signatures: if subkey.can_sign and subkey.fpr == sig.fpr: return raise gpg.errors.MissingSignatures(result, keys, results=(data, result)) class TreeEntry(namedtuple("TreeEntry", ["path", "mode", "sha"])): """Named tuple encapsulating a single tree entry.""" def in_path(self, path: bytes): """Return a copy of this entry with the given path prepended.""" if not isinstance(self.path, bytes): raise TypeError(f"Expected bytes for path, got {path!r}") return TreeEntry(posixpath.join(path, self.path), self.mode, self.sha) def parse_tree(text, strict=False): """Parse a tree text. Args: text: Serialized text to parse Returns: iterator of tuples of (name, mode, sha) Raises: ObjectFormatException: if the object was malformed in some way """ count = 0 length = len(text) while count < length: mode_end = text.index(b" ", count) mode_text = text[count:mode_end] if strict and mode_text.startswith(b"0"): raise ObjectFormatException(f"Invalid mode '{mode_text}'") try: mode = int(mode_text, 8) except ValueError as exc: raise ObjectFormatException(f"Invalid mode '{mode_text}'") from exc name_end = text.index(b"\0", mode_end) name = text[mode_end + 1 : name_end] count = name_end + 21 sha = text[name_end + 1 : count] if len(sha) != 20: raise ObjectFormatException("Sha has invalid length") hexsha = sha_to_hex(sha) yield (name, mode, hexsha) def serialize_tree(items): """Serialize the items in a tree to a text. Args: items: Sorted iterable over (name, mode, sha) tuples Returns: Serialized tree text as chunks """ for name, mode, hexsha in items: yield ( (f"{mode:04o}").encode("ascii") + b" " + name + b"\0" + hex_to_sha(hexsha) ) def sorted_tree_items(entries, name_order: bool): """Iterate over a tree entries dictionary. Args: name_order: If True, iterate entries in order of their name. If False, iterate entries in tree order, that is, treat subtree entries as having '/' appended. entries: Dictionary mapping names to (mode, sha) tuples Returns: Iterator over (name, mode, hexsha) """ if name_order: key_func = key_entry_name_order else: key_func = key_entry for name, entry in sorted(entries.items(), key=key_func): mode, hexsha = entry # Stricter type checks than normal to mirror checks in the Rust version. mode = int(mode) if not isinstance(hexsha, bytes): raise TypeError(f"Expected bytes for SHA, got {hexsha!r}") yield TreeEntry(name, mode, hexsha) def key_entry(entry: tuple[bytes, tuple[int, ObjectID]]) -> bytes: """Sort key for tree entry. Args: entry: (name, value) tuple """ (name, (mode, _sha)) = entry if stat.S_ISDIR(mode): name += b"/" return name def key_entry_name_order(entry: tuple[bytes, tuple[int, ObjectID]]) -> bytes: """Sort key for tree entry in name order.""" return entry[0] def pretty_format_tree_entry(name, mode, hexsha, encoding="utf-8") -> str: """Pretty format tree entry. Args: name: Name of the directory entry mode: Mode of entry hexsha: Hexsha of the referenced object Returns: string describing the tree entry """ if mode & stat.S_IFDIR: kind = "tree" else: kind = "blob" return "{:04o} {} {}\t{}\n".format( mode, kind, hexsha.decode("ascii"), name.decode(encoding, "replace"), ) class SubmoduleEncountered(Exception): """A submodule was encountered while resolving a path.""" def __init__(self, path, sha) -> None: self.path = path self.sha = sha class Tree(ShaFile): """A Git tree object.""" type_name = b"tree" type_num = 2 __slots__ = "_entries" def __init__(self) -> None: super().__init__() self._entries: dict[bytes, tuple[int, bytes]] = {} @classmethod def from_path(cls, filename): tree = ShaFile.from_path(filename) if not isinstance(tree, cls): raise NotTreeError(filename) return tree def __contains__(self, name) -> bool: return name in self._entries def __getitem__(self, name): return self._entries[name] def __setitem__(self, name, value) -> None: """Set a tree entry by name. Args: name: The name of the entry, as a string. value: A tuple of (mode, hexsha), where mode is the mode of the entry as an integral type and hexsha is the hex SHA of the entry as a string. """ mode, hexsha = value self._entries[name] = (mode, hexsha) self._needs_serialization = True def __delitem__(self, name) -> None: del self._entries[name] self._needs_serialization = True def __len__(self) -> int: return len(self._entries) def __iter__(self): return iter(self._entries) def add(self, name, mode, hexsha) -> None: """Add an entry to the tree. Args: mode: The mode of the entry as an integral type. Not all possible modes are supported by git; see check() for details. name: The name of the entry, as a string. hexsha: The hex SHA of the entry as a string. """ self._entries[name] = mode, hexsha self._needs_serialization = True def iteritems(self, name_order=False) -> Iterator[TreeEntry]: """Iterate over entries. Args: name_order: If True, iterate in name order instead of tree order. Returns: Iterator over (name, mode, sha) tuples """ return sorted_tree_items(self._entries, name_order) def items(self) -> list[TreeEntry]: """Return the sorted entries in this tree. Returns: List with (name, mode, sha) tuples """ return list(self.iteritems()) def _deserialize(self, chunks) -> None: """Grab the entries in the tree.""" try: parsed_entries = parse_tree(b"".join(chunks)) except ValueError as exc: raise ObjectFormatException(exc) from exc # TODO: list comprehension is for efficiency in the common (small) # case; if memory efficiency in the large case is a concern, use a # genexp. self._entries = {n: (m, s) for n, m, s in parsed_entries} def check(self) -> None: """Check this object for internal consistency. Raises: ObjectFormatException: if the object is malformed in some way """ super().check() assert self._chunked_text is not None last = None allowed_modes = ( stat.S_IFREG | 0o755, stat.S_IFREG | 0o644, stat.S_IFLNK, stat.S_IFDIR, S_IFGITLINK, # TODO: optionally exclude as in git fsck --strict stat.S_IFREG | 0o664, ) for name, mode, sha in parse_tree(b"".join(self._chunked_text), True): check_hexsha(sha, f"invalid sha {sha}") if b"/" in name or name in (b"", b".", b"..", b".git"): raise ObjectFormatException( "invalid name {}".format(name.decode("utf-8", "replace")) ) if mode not in allowed_modes: raise ObjectFormatException(f"invalid mode {mode:06o}") entry = (name, (mode, sha)) if last: if key_entry(last) > key_entry(entry): raise ObjectFormatException("entries not sorted") if name == last[0]: raise ObjectFormatException(f"duplicate entry {name}") last = entry def _serialize(self): return list(serialize_tree(self.iteritems())) def as_pretty_string(self) -> str: text: list[str] = [] for name, mode, hexsha in self.iteritems(): text.append(pretty_format_tree_entry(name, mode, hexsha)) return "".join(text) def lookup_path(self, lookup_obj: Callable[[ObjectID], ShaFile], path: bytes): """Look up an object in a Git tree. Args: lookup_obj: Callback for retrieving object by SHA1 path: Path to lookup Returns: A tuple of (mode, SHA) of the resulting path. """ parts = path.split(b"/") sha = self.id mode = None for i, p in enumerate(parts): if not p: continue if mode is not None and S_ISGITLINK(mode): raise SubmoduleEncountered(b"/".join(parts[:i]), sha) obj = lookup_obj(sha) if not isinstance(obj, Tree): raise NotTreeError(sha) mode, sha = obj[p] return mode, sha def parse_timezone(text): """Parse a timezone text fragment (e.g. '+0100'). Args: text: Text to parse. Returns: Tuple with timezone as seconds difference to UTC and a boolean indicating whether this was a UTC timezone prefixed with a negative sign (-0000). """ # cgit parses the first character as the sign, and the rest # as an integer (using strtol), which could also be negative. # We do the same for compatibility. See #697828. if text[0] not in b"+-": raise ValueError("Timezone must start with + or - ({text})".format(**vars())) sign = text[:1] offset = int(text[1:]) if sign == b"-": offset = -offset unnecessary_negative_timezone = offset >= 0 and sign == b"-" signum = ((offset < 0) and -1) or 1 offset = abs(offset) hours = int(offset / 100) minutes = offset % 100 return ( signum * (hours * 3600 + minutes * 60), unnecessary_negative_timezone, ) def format_timezone(offset, unnecessary_negative_timezone=False): """Format a timezone for Git serialization. Args: offset: Timezone offset as seconds difference to UTC unnecessary_negative_timezone: Whether to use a minus sign for UTC or positive timezones (-0000 and --700 rather than +0000 / +0700). """ if offset % 60 != 0: raise ValueError("Unable to handle non-minute offset.") if offset < 0 or unnecessary_negative_timezone: sign = "-" offset = -offset else: sign = "+" return ("%c%02d%02d" % (sign, offset / 3600, (offset / 60) % 60)).encode("ascii") # noqa: UP031 def parse_time_entry(value): """Parse event. Args: value: Bytes representing a git commit/tag line Raises: ObjectFormatException in case of parsing error (malformed field date) Returns: Tuple of (author, time, (timezone, timezone_neg_utc)) """ try: sep = value.rindex(b"> ") except ValueError: return (value, None, (None, False)) try: person = value[0 : sep + 1] rest = value[sep + 2 :] timetext, timezonetext = rest.rsplit(b" ", 1) time = int(timetext) timezone, timezone_neg_utc = parse_timezone(timezonetext) except ValueError as exc: raise ObjectFormatException(exc) from exc return person, time, (timezone, timezone_neg_utc) def format_time_entry(person, time, timezone_info): """Format an event.""" (timezone, timezone_neg_utc) = timezone_info return b" ".join( [person, str(time).encode("ascii"), format_timezone(timezone, timezone_neg_utc)] ) def parse_commit(chunks): """Parse a commit object from chunks. Args: chunks: Chunks to parse Returns: Tuple of (tree, parents, author_info, commit_info, encoding, mergetag, gpgsig, message, extra) """ warnings.warn("parse_commit will be removed in 0.22", DeprecationWarning) parents = [] extra = [] tree = None author_info = (None, None, (None, None)) commit_info = (None, None, (None, None)) encoding = None mergetag = [] message = None gpgsig = None for field, value in _parse_message(chunks): # TODO(jelmer): Enforce ordering if field == _TREE_HEADER: tree = value elif field == _PARENT_HEADER: parents.append(value) elif field == _AUTHOR_HEADER: author_info = parse_time_entry(value) elif field == _COMMITTER_HEADER: commit_info = parse_time_entry(value) elif field == _ENCODING_HEADER: encoding = value elif field == _MERGETAG_HEADER: mergetag.append(Tag.from_string(value + b"\n")) elif field == _GPGSIG_HEADER: gpgsig = value elif field is None: message = value else: extra.append((field, value)) return ( tree, parents, author_info, commit_info, encoding, mergetag, gpgsig, message, extra, ) class Commit(ShaFile): """A git commit object.""" type_name = b"commit" type_num = 1 __slots__ = ( "_author", "_author_time", "_author_timezone", "_author_timezone_neg_utc", "_commit_time", "_commit_timezone", "_commit_timezone_neg_utc", "_committer", "_encoding", "_extra", "_gpgsig", "_mergetag", "_message", "_parents", "_tree", ) def __init__(self) -> None: super().__init__() self._parents: list[bytes] = [] self._encoding: Optional[bytes] = None self._mergetag: list[Tag] = [] self._gpgsig: Optional[bytes] = None self._extra: list[tuple[bytes, Optional[bytes]]] = [] self._author_timezone_neg_utc: Optional[bool] = False self._commit_timezone_neg_utc: Optional[bool] = False @classmethod def from_path(cls, path): commit = ShaFile.from_path(path) if not isinstance(commit, cls): raise NotCommitError(path) return commit def _deserialize(self, chunks) -> None: self._parents = [] self._extra = [] self._tree = None author_info = (None, None, (None, None)) commit_info = (None, None, (None, None)) self._encoding = None self._mergetag = [] self._message = None self._gpgsig = None for field, value in _parse_message(chunks): # TODO(jelmer): Enforce ordering if field == _TREE_HEADER: self._tree = value elif field == _PARENT_HEADER: assert value is not None self._parents.append(value) elif field == _AUTHOR_HEADER: author_info = parse_time_entry(value) elif field == _COMMITTER_HEADER: commit_info = parse_time_entry(value) elif field == _ENCODING_HEADER: self._encoding = value elif field == _MERGETAG_HEADER: assert value is not None self._mergetag.append(Tag.from_string(value + b"\n")) elif field == _GPGSIG_HEADER: self._gpgsig = value elif field is None: self._message = value else: self._extra.append((field, value)) ( self._author, self._author_time, (self._author_timezone, self._author_timezone_neg_utc), ) = author_info ( self._committer, self._commit_time, (self._commit_timezone, self._commit_timezone_neg_utc), ) = commit_info def check(self) -> None: """Check this object for internal consistency. Raises: ObjectFormatException: if the object is malformed in some way """ super().check() assert self._chunked_text is not None self._check_has_member("_tree", "missing tree") self._check_has_member("_author", "missing author") self._check_has_member("_committer", "missing committer") self._check_has_member("_author_time", "missing author time") self._check_has_member("_commit_time", "missing commit time") for parent in self._parents: check_hexsha(parent, "invalid parent sha") check_hexsha(self._tree, "invalid tree sha") check_identity(self._author, "invalid author") check_identity(self._committer, "invalid committer") check_time(self._author_time) check_time(self._commit_time) last = None for field, _ in _parse_message(self._chunked_text): if field == _TREE_HEADER and last is not None: raise ObjectFormatException("unexpected tree") elif field == _PARENT_HEADER and last not in ( _PARENT_HEADER, _TREE_HEADER, ): raise ObjectFormatException("unexpected parent") elif field == _AUTHOR_HEADER and last not in ( _TREE_HEADER, _PARENT_HEADER, ): raise ObjectFormatException("unexpected author") elif field == _COMMITTER_HEADER and last != _AUTHOR_HEADER: raise ObjectFormatException("unexpected committer") elif field == _ENCODING_HEADER and last != _COMMITTER_HEADER: raise ObjectFormatException("unexpected encoding") last = field # TODO: optionally check for duplicate parents def sign(self, keyid: Optional[str] = None) -> None: import gpg with gpg.Context(armor=True) as c: if keyid is not None: key = c.get_key(keyid) with gpg.Context(armor=True, signers=[key]) as ctx: self.gpgsig, unused_result = ctx.sign( self.as_raw_string(), mode=gpg.constants.sig.mode.DETACH, ) else: self.gpgsig, unused_result = c.sign( self.as_raw_string(), mode=gpg.constants.sig.mode.DETACH ) def raw_without_sig(self) -> bytes: """Return raw string serialization without the GPG/SSH signature. self.gpgsig is a signature for the returned raw byte string serialization. """ tmp = self.copy() assert isinstance(tmp, Commit) tmp._gpgsig = None tmp.gpgsig = None return tmp.as_raw_string() def verify(self, keyids: Optional[Iterable[str]] = None) -> None: """Verify GPG signature for this commit (if it is signed). Args: keyids: Optional iterable of trusted keyids for this commit. If this commit is not signed by any key in keyids verification will fail. If not specified, this function only verifies that the commit has a valid signature. Raises: gpg.errors.BadSignatures: if GPG signature verification fails gpg.errors.MissingSignatures: if commit was not signed by a key specified in keyids """ if self._gpgsig is None: return import gpg with gpg.Context() as ctx: data, result = ctx.verify( self.raw_without_sig(), signature=self._gpgsig, ) if keyids: keys = [ctx.get_key(key) for key in keyids] for key in keys: for subkey in keys: for sig in result.signatures: if subkey.can_sign and subkey.fpr == sig.fpr: return raise gpg.errors.MissingSignatures(result, keys, results=(data, result)) def _serialize(self): headers = [] tree_bytes = self._tree.id if isinstance(self._tree, Tree) else self._tree headers.append((_TREE_HEADER, tree_bytes)) for p in self._parents: headers.append((_PARENT_HEADER, p)) headers.append( ( _AUTHOR_HEADER, format_time_entry( self._author, self._author_time, (self._author_timezone, self._author_timezone_neg_utc), ), ) ) headers.append( ( _COMMITTER_HEADER, format_time_entry( self._committer, self._commit_time, (self._commit_timezone, self._commit_timezone_neg_utc), ), ) ) if self.encoding: headers.append((_ENCODING_HEADER, self.encoding)) for mergetag in self.mergetag: headers.append((_MERGETAG_HEADER, mergetag.as_raw_string()[:-1])) headers.extend(self._extra) if self.gpgsig: headers.append((_GPGSIG_HEADER, self.gpgsig)) return list(_format_message(headers, self._message)) tree = serializable_property("tree", "Tree that is the state of this commit") def _get_parents(self): """Return a list of parents of this commit.""" return self._parents def _set_parents(self, value) -> None: """Set a list of parents of this commit.""" self._needs_serialization = True self._parents = value parents = property( _get_parents, _set_parents, doc="Parents of this commit, by their SHA1.", ) def _get_extra(self): """Return extra settings of this commit.""" warnings.warn( "Commit.extra is deprecated. Use Commit._extra instead.", DeprecationWarning, stacklevel=2, ) return self._extra extra = property( _get_extra, doc="Extra header fields not understood (presumably added in a " "newer version of git). Kept verbatim so the object can " "be correctly reserialized. For private commit metadata, use " "pseudo-headers in Commit.message, rather than this field.", ) author = serializable_property("author", "The name of the author of the commit") committer = serializable_property( "committer", "The name of the committer of the commit" ) message = serializable_property("message", "The commit message") commit_time = serializable_property( "commit_time", "The timestamp of the commit. As the number of seconds since the " "epoch.", ) commit_timezone = serializable_property( "commit_timezone", "The zone the commit time is in" ) author_time = serializable_property( "author_time", "The timestamp the commit was written. As the number of " "seconds since the epoch.", ) author_timezone = serializable_property( "author_timezone", "Returns the zone the author time is in." ) encoding = serializable_property("encoding", "Encoding of the commit message.") mergetag = serializable_property("mergetag", "Associated signed tag.") gpgsig = serializable_property("gpgsig", "GPG Signature.") OBJECT_CLASSES = ( Commit, Tree, Blob, Tag, ) _TYPE_MAP: dict[Union[bytes, int], type[ShaFile]] = {} for cls in OBJECT_CLASSES: _TYPE_MAP[cls.type_name] = cls _TYPE_MAP[cls.type_num] = cls # Hold on to the pure-python implementations for testing _parse_tree_py = parse_tree _sorted_tree_items_py = sorted_tree_items try: # Try to import Rust versions from dulwich._objects import ( parse_tree as _parse_tree_rs, ) from dulwich._objects import ( sorted_tree_items as _sorted_tree_items_rs, ) except ImportError: pass else: parse_tree = _parse_tree_rs sorted_tree_items = _sorted_tree_items_rs ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/objectspec.py0000644000175100002000000001662514731042555017003 0ustar00runnerdocker# objectspec.py -- Object specification # Copyright (C) 2014 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Object specification.""" from collections.abc import Iterator from typing import TYPE_CHECKING, Optional, Union from .objects import Commit, ShaFile, Tree if TYPE_CHECKING: from .refs import Ref, RefsContainer from .repo import Repo def to_bytes(text: Union[str, bytes]) -> bytes: if getattr(text, "encode", None) is not None: text = text.encode("ascii") # type: ignore return text # type: ignore def parse_object(repo: "Repo", objectish: Union[bytes, str]) -> "ShaFile": """Parse a string referring to an object. Args: repo: A `Repo` object objectish: A string referring to an object Returns: A git object Raises: KeyError: If the object can not be found """ objectish = to_bytes(objectish) return repo[objectish] def parse_tree(repo: "Repo", treeish: Union[bytes, str]) -> "Tree": """Parse a string referring to a tree. Args: repo: A `Repo` object treeish: A string referring to a tree Returns: A git object Raises: KeyError: If the object can not be found """ treeish = to_bytes(treeish) try: treeish = parse_ref(repo, treeish) except KeyError: # treeish is commit sha pass o = repo[treeish] if o.type_name == b"commit": return repo[o.tree] return o def parse_ref( container: Union["Repo", "RefsContainer"], refspec: Union[str, bytes] ) -> "Ref": """Parse a string referring to a reference. Args: container: A RefsContainer object refspec: A string referring to a ref Returns: A ref Raises: KeyError: If the ref can not be found """ refspec = to_bytes(refspec) possible_refs = [ refspec, b"refs/" + refspec, b"refs/tags/" + refspec, b"refs/heads/" + refspec, b"refs/remotes/" + refspec, b"refs/remotes/" + refspec + b"/HEAD", ] for ref in possible_refs: if ref in container: return ref raise KeyError(refspec) def parse_reftuple( lh_container: Union["Repo", "RefsContainer"], rh_container: Union["Repo", "RefsContainer"], refspec: Union[str, bytes], force: bool = False, ) -> tuple[Optional["Ref"], Optional["Ref"], bool]: """Parse a reftuple spec. Args: lh_container: A RefsContainer object rh_container: A RefsContainer object refspec: A string Returns: A tuple with left and right ref Raises: KeyError: If one of the refs can not be found """ refspec = to_bytes(refspec) if refspec.startswith(b"+"): force = True refspec = refspec[1:] lh: Optional[bytes] rh: Optional[bytes] if b":" in refspec: (lh, rh) = refspec.split(b":") else: lh = rh = refspec if lh == b"": lh = None else: lh = parse_ref(lh_container, lh) if rh == b"": rh = None else: try: rh = parse_ref(rh_container, rh) except KeyError: # TODO: check force? if b"/" not in rh: rh = b"refs/heads/" + rh return (lh, rh, force) def parse_reftuples( lh_container: Union["Repo", "RefsContainer"], rh_container: Union["Repo", "RefsContainer"], refspecs: Union[bytes, list[bytes]], force: bool = False, ): """Parse a list of reftuple specs to a list of reftuples. Args: lh_container: A RefsContainer object rh_container: A RefsContainer object refspecs: A list of refspecs or a string force: Force overwriting for all reftuples Returns: A list of refs Raises: KeyError: If one of the refs can not be found """ if not isinstance(refspecs, list): refspecs = [refspecs] ret = [] # TODO: Support * in refspecs for refspec in refspecs: ret.append(parse_reftuple(lh_container, rh_container, refspec, force=force)) return ret def parse_refs(container, refspecs): """Parse a list of refspecs to a list of refs. Args: container: A RefsContainer object refspecs: A list of refspecs or a string Returns: A list of refs Raises: KeyError: If one of the refs can not be found """ # TODO: Support * in refspecs if not isinstance(refspecs, list): refspecs = [refspecs] ret = [] for refspec in refspecs: ret.append(parse_ref(container, refspec)) return ret def parse_commit_range( repo: "Repo", committishs: Union[str, bytes] ) -> Iterator["Commit"]: """Parse a string referring to a range of commits. Args: repo: A `Repo` object committishs: A string referring to a range of commits. Returns: An iterator over `Commit` objects Raises: KeyError: When the reference commits can not be found ValueError: If the range can not be parsed """ committishs = to_bytes(committishs) # TODO(jelmer): Support more than a single commit.. return iter([parse_commit(repo, committishs)]) class AmbiguousShortId(Exception): """The short id is ambiguous.""" def __init__(self, prefix, options) -> None: self.prefix = prefix self.options = options def scan_for_short_id(object_store, prefix, tp): """Scan an object store for a short id.""" ret = [] for object_id in object_store.iter_prefix(prefix): o = object_store[object_id] if isinstance(o, tp): ret.append(o) if not ret: raise KeyError(prefix) if len(ret) == 1: return ret[0] raise AmbiguousShortId(prefix, ret) def parse_commit(repo: "Repo", committish: Union[str, bytes]) -> "Commit": """Parse a string referring to a single commit. Args: repo: A` Repo` object committish: A string referring to a single commit. Returns: A Commit object Raises: KeyError: When the reference commits can not be found ValueError: If the range can not be parsed """ committish = to_bytes(committish) try: return repo[committish] except KeyError: pass try: return repo[parse_ref(repo, committish)] except KeyError: pass if len(committish) >= 4 and len(committish) < 40: try: int(committish, 16) except ValueError: pass else: try: return scan_for_short_id(repo.object_store, committish, Commit) except KeyError: pass raise KeyError(committish) # TODO: parse_path_in_tree(), which handles e.g. v1.0:Documentation ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/pack.py0000644000175100002000000026370614731042555015604 0ustar00runnerdocker# pack.py -- For dealing with packed git objects. # Copyright (C) 2007 James Westby # Copyright (C) 2008-2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Classes for dealing with packed git objects. A pack is a compact representation of a bunch of objects, stored using deltas where possible. They have two parts, the pack file, which stores the data, and an index that tells you where the data is. To find an object you look in all of the index files 'til you find a match for the object name. You then use the pointer got from this as a pointer in to the corresponding packfile. """ import binascii from collections import defaultdict, deque from contextlib import suppress from io import BytesIO, UnsupportedOperation try: from cdifflib import CSequenceMatcher as SequenceMatcher except ModuleNotFoundError: from difflib import SequenceMatcher import os import struct import sys import warnings import zlib from collections.abc import Iterable, Iterator, Sequence from hashlib import sha1 from itertools import chain from os import SEEK_CUR, SEEK_END from struct import unpack_from from typing import ( BinaryIO, Callable, Generic, Optional, Protocol, TypeVar, Union, ) try: import mmap except ImportError: has_mmap = False else: has_mmap = True # For some reason the above try, except fails to set has_mmap = False for plan9 if sys.platform == "Plan9": has_mmap = False from .errors import ApplyDeltaError, ChecksumMismatch from .file import GitFile from .lru_cache import LRUSizeCache from .objects import ObjectID, ShaFile, hex_to_sha, object_header, sha_to_hex OFS_DELTA = 6 REF_DELTA = 7 DELTA_TYPES = (OFS_DELTA, REF_DELTA) DEFAULT_PACK_DELTA_WINDOW_SIZE = 10 # Keep pack files under 16Mb in memory, otherwise write them out to disk PACK_SPOOL_FILE_MAX_SIZE = 16 * 1024 * 1024 OldUnpackedObject = Union[tuple[Union[bytes, int], list[bytes]], list[bytes]] ResolveExtRefFn = Callable[[bytes], tuple[int, OldUnpackedObject]] ProgressFn = Callable[[int, str], None] PackHint = tuple[int, Optional[bytes]] class UnresolvedDeltas(Exception): """Delta objects could not be resolved.""" def __init__(self, shas) -> None: self.shas = shas class ObjectContainer(Protocol): def add_object(self, obj: ShaFile) -> None: """Add a single object to this object store.""" def add_objects( self, objects: Sequence[tuple[ShaFile, Optional[str]]], progress: Optional[Callable[[str], None]] = None, ) -> None: """Add a set of objects to this object store. Args: objects: Iterable over a list of (object, path) tuples """ def __contains__(self, sha1: bytes) -> bool: """Check if a hex sha is present.""" def __getitem__(self, sha1: bytes) -> ShaFile: """Retrieve an object.""" class PackedObjectContainer(ObjectContainer): def get_unpacked_object( self, sha1: bytes, *, include_comp: bool = False ) -> "UnpackedObject": """Get a raw unresolved object.""" raise NotImplementedError(self.get_unpacked_object) def iterobjects_subset( self, shas: Iterable[bytes], *, allow_missing: bool = False ) -> Iterator[ShaFile]: raise NotImplementedError(self.iterobjects_subset) def iter_unpacked_subset( self, shas: set[bytes], include_comp: bool = False, allow_missing: bool = False, convert_ofs_delta: bool = True, ) -> Iterator["UnpackedObject"]: raise NotImplementedError(self.iter_unpacked_subset) class UnpackedObjectStream: def __iter__(self) -> Iterator["UnpackedObject"]: raise NotImplementedError(self.__iter__) def __len__(self) -> int: raise NotImplementedError(self.__len__) def take_msb_bytes( read: Callable[[int], bytes], crc32: Optional[int] = None ) -> tuple[list[int], Optional[int]]: """Read bytes marked with most significant bit. Args: read: Read function """ ret: list[int] = [] while len(ret) == 0 or ret[-1] & 0x80: b = read(1) if crc32 is not None: crc32 = binascii.crc32(b, crc32) ret.append(ord(b[:1])) return ret, crc32 class PackFileDisappeared(Exception): def __init__(self, obj) -> None: self.obj = obj class UnpackedObject: """Class encapsulating an object unpacked from a pack file. These objects should only be created from within unpack_object. Most members start out as empty and are filled in at various points by read_zlib_chunks, unpack_object, DeltaChainIterator, etc. End users of this object should take care that the function they're getting this object from is guaranteed to set the members they need. """ __slots__ = [ "_sha", # Cached binary SHA. "comp_chunks", # Compressed object chunks. "crc32", # CRC32. "decomp_chunks", # Decompressed object chunks. "decomp_len", # Decompressed length of this object. "delta_base", # Delta base offset or SHA. "obj_chunks", # Decompressed and delta-resolved chunks. "obj_type_num", # Type of this object. "offset", # Offset in its pack. "pack_type_num", # Type of this object in the pack (may be a delta). ] obj_type_num: Optional[int] obj_chunks: Optional[list[bytes]] delta_base: Union[None, bytes, int] decomp_chunks: list[bytes] comp_chunks: Optional[list[bytes]] # TODO(dborowitz): read_zlib_chunks and unpack_object could very well be # methods of this object. def __init__( self, pack_type_num, *, delta_base=None, decomp_len=None, crc32=None, sha=None, decomp_chunks=None, offset=None, ) -> None: self.offset = offset self._sha = sha self.pack_type_num = pack_type_num self.delta_base = delta_base self.comp_chunks = None self.decomp_chunks: list[bytes] = decomp_chunks or [] if decomp_chunks is not None and decomp_len is None: self.decomp_len = sum(map(len, decomp_chunks)) else: self.decomp_len = decomp_len self.crc32 = crc32 if pack_type_num in DELTA_TYPES: self.obj_type_num = None self.obj_chunks = None else: self.obj_type_num = pack_type_num self.obj_chunks = self.decomp_chunks self.delta_base = delta_base def sha(self): """Return the binary SHA of this object.""" if self._sha is None: self._sha = obj_sha(self.obj_type_num, self.obj_chunks) return self._sha def sha_file(self): """Return a ShaFile from this object.""" assert self.obj_type_num is not None and self.obj_chunks is not None return ShaFile.from_raw_chunks(self.obj_type_num, self.obj_chunks) # Only provided for backwards compatibility with code that expects either # chunks or a delta tuple. def _obj(self) -> OldUnpackedObject: """Return the decompressed chunks, or (delta base, delta chunks).""" if self.pack_type_num in DELTA_TYPES: assert isinstance(self.delta_base, (bytes, int)) return (self.delta_base, self.decomp_chunks) else: return self.decomp_chunks def __eq__(self, other): if not isinstance(other, UnpackedObject): return False for slot in self.__slots__: if getattr(self, slot) != getattr(other, slot): return False return True def __ne__(self, other): return not (self == other) def __repr__(self) -> str: data = [f"{s}={getattr(self, s)!r}" for s in self.__slots__] return "{}({})".format(self.__class__.__name__, ", ".join(data)) _ZLIB_BUFSIZE = 4096 def read_zlib_chunks( read_some: Callable[[int], bytes], unpacked: UnpackedObject, include_comp: bool = False, buffer_size: int = _ZLIB_BUFSIZE, ) -> bytes: """Read zlib data from a buffer. This function requires that the buffer have additional data following the compressed data, which is guaranteed to be the case for git pack files. Args: read_some: Read function that returns at least one byte, but may return less than the requested size. unpacked: An UnpackedObject to write result data to. If its crc32 attr is not None, the CRC32 of the compressed bytes will be computed using this starting CRC32. After this function, will have the following attrs set: * comp_chunks (if include_comp is True) * decomp_chunks * decomp_len * crc32 include_comp: If True, include compressed data in the result. buffer_size: Size of the read buffer. Returns: Leftover unused data from the decompression. Raises: zlib.error: if a decompression error occurred. """ if unpacked.decomp_len <= -1: raise ValueError("non-negative zlib data stream size expected") decomp_obj = zlib.decompressobj() comp_chunks = [] decomp_chunks = unpacked.decomp_chunks decomp_len = 0 crc32 = unpacked.crc32 while True: add = read_some(buffer_size) if not add: raise zlib.error("EOF before end of zlib stream") comp_chunks.append(add) decomp = decomp_obj.decompress(add) decomp_len += len(decomp) decomp_chunks.append(decomp) unused = decomp_obj.unused_data if unused: left = len(unused) if crc32 is not None: crc32 = binascii.crc32(add[:-left], crc32) if include_comp: comp_chunks[-1] = add[:-left] break elif crc32 is not None: crc32 = binascii.crc32(add, crc32) if crc32 is not None: crc32 &= 0xFFFFFFFF if decomp_len != unpacked.decomp_len: raise zlib.error("decompressed data does not match expected size") unpacked.crc32 = crc32 if include_comp: unpacked.comp_chunks = comp_chunks return unused def iter_sha1(iter): """Return the hexdigest of the SHA1 over a set of names. Args: iter: Iterator over string objects Returns: 40-byte hex sha1 digest """ sha = sha1() for name in iter: sha.update(name) return sha.hexdigest().encode("ascii") def load_pack_index(path): """Load an index file by path. Args: path: Path to the index file Returns: A PackIndex loaded from the given path """ with GitFile(path, "rb") as f: return load_pack_index_file(path, f) def _load_file_contents(f, size=None): try: fd = f.fileno() except (UnsupportedOperation, AttributeError): fd = None # Attempt to use mmap if possible if fd is not None: if size is None: size = os.fstat(fd).st_size if has_mmap: try: contents = mmap.mmap(fd, size, access=mmap.ACCESS_READ) except OSError: # Perhaps a socket? pass else: return contents, size contents = f.read() size = len(contents) return contents, size def load_pack_index_file(path, f): """Load an index file from a file-like object. Args: path: Path for the index file f: File-like object Returns: A PackIndex loaded from the given file """ contents, size = _load_file_contents(f) if contents[:4] == b"\377tOc": version = struct.unpack(b">L", contents[4:8])[0] if version == 2: return PackIndex2(path, file=f, contents=contents, size=size) else: raise KeyError(f"Unknown pack index format {version}") else: return PackIndex1(path, file=f, contents=contents, size=size) def bisect_find_sha(start, end, sha, unpack_name): """Find a SHA in a data blob with sorted SHAs. Args: start: Start index of range to search end: End index of range to search sha: Sha to find unpack_name: Callback to retrieve SHA by index Returns: Index of the SHA, or None if it wasn't found """ assert start <= end while start <= end: i = (start + end) // 2 file_sha = unpack_name(i) if file_sha < sha: start = i + 1 elif file_sha > sha: end = i - 1 else: return i return None PackIndexEntry = tuple[bytes, int, Optional[int]] class PackIndex: """An index in to a packfile. Given a sha id of an object a pack index can tell you the location in the packfile of that object if it has it. """ def __eq__(self, other): if not isinstance(other, PackIndex): return False for (name1, _, _), (name2, _, _) in zip( self.iterentries(), other.iterentries() ): if name1 != name2: return False return True def __ne__(self, other): return not self.__eq__(other) def __len__(self) -> int: """Return the number of entries in this pack index.""" raise NotImplementedError(self.__len__) def __iter__(self) -> Iterator[bytes]: """Iterate over the SHAs in this pack.""" return map(sha_to_hex, self._itersha()) def iterentries(self) -> Iterator[PackIndexEntry]: """Iterate over the entries in this pack index. Returns: iterator over tuples with object name, offset in packfile and crc32 checksum. """ raise NotImplementedError(self.iterentries) def get_pack_checksum(self) -> bytes: """Return the SHA1 checksum stored for the corresponding packfile. Returns: 20-byte binary digest """ raise NotImplementedError(self.get_pack_checksum) def object_index(self, sha: bytes) -> int: warnings.warn( "Please use object_offset instead", DeprecationWarning, stacklevel=2 ) return self.object_offset(sha) def object_offset(self, sha: bytes) -> int: """Return the offset in to the corresponding packfile for the object. Given the name of an object it will return the offset that object lives at within the corresponding pack file. If the pack file doesn't have the object then None will be returned. """ raise NotImplementedError(self.object_offset) def object_sha1(self, index: int) -> bytes: """Return the SHA1 corresponding to the index in the pack file.""" for name, offset, crc32 in self.iterentries(): if offset == index: return name else: raise KeyError(index) def _object_offset(self, sha: bytes) -> int: """See object_offset. Args: sha: A *binary* SHA string. (20 characters long)_ """ raise NotImplementedError(self._object_offset) def objects_sha1(self) -> bytes: """Return the hex SHA1 over all the shas of all objects in this pack. Note: This is used for the filename of the pack. """ return iter_sha1(self._itersha()) def _itersha(self) -> Iterator[bytes]: """Yield all the SHA1's of the objects in the index, sorted.""" raise NotImplementedError(self._itersha) def close(self) -> None: pass def check(self) -> None: pass class MemoryPackIndex(PackIndex): """Pack index that is stored entirely in memory.""" def __init__(self, entries, pack_checksum=None) -> None: """Create a new MemoryPackIndex. Args: entries: Sequence of name, idx, crc32 (sorted) pack_checksum: Optional pack checksum """ self._by_sha = {} self._by_offset = {} for name, offset, crc32 in entries: self._by_sha[name] = offset self._by_offset[offset] = name self._entries = entries self._pack_checksum = pack_checksum def get_pack_checksum(self): return self._pack_checksum def __len__(self) -> int: return len(self._entries) def object_offset(self, sha): if len(sha) == 40: sha = hex_to_sha(sha) return self._by_sha[sha] def object_sha1(self, offset): return self._by_offset[offset] def _itersha(self): return iter(self._by_sha) def iterentries(self): return iter(self._entries) @classmethod def for_pack(cls, pack): return MemoryPackIndex(pack.sorted_entries(), pack.calculate_checksum()) @classmethod def clone(cls, other_index): return cls(other_index.iterentries(), other_index.get_pack_checksum()) class FilePackIndex(PackIndex): """Pack index that is based on a file. To do the loop it opens the file, and indexes first 256 4 byte groups with the first byte of the sha id. The value in the four byte group indexed is the end of the group that shares the same starting byte. Subtract one from the starting byte and index again to find the start of the group. The values are sorted by sha id within the group, so do the math to find the start and end offset and then bisect in to find if the value is present. """ _fan_out_table: list[int] def __init__(self, filename, file=None, contents=None, size=None) -> None: """Create a pack index object. Provide it with the name of the index file to consider, and it will map it whenever required. """ self._filename = filename # Take the size now, so it can be checked each time we map the file to # ensure that it hasn't changed. if file is None: self._file = GitFile(filename, "rb") else: self._file = file if contents is None: self._contents, self._size = _load_file_contents(self._file, size) else: self._contents, self._size = (contents, size) @property def path(self) -> str: return self._filename def __eq__(self, other): # Quick optimization: if ( isinstance(other, FilePackIndex) and self._fan_out_table != other._fan_out_table ): return False return super().__eq__(other) def close(self) -> None: self._file.close() if getattr(self._contents, "close", None) is not None: self._contents.close() def __len__(self) -> int: """Return the number of entries in this pack index.""" return self._fan_out_table[-1] def _unpack_entry(self, i: int) -> PackIndexEntry: """Unpack the i-th entry in the index file. Returns: Tuple with object name (SHA), offset in pack file and CRC32 checksum (if known). """ raise NotImplementedError(self._unpack_entry) def _unpack_name(self, i) -> bytes: """Unpack the i-th name from the index file.""" raise NotImplementedError(self._unpack_name) def _unpack_offset(self, i) -> int: """Unpack the i-th object offset from the index file.""" raise NotImplementedError(self._unpack_offset) def _unpack_crc32_checksum(self, i) -> Optional[int]: """Unpack the crc32 checksum for the ith object from the index file.""" raise NotImplementedError(self._unpack_crc32_checksum) def _itersha(self) -> Iterator[bytes]: for i in range(len(self)): yield self._unpack_name(i) def iterentries(self) -> Iterator[PackIndexEntry]: """Iterate over the entries in this pack index. Returns: iterator over tuples with object name, offset in packfile and crc32 checksum. """ for i in range(len(self)): yield self._unpack_entry(i) def _read_fan_out_table(self, start_offset: int): ret = [] for i in range(0x100): fanout_entry = self._contents[ start_offset + i * 4 : start_offset + (i + 1) * 4 ] ret.append(struct.unpack(">L", fanout_entry)[0]) return ret def check(self) -> None: """Check that the stored checksum matches the actual checksum.""" actual = self.calculate_checksum() stored = self.get_stored_checksum() if actual != stored: raise ChecksumMismatch(stored, actual) def calculate_checksum(self) -> bytes: """Calculate the SHA1 checksum over this pack index. Returns: This is a 20-byte binary digest """ return sha1(self._contents[:-20]).digest() def get_pack_checksum(self) -> bytes: """Return the SHA1 checksum stored for the corresponding packfile. Returns: 20-byte binary digest """ return bytes(self._contents[-40:-20]) def get_stored_checksum(self) -> bytes: """Return the SHA1 checksum stored for this index. Returns: 20-byte binary digest """ return bytes(self._contents[-20:]) def object_offset(self, sha: bytes) -> int: """Return the offset in to the corresponding packfile for the object. Given the name of an object it will return the offset that object lives at within the corresponding pack file. If the pack file doesn't have the object then None will be returned. """ if len(sha) == 40: sha = hex_to_sha(sha) try: return self._object_offset(sha) except ValueError as exc: closed = getattr(self._contents, "closed", None) if closed in (None, True): raise PackFileDisappeared(self) from exc raise def _object_offset(self, sha: bytes) -> int: """See object_offset. Args: sha: A *binary* SHA string. (20 characters long)_ """ assert len(sha) == 20 idx = ord(sha[:1]) if idx == 0: start = 0 else: start = self._fan_out_table[idx - 1] end = self._fan_out_table[idx] i = bisect_find_sha(start, end, sha, self._unpack_name) if i is None: raise KeyError(sha) return self._unpack_offset(i) def iter_prefix(self, prefix: bytes) -> Iterator[bytes]: """Iterate over all SHA1s with the given prefix.""" start = ord(prefix[:1]) if start == 0: start = 0 else: start = self._fan_out_table[start - 1] end = ord(prefix[:1]) + 1 if end == 0x100: end = len(self) else: end = self._fan_out_table[end] assert start <= end started = False for i in range(start, end): name: bytes = self._unpack_name(i) if name.startswith(prefix): yield name started = True elif started: break class PackIndex1(FilePackIndex): """Version 1 Pack Index file.""" def __init__(self, filename: str, file=None, contents=None, size=None) -> None: super().__init__(filename, file, contents, size) self.version = 1 self._fan_out_table = self._read_fan_out_table(0) def _unpack_entry(self, i): (offset, name) = unpack_from(">L20s", self._contents, (0x100 * 4) + (i * 24)) return (name, offset, None) def _unpack_name(self, i): offset = (0x100 * 4) + (i * 24) + 4 return self._contents[offset : offset + 20] def _unpack_offset(self, i): offset = (0x100 * 4) + (i * 24) return unpack_from(">L", self._contents, offset)[0] def _unpack_crc32_checksum(self, i) -> None: # Not stored in v1 index files return None class PackIndex2(FilePackIndex): """Version 2 Pack Index file.""" def __init__(self, filename: str, file=None, contents=None, size=None) -> None: super().__init__(filename, file, contents, size) if self._contents[:4] != b"\377tOc": raise AssertionError("Not a v2 pack index file") (self.version,) = unpack_from(b">L", self._contents, 4) if self.version != 2: raise AssertionError(f"Version was {self.version}") self._fan_out_table = self._read_fan_out_table(8) self._name_table_offset = 8 + 0x100 * 4 self._crc32_table_offset = self._name_table_offset + 20 * len(self) self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self) self._pack_offset_largetable_offset = self._pack_offset_table_offset + 4 * len( self ) def _unpack_entry(self, i): return ( self._unpack_name(i), self._unpack_offset(i), self._unpack_crc32_checksum(i), ) def _unpack_name(self, i): offset = self._name_table_offset + i * 20 return self._contents[offset : offset + 20] def _unpack_offset(self, i): offset = self._pack_offset_table_offset + i * 4 offset = unpack_from(">L", self._contents, offset)[0] if offset & (2**31): offset = self._pack_offset_largetable_offset + (offset & (2**31 - 1)) * 8 offset = unpack_from(">Q", self._contents, offset)[0] return offset def _unpack_crc32_checksum(self, i): return unpack_from(">L", self._contents, self._crc32_table_offset + i * 4)[0] def read_pack_header(read) -> tuple[int, int]: """Read the header of a pack file. Args: read: Read function Returns: Tuple of (pack version, number of objects). If no data is available to read, returns (None, None). """ header = read(12) if not header: raise AssertionError("file too short to contain pack") if header[:4] != b"PACK": raise AssertionError(f"Invalid pack header {header!r}") (version,) = unpack_from(b">L", header, 4) if version not in (2, 3): raise AssertionError(f"Version was {version}") (num_objects,) = unpack_from(b">L", header, 8) return (version, num_objects) def chunks_length(chunks: Union[bytes, Iterable[bytes]]) -> int: if isinstance(chunks, bytes): return len(chunks) else: return sum(map(len, chunks)) def unpack_object( read_all: Callable[[int], bytes], read_some: Optional[Callable[[int], bytes]] = None, compute_crc32=False, include_comp=False, zlib_bufsize=_ZLIB_BUFSIZE, ) -> tuple[UnpackedObject, bytes]: """Unpack a Git object. Args: read_all: Read function that blocks until the number of requested bytes are read. read_some: Read function that returns at least one byte, but may not return the number of bytes requested. compute_crc32: If True, compute the CRC32 of the compressed data. If False, the returned CRC32 will be None. include_comp: If True, include compressed data in the result. zlib_bufsize: An optional buffer size for zlib operations. Returns: A tuple of (unpacked, unused), where unused is the unused data leftover from decompression, and unpacked in an UnpackedObject with the following attrs set: * obj_chunks (for non-delta types) * pack_type_num * delta_base (for delta types) * comp_chunks (if include_comp is True) * decomp_chunks * decomp_len * crc32 (if compute_crc32 is True) """ if read_some is None: read_some = read_all if compute_crc32: crc32 = 0 else: crc32 = None raw, crc32 = take_msb_bytes(read_all, crc32=crc32) type_num = (raw[0] >> 4) & 0x07 size = raw[0] & 0x0F for i, byte in enumerate(raw[1:]): size += (byte & 0x7F) << ((i * 7) + 4) delta_base: Union[int, bytes, None] raw_base = len(raw) if type_num == OFS_DELTA: raw, crc32 = take_msb_bytes(read_all, crc32=crc32) raw_base += len(raw) if raw[-1] & 0x80: raise AssertionError delta_base_offset = raw[0] & 0x7F for byte in raw[1:]: delta_base_offset += 1 delta_base_offset <<= 7 delta_base_offset += byte & 0x7F delta_base = delta_base_offset elif type_num == REF_DELTA: delta_base_obj = read_all(20) if crc32 is not None: crc32 = binascii.crc32(delta_base_obj, crc32) delta_base = delta_base_obj raw_base += 20 else: delta_base = None unpacked = UnpackedObject( type_num, delta_base=delta_base, decomp_len=size, crc32=crc32 ) unused = read_zlib_chunks( read_some, unpacked, buffer_size=zlib_bufsize, include_comp=include_comp, ) return unpacked, unused def _compute_object_size(value): """Compute the size of a unresolved object for use with LRUSizeCache.""" (num, obj) = value if num in DELTA_TYPES: return chunks_length(obj[1]) return chunks_length(obj) class PackStreamReader: """Class to read a pack stream. The pack is read from a ReceivableProtocol using read() or recv() as appropriate. """ def __init__(self, read_all, read_some=None, zlib_bufsize=_ZLIB_BUFSIZE) -> None: self.read_all = read_all if read_some is None: self.read_some = read_all else: self.read_some = read_some self.sha = sha1() self._offset = 0 self._rbuf = BytesIO() # trailer is a deque to avoid memory allocation on small reads self._trailer: deque[bytes] = deque() self._zlib_bufsize = zlib_bufsize def _read(self, read, size): """Read up to size bytes using the given callback. As a side effect, update the verifier's hash (excluding the last 20 bytes read). Args: read: The read callback to read from. size: The maximum number of bytes to read; the particular behavior is callback-specific. """ data = read(size) # maintain a trailer of the last 20 bytes we've read n = len(data) self._offset += n tn = len(self._trailer) if n >= 20: to_pop = tn to_add = 20 else: to_pop = max(n + tn - 20, 0) to_add = n self.sha.update( bytes(bytearray([self._trailer.popleft() for _ in range(to_pop)])) ) self._trailer.extend(data[-to_add:]) # hash everything but the trailer self.sha.update(data[:-to_add]) return data def _buf_len(self): buf = self._rbuf start = buf.tell() buf.seek(0, SEEK_END) end = buf.tell() buf.seek(start) return end - start @property def offset(self): return self._offset - self._buf_len() def read(self, size): """Read, blocking until size bytes are read.""" buf_len = self._buf_len() if buf_len >= size: return self._rbuf.read(size) buf_data = self._rbuf.read() self._rbuf = BytesIO() return buf_data + self._read(self.read_all, size - buf_len) def recv(self, size): """Read up to size bytes, blocking until one byte is read.""" buf_len = self._buf_len() if buf_len: data = self._rbuf.read(size) if size >= buf_len: self._rbuf = BytesIO() return data return self._read(self.read_some, size) def __len__(self) -> int: return self._num_objects def read_objects(self, compute_crc32=False) -> Iterator[UnpackedObject]: """Read the objects in this pack file. Args: compute_crc32: If True, compute the CRC32 of the compressed data. If False, the returned CRC32 will be None. Returns: Iterator over UnpackedObjects with the following members set: offset obj_type_num obj_chunks (for non-delta types) delta_base (for delta types) decomp_chunks decomp_len crc32 (if compute_crc32 is True) Raises: ChecksumMismatch: if the checksum of the pack contents does not match the checksum in the pack trailer. zlib.error: if an error occurred during zlib decompression. IOError: if an error occurred writing to the output file. """ pack_version, self._num_objects = read_pack_header(self.read) for i in range(self._num_objects): offset = self.offset unpacked, unused = unpack_object( self.read, read_some=self.recv, compute_crc32=compute_crc32, zlib_bufsize=self._zlib_bufsize, ) unpacked.offset = offset # prepend any unused data to current read buffer buf = BytesIO() buf.write(unused) buf.write(self._rbuf.read()) buf.seek(0) self._rbuf = buf yield unpacked if self._buf_len() < 20: # If the read buffer is full, then the last read() got the whole # trailer off the wire. If not, it means there is still some of the # trailer to read. We need to read() all 20 bytes; N come from the # read buffer and (20 - N) come from the wire. self.read(20) pack_sha = bytearray(self._trailer) # type: ignore if pack_sha != self.sha.digest(): raise ChecksumMismatch(sha_to_hex(pack_sha), self.sha.hexdigest()) class PackStreamCopier(PackStreamReader): """Class to verify a pack stream as it is being read. The pack is read from a ReceivableProtocol using read() or recv() as appropriate and written out to the given file-like object. """ def __init__(self, read_all, read_some, outfile, delta_iter=None) -> None: """Initialize the copier. Args: read_all: Read function that blocks until the number of requested bytes are read. read_some: Read function that returns at least one byte, but may not return the number of bytes requested. outfile: File-like object to write output through. delta_iter: Optional DeltaChainIterator to record deltas as we read them. """ super().__init__(read_all, read_some=read_some) self.outfile = outfile self._delta_iter = delta_iter def _read(self, read, size): """Read data from the read callback and write it to the file.""" data = super()._read(read, size) self.outfile.write(data) return data def verify(self, progress=None) -> None: """Verify a pack stream and write it to the output file. See PackStreamReader.iterobjects for a list of exceptions this may throw. """ i = 0 # default count of entries if read_objects() is empty for i, unpacked in enumerate(self.read_objects()): if self._delta_iter: self._delta_iter.record(unpacked) if progress is not None: progress(f"copying pack entries: {i}/{len(self)}\r".encode("ascii")) if progress is not None: progress(f"copied {i} pack entries\n".encode("ascii")) def obj_sha(type, chunks): """Compute the SHA for a numeric type and object chunks.""" sha = sha1() sha.update(object_header(type, chunks_length(chunks))) if isinstance(chunks, bytes): sha.update(chunks) else: for chunk in chunks: sha.update(chunk) return sha.digest() def compute_file_sha(f, start_ofs=0, end_ofs=0, buffer_size=1 << 16): """Hash a portion of a file into a new SHA. Args: f: A file-like object to read from that supports seek(). start_ofs: The offset in the file to start reading at. end_ofs: The offset in the file to end reading at, relative to the end of the file. buffer_size: A buffer size for reading. Returns: A new SHA object updated with data read from the file. """ sha = sha1() f.seek(0, SEEK_END) length = f.tell() if (end_ofs < 0 and length + end_ofs < start_ofs) or end_ofs > length: raise AssertionError( f"Attempt to read beyond file length. start_ofs: {start_ofs}, end_ofs: {end_ofs}, file length: {length}" ) todo = length + end_ofs - start_ofs f.seek(start_ofs) while todo: data = f.read(min(todo, buffer_size)) sha.update(data) todo -= len(data) return sha class PackData: """The data contained in a packfile. Pack files can be accessed both sequentially for exploding a pack, and directly with the help of an index to retrieve a specific object. The objects within are either complete or a delta against another. The header is variable length. If the MSB of each byte is set then it indicates that the subsequent byte is still part of the header. For the first byte the next MS bits are the type, which tells you the type of object, and whether it is a delta. The LS byte is the lowest bits of the size. For each subsequent byte the LS 7 bits are the next MS bits of the size, i.e. the last byte of the header contains the MS bits of the size. For the complete objects the data is stored as zlib deflated data. The size in the header is the uncompressed object size, so to uncompress you need to just keep feeding data to zlib until you get an object back, or it errors on bad data. This is done here by just giving the complete buffer from the start of the deflated object on. This is bad, but until I get mmap sorted out it will have to do. Currently there are no integrity checks done. Also no attempt is made to try and detect the delta case, or a request for an object at the wrong position. It will all just throw a zlib or KeyError. """ def __init__(self, filename, file=None, size=None) -> None: """Create a PackData object representing the pack in the given filename. The file must exist and stay readable until the object is disposed of. It must also stay the same size. It will be mapped whenever needed. Currently there is a restriction on the size of the pack as the python mmap implementation is flawed. """ self._filename = filename self._size = size self._header_size = 12 if file is None: self._file = GitFile(self._filename, "rb") else: self._file = file (version, self._num_objects) = read_pack_header(self._file.read) self._offset_cache = LRUSizeCache[int, tuple[int, OldUnpackedObject]]( 1024 * 1024 * 20, compute_size=_compute_object_size ) @property def filename(self): return os.path.basename(self._filename) @property def path(self): return self._filename @classmethod def from_file(cls, file, size=None): return cls(str(file), file=file, size=size) @classmethod def from_path(cls, path): return cls(filename=path) def close(self) -> None: self._file.close() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def __eq__(self, other): if isinstance(other, PackData): return self.get_stored_checksum() == other.get_stored_checksum() return False def _get_size(self): if self._size is not None: return self._size self._size = os.path.getsize(self._filename) if self._size < self._header_size: errmsg = f"{self._filename} is too small for a packfile ({self._size} < {self._header_size})" raise AssertionError(errmsg) return self._size def __len__(self) -> int: """Returns the number of objects in this pack.""" return self._num_objects def calculate_checksum(self): """Calculate the checksum for this pack. Returns: 20-byte binary SHA1 digest """ return compute_file_sha(self._file, end_ofs=-20).digest() def iter_unpacked(self, *, include_comp: bool = False): self._file.seek(self._header_size) if self._num_objects is None: return for _ in range(self._num_objects): offset = self._file.tell() unpacked, unused = unpack_object( self._file.read, compute_crc32=False, include_comp=include_comp ) unpacked.offset = offset yield unpacked # Back up over unused data. self._file.seek(-len(unused), SEEK_CUR) def iterentries( self, progress=None, resolve_ext_ref: Optional[ResolveExtRefFn] = None ): """Yield entries summarizing the contents of this pack. Args: progress: Progress function, called with current and total object count. Returns: iterator of tuples with (sha, offset, crc32) """ num_objects = self._num_objects indexer = PackIndexer.for_pack_data(self, resolve_ext_ref=resolve_ext_ref) for i, result in enumerate(indexer): if progress is not None: progress(i, num_objects) yield result def sorted_entries( self, progress: Optional[ProgressFn] = None, resolve_ext_ref: Optional[ResolveExtRefFn] = None, ): """Return entries in this pack, sorted by SHA. Args: progress: Progress function, called with current and total object count Returns: Iterator of tuples with (sha, offset, crc32) """ return sorted( self.iterentries(progress=progress, resolve_ext_ref=resolve_ext_ref) ) def create_index_v1(self, filename, progress=None, resolve_ext_ref=None): """Create a version 1 file for this data file. Args: filename: Index filename. progress: Progress report function Returns: Checksum of index file """ entries = self.sorted_entries( progress=progress, resolve_ext_ref=resolve_ext_ref ) with GitFile(filename, "wb") as f: return write_pack_index_v1(f, entries, self.calculate_checksum()) def create_index_v2(self, filename, progress=None, resolve_ext_ref=None): """Create a version 2 index file for this data file. Args: filename: Index filename. progress: Progress report function Returns: Checksum of index file """ entries = self.sorted_entries( progress=progress, resolve_ext_ref=resolve_ext_ref ) with GitFile(filename, "wb") as f: return write_pack_index_v2(f, entries, self.calculate_checksum()) def create_index(self, filename, progress=None, version=2, resolve_ext_ref=None): """Create an index file for this data file. Args: filename: Index filename. progress: Progress report function Returns: Checksum of index file """ if version == 1: return self.create_index_v1( filename, progress, resolve_ext_ref=resolve_ext_ref ) elif version == 2: return self.create_index_v2( filename, progress, resolve_ext_ref=resolve_ext_ref ) else: raise ValueError(f"unknown index format {version}") def get_stored_checksum(self): """Return the expected checksum stored in this pack.""" self._file.seek(-20, SEEK_END) return self._file.read(20) def check(self) -> None: """Check the consistency of this pack.""" actual = self.calculate_checksum() stored = self.get_stored_checksum() if actual != stored: raise ChecksumMismatch(stored, actual) def get_unpacked_object_at( self, offset: int, *, include_comp: bool = False ) -> UnpackedObject: """Given offset in the packfile return a UnpackedObject.""" assert offset >= self._header_size self._file.seek(offset) unpacked, _ = unpack_object(self._file.read, include_comp=include_comp) unpacked.offset = offset return unpacked def get_object_at(self, offset: int) -> tuple[int, OldUnpackedObject]: """Given an offset in to the packfile return the object that is there. Using the associated index the location of an object can be looked up, and then the packfile can be asked directly for that object using this function. """ try: return self._offset_cache[offset] except KeyError: pass unpacked = self.get_unpacked_object_at(offset, include_comp=False) return (unpacked.pack_type_num, unpacked._obj()) T = TypeVar("T") class DeltaChainIterator(Generic[T]): """Abstract iterator over pack data based on delta chains. Each object in the pack is guaranteed to be inflated exactly once, regardless of how many objects reference it as a delta base. As a result, memory usage is proportional to the length of the longest delta chain. Subclasses can override _result to define the result type of the iterator. By default, results are UnpackedObjects with the following members set: * offset * obj_type_num * obj_chunks * pack_type_num * delta_base (for delta types) * comp_chunks (if _include_comp is True) * decomp_chunks * decomp_len * crc32 (if _compute_crc32 is True) """ _compute_crc32 = False _include_comp = False def __init__(self, file_obj, *, resolve_ext_ref=None) -> None: self._file = file_obj self._resolve_ext_ref = resolve_ext_ref self._pending_ofs: dict[int, list[int]] = defaultdict(list) self._pending_ref: dict[bytes, list[int]] = defaultdict(list) self._full_ofs: list[tuple[int, int]] = [] self._ext_refs: list[bytes] = [] @classmethod def for_pack_data(cls, pack_data: PackData, resolve_ext_ref=None): walker = cls(None, resolve_ext_ref=resolve_ext_ref) walker.set_pack_data(pack_data) for unpacked in pack_data.iter_unpacked(include_comp=False): walker.record(unpacked) return walker @classmethod def for_pack_subset( cls, pack: "Pack", shas: Iterable[bytes], *, allow_missing: bool = False, resolve_ext_ref=None, ): walker = cls(None, resolve_ext_ref=resolve_ext_ref) walker.set_pack_data(pack.data) todo = set() for sha in shas: assert isinstance(sha, bytes) try: off = pack.index.object_offset(sha) except KeyError: if not allow_missing: raise else: todo.add(off) done = set() while todo: off = todo.pop() unpacked = pack.data.get_unpacked_object_at(off) walker.record(unpacked) done.add(off) base_ofs = None if unpacked.pack_type_num == OFS_DELTA: base_ofs = unpacked.offset - unpacked.delta_base elif unpacked.pack_type_num == REF_DELTA: with suppress(KeyError): assert isinstance(unpacked.delta_base, bytes) base_ofs = pack.index.object_index(unpacked.delta_base) if base_ofs is not None and base_ofs not in done: todo.add(base_ofs) return walker def record(self, unpacked: UnpackedObject) -> None: type_num = unpacked.pack_type_num offset = unpacked.offset if type_num == OFS_DELTA: base_offset = offset - unpacked.delta_base self._pending_ofs[base_offset].append(offset) elif type_num == REF_DELTA: assert isinstance(unpacked.delta_base, bytes) self._pending_ref[unpacked.delta_base].append(offset) else: self._full_ofs.append((offset, type_num)) def set_pack_data(self, pack_data: PackData) -> None: self._file = pack_data._file def _walk_all_chains(self): for offset, type_num in self._full_ofs: yield from self._follow_chain(offset, type_num, None) yield from self._walk_ref_chains() assert not self._pending_ofs, repr(self._pending_ofs) def _ensure_no_pending(self) -> None: if self._pending_ref: raise UnresolvedDeltas([sha_to_hex(s) for s in self._pending_ref]) def _walk_ref_chains(self): if not self._resolve_ext_ref: self._ensure_no_pending() return for base_sha, pending in sorted(self._pending_ref.items()): if base_sha not in self._pending_ref: continue try: type_num, chunks = self._resolve_ext_ref(base_sha) except KeyError: # Not an external ref, but may depend on one. Either it will # get popped via a _follow_chain call, or we will raise an # error below. continue self._ext_refs.append(base_sha) self._pending_ref.pop(base_sha) for new_offset in pending: yield from self._follow_chain(new_offset, type_num, chunks) self._ensure_no_pending() def _result(self, unpacked: UnpackedObject) -> T: raise NotImplementedError def _resolve_object( self, offset: int, obj_type_num: int, base_chunks: list[bytes] ) -> UnpackedObject: self._file.seek(offset) unpacked, _ = unpack_object( self._file.read, include_comp=self._include_comp, compute_crc32=self._compute_crc32, ) unpacked.offset = offset if base_chunks is None: assert unpacked.pack_type_num == obj_type_num else: assert unpacked.pack_type_num in DELTA_TYPES unpacked.obj_type_num = obj_type_num unpacked.obj_chunks = apply_delta(base_chunks, unpacked.decomp_chunks) return unpacked def _follow_chain(self, offset: int, obj_type_num: int, base_chunks: list[bytes]): # Unlike PackData.get_object_at, there is no need to cache offsets as # this approach by design inflates each object exactly once. todo = [(offset, obj_type_num, base_chunks)] while todo: (offset, obj_type_num, base_chunks) = todo.pop() unpacked = self._resolve_object(offset, obj_type_num, base_chunks) yield self._result(unpacked) unblocked = chain( self._pending_ofs.pop(unpacked.offset, []), self._pending_ref.pop(unpacked.sha(), []), ) todo.extend( (new_offset, unpacked.obj_type_num, unpacked.obj_chunks) # type: ignore for new_offset in unblocked ) def __iter__(self) -> Iterator[T]: return self._walk_all_chains() def ext_refs(self): return self._ext_refs class UnpackedObjectIterator(DeltaChainIterator[UnpackedObject]): """Delta chain iterator that yield unpacked objects.""" def _result(self, unpacked): return unpacked class PackIndexer(DeltaChainIterator[PackIndexEntry]): """Delta chain iterator that yields index entries.""" _compute_crc32 = True def _result(self, unpacked): return unpacked.sha(), unpacked.offset, unpacked.crc32 class PackInflater(DeltaChainIterator[ShaFile]): """Delta chain iterator that yields ShaFile objects.""" def _result(self, unpacked): return unpacked.sha_file() class SHA1Reader: """Wrapper for file-like object that remembers the SHA1 of its data.""" def __init__(self, f) -> None: self.f = f self.sha1 = sha1(b"") def read(self, num=None): data = self.f.read(num) self.sha1.update(data) return data def check_sha(self) -> None: stored = self.f.read(20) if stored != self.sha1.digest(): raise ChecksumMismatch(self.sha1.hexdigest(), sha_to_hex(stored)) def close(self): return self.f.close() def tell(self): return self.f.tell() class SHA1Writer: """Wrapper for file-like object that remembers the SHA1 of its data.""" def __init__(self, f) -> None: self.f = f self.length = 0 self.sha1 = sha1(b"") def write(self, data) -> None: self.sha1.update(data) self.f.write(data) self.length += len(data) def write_sha(self): sha = self.sha1.digest() assert len(sha) == 20 self.f.write(sha) self.length += len(sha) return sha def close(self): sha = self.write_sha() self.f.close() return sha def offset(self): return self.length def tell(self): return self.f.tell() def pack_object_header(type_num, delta_base, size): """Create a pack object header for the given object info. Args: type_num: Numeric type of the object. delta_base: Delta base offset or ref, or None for whole objects. size: Uncompressed object size. Returns: A header for a packed object. """ header = [] c = (type_num << 4) | (size & 15) size >>= 4 while size: header.append(c | 0x80) c = size & 0x7F size >>= 7 header.append(c) if type_num == OFS_DELTA: ret = [delta_base & 0x7F] delta_base >>= 7 while delta_base: delta_base -= 1 ret.insert(0, 0x80 | (delta_base & 0x7F)) delta_base >>= 7 header.extend(ret) elif type_num == REF_DELTA: assert len(delta_base) == 20 header += delta_base return bytearray(header) def pack_object_chunks(type, object, compression_level=-1): """Generate chunks for a pack object. Args: type: Numeric type of the object object: Object to write compression_level: the zlib compression level Returns: Chunks """ if type in DELTA_TYPES: delta_base, object = object else: delta_base = None if isinstance(object, bytes): object = [object] yield bytes(pack_object_header(type, delta_base, sum(map(len, object)))) compressor = zlib.compressobj(level=compression_level) for data in object: yield compressor.compress(data) yield compressor.flush() def write_pack_object(write, type, object, sha=None, compression_level=-1): """Write pack object to a file. Args: write: Write function to use type: Numeric type of the object object: Object to write compression_level: the zlib compression level Returns: Tuple with offset at which the object was written, and crc32 """ crc32 = 0 for chunk in pack_object_chunks(type, object, compression_level=compression_level): write(chunk) if sha is not None: sha.update(chunk) crc32 = binascii.crc32(chunk, crc32) return crc32 & 0xFFFFFFFF def write_pack( filename, objects: Union[Sequence[ShaFile], Sequence[tuple[ShaFile, Optional[bytes]]]], *, deltify: Optional[bool] = None, delta_window_size: Optional[int] = None, compression_level: int = -1, ): """Write a new pack data file. Args: filename: Path to the new pack file (without .pack extension) container: PackedObjectContainer entries: Sequence of (object_id, path) tuples to write delta_window_size: Delta window size deltify: Whether to deltify pack objects compression_level: the zlib compression level Returns: Tuple with checksum of pack file and index file """ with GitFile(filename + ".pack", "wb") as f: entries, data_sum = write_pack_objects( f.write, objects, delta_window_size=delta_window_size, deltify=deltify, compression_level=compression_level, ) entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()]) with GitFile(filename + ".idx", "wb") as f: return data_sum, write_pack_index_v2(f, entries, data_sum) def pack_header_chunks(num_objects): """Yield chunks for a pack header.""" yield b"PACK" # Pack header yield struct.pack(b">L", 2) # Pack version yield struct.pack(b">L", num_objects) # Number of objects in pack def write_pack_header(write, num_objects) -> None: """Write a pack header for the given number of objects.""" if hasattr(write, "write"): write = write.write warnings.warn( "write_pack_header() now takes a write rather than file argument", DeprecationWarning, stacklevel=2, ) for chunk in pack_header_chunks(num_objects): write(chunk) def find_reusable_deltas( container: PackedObjectContainer, object_ids: set[bytes], *, other_haves: Optional[set[bytes]] = None, progress=None, ) -> Iterator[UnpackedObject]: if other_haves is None: other_haves = set() reused = 0 for i, unpacked in enumerate( container.iter_unpacked_subset( object_ids, allow_missing=True, convert_ofs_delta=True ) ): if progress is not None and i % 1000 == 0: progress(f"checking for reusable deltas: {i}/{len(object_ids)}\r".encode()) if unpacked.pack_type_num == REF_DELTA: hexsha = sha_to_hex(unpacked.delta_base) if hexsha in object_ids or hexsha in other_haves: yield unpacked reused += 1 if progress is not None: progress((f"found {reused} deltas to reuse\n").encode()) def deltify_pack_objects( objects: Union[Iterator[bytes], Iterator[tuple[ShaFile, Optional[bytes]]]], *, window_size: Optional[int] = None, progress=None, ) -> Iterator[UnpackedObject]: """Generate deltas for pack objects. Args: objects: An iterable of (object, path) tuples to deltify. window_size: Window size; None for default Returns: Iterator over type_num, object id, delta_base, content delta_base is None for full text entries """ def objects_with_hints(): for e in objects: if isinstance(e, ShaFile): yield (e, (e.type_num, None)) else: yield (e[0], (e[0].type_num, e[1])) yield from deltas_from_sorted_objects( sort_objects_for_delta(objects_with_hints()), window_size=window_size, progress=progress, ) def sort_objects_for_delta( objects: Union[Iterator[ShaFile], Iterator[tuple[ShaFile, Optional[PackHint]]]], ) -> Iterator[ShaFile]: magic = [] for entry in objects: if isinstance(entry, tuple): obj, hint = entry if hint is None: type_num = None path = None else: (type_num, path) = hint else: obj = entry magic.append((type_num, path, -obj.raw_length(), obj)) # Build a list of objects ordered by the magic Linus heuristic # This helps us find good objects to diff against us magic.sort() return (x[3] for x in magic) def deltas_from_sorted_objects( objects, window_size: Optional[int] = None, progress=None ): # TODO(jelmer): Use threads if window_size is None: window_size = DEFAULT_PACK_DELTA_WINDOW_SIZE possible_bases: deque[tuple[bytes, int, list[bytes]]] = deque() for i, o in enumerate(objects): if progress is not None and i % 1000 == 0: progress((f"generating deltas: {i}\r").encode()) raw = o.as_raw_chunks() winner = raw winner_len = sum(map(len, winner)) winner_base = None for base_id, base_type_num, base in possible_bases: if base_type_num != o.type_num: continue delta_len = 0 delta = [] for chunk in create_delta(base, raw): delta_len += len(chunk) if delta_len >= winner_len: break delta.append(chunk) else: winner_base = base_id winner = delta winner_len = sum(map(len, winner)) yield UnpackedObject( o.type_num, sha=o.sha().digest(), delta_base=winner_base, decomp_len=winner_len, decomp_chunks=winner, ) possible_bases.appendleft((o.sha().digest(), o.type_num, raw)) while len(possible_bases) > window_size: possible_bases.pop() def pack_objects_to_data( objects: Union[Sequence[ShaFile], Sequence[tuple[ShaFile, Optional[bytes]]]], *, deltify: Optional[bool] = None, delta_window_size: Optional[int] = None, ofs_delta: bool = True, progress=None, ) -> tuple[int, Iterator[UnpackedObject]]: """Create pack data from objects. Args: objects: Pack objects Returns: Tuples with (type_num, hexdigest, delta base, object chunks) """ # TODO(jelmer): support deltaifying count = len(objects) if deltify is None: # PERFORMANCE/TODO(jelmer): This should be enabled but is *much* too # slow at the moment. deltify = False if deltify: return ( count, deltify_pack_objects( iter(objects), # type: ignore window_size=delta_window_size, progress=progress, ), ) else: def iter_without_path(): for o in objects: if isinstance(o, tuple): yield full_unpacked_object(o[0]) else: yield full_unpacked_object(o) return (count, iter_without_path()) def generate_unpacked_objects( container: PackedObjectContainer, object_ids: Sequence[tuple[ObjectID, Optional[PackHint]]], delta_window_size: Optional[int] = None, deltify: Optional[bool] = None, reuse_deltas: bool = True, ofs_delta: bool = True, other_haves: Optional[set[bytes]] = None, progress=None, ) -> Iterator[UnpackedObject]: """Create pack data from objects. Args: objects: Pack objects Returns: Tuples with (type_num, hexdigest, delta base, object chunks) """ todo = dict(object_ids) if reuse_deltas: for unpack in find_reusable_deltas( container, set(todo), other_haves=other_haves, progress=progress ): del todo[sha_to_hex(unpack.sha())] yield unpack if deltify is None: # PERFORMANCE/TODO(jelmer): This should be enabled but is *much* too # slow at the moment. deltify = False if deltify: objects_to_delta = container.iterobjects_subset( todo.keys(), allow_missing=False ) yield from deltas_from_sorted_objects( sort_objects_for_delta((o, todo[o.id]) for o in objects_to_delta), window_size=delta_window_size, progress=progress, ) else: for oid in todo: yield full_unpacked_object(container[oid]) def full_unpacked_object(o: ShaFile) -> UnpackedObject: return UnpackedObject( o.type_num, delta_base=None, crc32=None, decomp_chunks=o.as_raw_chunks(), sha=o.sha().digest(), ) def write_pack_from_container( write, container: PackedObjectContainer, object_ids: Sequence[tuple[ObjectID, Optional[PackHint]]], delta_window_size: Optional[int] = None, deltify: Optional[bool] = None, reuse_deltas: bool = True, compression_level: int = -1, other_haves: Optional[set[bytes]] = None, ): """Write a new pack data file. Args: write: write function to use container: PackedObjectContainer entries: Sequence of (object_id, path) tuples to write delta_window_size: Sliding window size for searching for deltas; Set to None for default window size. deltify: Whether to deltify objects compression_level: the zlib compression level to use Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum """ pack_contents_count = len(object_ids) pack_contents = generate_unpacked_objects( container, object_ids, delta_window_size=delta_window_size, deltify=deltify, reuse_deltas=reuse_deltas, other_haves=other_haves, ) return write_pack_data( write, pack_contents, num_records=pack_contents_count, compression_level=compression_level, ) def write_pack_objects( write, objects: Union[Sequence[ShaFile], Sequence[tuple[ShaFile, Optional[bytes]]]], *, delta_window_size: Optional[int] = None, deltify: Optional[bool] = None, compression_level: int = -1, ): """Write a new pack data file. Args: write: write function to use objects: Sequence of (object, path) tuples to write delta_window_size: Sliding window size for searching for deltas; Set to None for default window size. deltify: Whether to deltify objects compression_level: the zlib compression level to use Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum """ pack_contents_count, pack_contents = pack_objects_to_data(objects, deltify=deltify) return write_pack_data( write, pack_contents, num_records=pack_contents_count, compression_level=compression_level, ) class PackChunkGenerator: def __init__( self, num_records=None, records=None, progress=None, compression_level=-1, reuse_compressed=True, ) -> None: self.cs = sha1(b"") self.entries: dict[Union[int, bytes], tuple[int, int]] = {} self._it = self._pack_data_chunks( num_records=num_records, records=records, progress=progress, compression_level=compression_level, reuse_compressed=reuse_compressed, ) def sha1digest(self): return self.cs.digest() def __iter__(self): return self._it def _pack_data_chunks( self, records: Iterator[UnpackedObject], *, num_records=None, progress=None, compression_level: int = -1, reuse_compressed: bool = True, ) -> Iterator[bytes]: """Iterate pack data file chunks. Args: records: Iterator over UnpackedObject num_records: Number of records (defaults to len(records) if not specified) progress: Function to report progress to compression_level: the zlib compression level Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum """ # Write the pack if num_records is None: num_records = len(records) # type: ignore offset = 0 for chunk in pack_header_chunks(num_records): yield chunk self.cs.update(chunk) offset += len(chunk) actual_num_records = 0 for i, unpacked in enumerate(records): type_num = unpacked.pack_type_num if progress is not None and i % 1000 == 0: progress((f"writing pack data: {i}/{num_records}\r").encode("ascii")) raw: Union[list[bytes], tuple[int, list[bytes]], tuple[bytes, list[bytes]]] if unpacked.delta_base is not None: try: base_offset, base_crc32 = self.entries[unpacked.delta_base] except KeyError: type_num = REF_DELTA assert isinstance(unpacked.delta_base, bytes) raw = (unpacked.delta_base, unpacked.decomp_chunks) else: type_num = OFS_DELTA raw = (offset - base_offset, unpacked.decomp_chunks) else: raw = unpacked.decomp_chunks if unpacked.comp_chunks is not None and reuse_compressed: chunks = unpacked.comp_chunks else: chunks = pack_object_chunks( type_num, raw, compression_level=compression_level ) crc32 = 0 object_size = 0 for chunk in chunks: yield chunk crc32 = binascii.crc32(chunk, crc32) self.cs.update(chunk) object_size += len(chunk) actual_num_records += 1 self.entries[unpacked.sha()] = (offset, crc32) offset += object_size if actual_num_records != num_records: raise AssertionError( f"actual records written differs: {actual_num_records} != {num_records}" ) yield self.cs.digest() def write_pack_data( write, records: Iterator[UnpackedObject], *, num_records=None, progress=None, compression_level=-1, ): """Write a new pack data file. Args: write: Write function to use num_records: Number of records (defaults to len(records) if None) records: Iterator over type_num, object_id, delta_base, raw progress: Function to report progress to compression_level: the zlib compression level Returns: Dict mapping id -> (offset, crc32 checksum), pack checksum """ chunk_generator = PackChunkGenerator( num_records=num_records, records=records, progress=progress, compression_level=compression_level, ) for chunk in chunk_generator: write(chunk) return chunk_generator.entries, chunk_generator.sha1digest() def write_pack_index_v1(f, entries, pack_checksum): """Write a new pack index file. Args: f: A file-like object to write to entries: List of tuples with object name (sha), offset_in_pack, and crc32_checksum. pack_checksum: Checksum of the pack file. Returns: The SHA of the written index file """ f = SHA1Writer(f) fan_out_table = defaultdict(lambda: 0) for name, offset, entry_checksum in entries: fan_out_table[ord(name[:1])] += 1 # Fan-out table for i in range(0x100): f.write(struct.pack(">L", fan_out_table[i])) fan_out_table[i + 1] += fan_out_table[i] for name, offset, entry_checksum in entries: if not (offset <= 0xFFFFFFFF): raise TypeError("pack format 1 only supports offsets < 2Gb") f.write(struct.pack(">L20s", offset, name)) assert len(pack_checksum) == 20 f.write(pack_checksum) return f.write_sha() def _delta_encode_size(size) -> bytes: ret = bytearray() c = size & 0x7F size >>= 7 while size: ret.append(c | 0x80) c = size & 0x7F size >>= 7 ret.append(c) return bytes(ret) # The length of delta compression copy operations in version 2 packs is limited # to 64K. To copy more, we use several copy operations. Version 3 packs allow # 24-bit lengths in copy operations, but we always make version 2 packs. _MAX_COPY_LEN = 0xFFFF def _encode_copy_operation(start, length): scratch = bytearray([0x80]) for i in range(4): if start & 0xFF << i * 8: scratch.append((start >> i * 8) & 0xFF) scratch[0] |= 1 << i for i in range(2): if length & 0xFF << i * 8: scratch.append((length >> i * 8) & 0xFF) scratch[0] |= 1 << (4 + i) return bytes(scratch) def create_delta(base_buf, target_buf): """Use python difflib to work out how to transform base_buf to target_buf. Args: base_buf: Base buffer target_buf: Target buffer """ if isinstance(base_buf, list): base_buf = b"".join(base_buf) if isinstance(target_buf, list): target_buf = b"".join(target_buf) assert isinstance(base_buf, bytes) assert isinstance(target_buf, bytes) # write delta header yield _delta_encode_size(len(base_buf)) yield _delta_encode_size(len(target_buf)) # write out delta opcodes seq = SequenceMatcher(isjunk=None, a=base_buf, b=target_buf) for opcode, i1, i2, j1, j2 in seq.get_opcodes(): # Git patch opcodes don't care about deletes! # if opcode == 'replace' or opcode == 'delete': # pass if opcode == "equal": # If they are equal, unpacker will use data from base_buf # Write out an opcode that says what range to use copy_start = i1 copy_len = i2 - i1 while copy_len > 0: to_copy = min(copy_len, _MAX_COPY_LEN) yield _encode_copy_operation(copy_start, to_copy) copy_start += to_copy copy_len -= to_copy if opcode == "replace" or opcode == "insert": # If we are replacing a range or adding one, then we just # output it to the stream (prefixed by its size) s = j2 - j1 o = j1 while s > 127: yield bytes([127]) yield memoryview(target_buf)[o : o + 127] s -= 127 o += 127 yield bytes([s]) yield memoryview(target_buf)[o : o + s] def apply_delta(src_buf, delta): """Based on the similar function in git's patch-delta.c. Args: src_buf: Source buffer delta: Delta instructions """ if not isinstance(src_buf, bytes): src_buf = b"".join(src_buf) if not isinstance(delta, bytes): delta = b"".join(delta) out = [] index = 0 delta_length = len(delta) def get_delta_header_size(delta, index): size = 0 i = 0 while delta: cmd = ord(delta[index : index + 1]) index += 1 size |= (cmd & ~0x80) << i i += 7 if not cmd & 0x80: break return size, index src_size, index = get_delta_header_size(delta, index) dest_size, index = get_delta_header_size(delta, index) assert src_size == len(src_buf), f"{src_size} vs {len(src_buf)}" while index < delta_length: cmd = ord(delta[index : index + 1]) index += 1 if cmd & 0x80: cp_off = 0 for i in range(4): if cmd & (1 << i): x = ord(delta[index : index + 1]) index += 1 cp_off |= x << (i * 8) cp_size = 0 # Version 3 packs can contain copy sizes larger than 64K. for i in range(3): if cmd & (1 << (4 + i)): x = ord(delta[index : index + 1]) index += 1 cp_size |= x << (i * 8) if cp_size == 0: cp_size = 0x10000 if ( cp_off + cp_size < cp_size or cp_off + cp_size > src_size or cp_size > dest_size ): break out.append(src_buf[cp_off : cp_off + cp_size]) elif cmd != 0: out.append(delta[index : index + cmd]) index += cmd else: raise ApplyDeltaError("Invalid opcode 0") if index != delta_length: raise ApplyDeltaError(f"delta not empty: {delta[index:]!r}") if dest_size != chunks_length(out): raise ApplyDeltaError("dest size incorrect") return out def write_pack_index_v2( f, entries: Iterable[PackIndexEntry], pack_checksum: bytes ) -> bytes: """Write a new pack index file. Args: f: File-like object to write to entries: List of tuples with object name (sha), offset_in_pack, and crc32_checksum. pack_checksum: Checksum of the pack file. Returns: The SHA of the index file written """ f = SHA1Writer(f) f.write(b"\377tOc") # Magic! f.write(struct.pack(">L", 2)) fan_out_table: dict[int, int] = defaultdict(lambda: 0) for name, offset, entry_checksum in entries: fan_out_table[ord(name[:1])] += 1 # Fan-out table largetable: list[int] = [] for i in range(0x100): f.write(struct.pack(b">L", fan_out_table[i])) fan_out_table[i + 1] += fan_out_table[i] for name, offset, entry_checksum in entries: f.write(name) for name, offset, entry_checksum in entries: f.write(struct.pack(b">L", entry_checksum)) for name, offset, entry_checksum in entries: if offset < 2**31: f.write(struct.pack(b">L", offset)) else: f.write(struct.pack(b">L", 2**31 + len(largetable))) largetable.append(offset) for offset in largetable: f.write(struct.pack(b">Q", offset)) assert len(pack_checksum) == 20 f.write(pack_checksum) return f.write_sha() write_pack_index = write_pack_index_v2 class Pack: """A Git pack object.""" _data_load: Optional[Callable[[], PackData]] _idx_load: Optional[Callable[[], PackIndex]] _data: Optional[PackData] _idx: Optional[PackIndex] def __init__( self, basename, resolve_ext_ref: Optional[ResolveExtRefFn] = None ) -> None: self._basename = basename self._data = None self._idx = None self._idx_path = self._basename + ".idx" self._data_path = self._basename + ".pack" self._data_load = lambda: PackData(self._data_path) self._idx_load = lambda: load_pack_index(self._idx_path) self.resolve_ext_ref = resolve_ext_ref @classmethod def from_lazy_objects(cls, data_fn, idx_fn): """Create a new pack object from callables to load pack data and index objects. """ ret = cls("") ret._data_load = data_fn ret._idx_load = idx_fn return ret @classmethod def from_objects(cls, data, idx): """Create a new pack object from pack data and index objects.""" ret = cls("") ret._data = data ret._data_load = None ret._idx = idx ret._idx_load = None ret.check_length_and_checksum() return ret def name(self): """The SHA over the SHAs of the objects in this pack.""" return self.index.objects_sha1() @property def data(self) -> PackData: """The pack data object being used.""" if self._data is None: assert self._data_load self._data = self._data_load() self.check_length_and_checksum() return self._data @property def index(self) -> PackIndex: """The index being used. Note: This may be an in-memory index """ if self._idx is None: assert self._idx_load self._idx = self._idx_load() return self._idx def close(self) -> None: if self._data is not None: self._data.close() if self._idx is not None: self._idx.close() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def __eq__(self, other): return isinstance(self, type(other)) and self.index == other.index def __len__(self) -> int: """Number of entries in this pack.""" return len(self.index) def __repr__(self) -> str: return f"{self.__class__.__name__}({self._basename!r})" def __iter__(self): """Iterate over all the sha1s of the objects in this pack.""" return iter(self.index) def check_length_and_checksum(self) -> None: """Sanity check the length and checksum of the pack index and data.""" assert len(self.index) == len( self.data ), f"Length mismatch: {len(self.index)} (index) != {len(self.data)} (data)" idx_stored_checksum = self.index.get_pack_checksum() data_stored_checksum = self.data.get_stored_checksum() if idx_stored_checksum != data_stored_checksum: raise ChecksumMismatch( sha_to_hex(idx_stored_checksum), sha_to_hex(data_stored_checksum), ) def check(self) -> None: """Check the integrity of this pack. Raises: ChecksumMismatch: if a checksum for the index or data is wrong """ self.index.check() self.data.check() for obj in self.iterobjects(): obj.check() # TODO: object connectivity checks def get_stored_checksum(self) -> bytes: return self.data.get_stored_checksum() def pack_tuples(self): return [(o, None) for o in self.iterobjects()] def __contains__(self, sha1: bytes) -> bool: """Check whether this pack contains a particular SHA1.""" try: self.index.object_offset(sha1) return True except KeyError: return False def get_raw(self, sha1: bytes) -> tuple[int, bytes]: offset = self.index.object_offset(sha1) obj_type, obj = self.data.get_object_at(offset) type_num, chunks = self.resolve_object(offset, obj_type, obj) return type_num, b"".join(chunks) def __getitem__(self, sha1: bytes) -> ShaFile: """Retrieve the specified SHA1.""" type, uncomp = self.get_raw(sha1) return ShaFile.from_raw_string(type, uncomp, sha=sha1) def iterobjects(self) -> Iterator[ShaFile]: """Iterate over the objects in this pack.""" return iter( PackInflater.for_pack_data(self.data, resolve_ext_ref=self.resolve_ext_ref) ) def iterobjects_subset( self, shas: Iterable[ObjectID], *, allow_missing: bool = False ) -> Iterator[ShaFile]: return ( uo for uo in PackInflater.for_pack_subset( self, shas, allow_missing=allow_missing, resolve_ext_ref=self.resolve_ext_ref, ) if uo.id in shas ) def iter_unpacked_subset( self, shas: Iterable[ObjectID], *, include_comp: bool = False, allow_missing: bool = False, convert_ofs_delta: bool = False, ) -> Iterator[UnpackedObject]: ofs_pending: dict[int, list[UnpackedObject]] = defaultdict(list) ofs: dict[bytes, int] = {} todo = set(shas) for unpacked in self.iter_unpacked(include_comp=include_comp): sha = unpacked.sha() ofs[unpacked.offset] = sha hexsha = sha_to_hex(sha) if hexsha in todo: if unpacked.pack_type_num == OFS_DELTA: assert isinstance(unpacked.delta_base, int) base_offset = unpacked.offset - unpacked.delta_base try: unpacked.delta_base = ofs[base_offset] except KeyError: ofs_pending[base_offset].append(unpacked) continue else: unpacked.pack_type_num = REF_DELTA yield unpacked todo.remove(hexsha) for child in ofs_pending.pop(unpacked.offset, []): child.pack_type_num = REF_DELTA child.delta_base = sha yield child assert not ofs_pending if not allow_missing and todo: raise UnresolvedDeltas(todo) def iter_unpacked(self, include_comp=False): ofs_to_entries = { ofs: (sha, crc32) for (sha, ofs, crc32) in self.index.iterentries() } for unpacked in self.data.iter_unpacked(include_comp=include_comp): (sha, crc32) = ofs_to_entries[unpacked.offset] unpacked._sha = sha unpacked.crc32 = crc32 yield unpacked def keep(self, msg: Optional[bytes] = None) -> str: """Add a .keep file for the pack, preventing git from garbage collecting it. Args: msg: A message written inside the .keep file; can be used later to determine whether or not a .keep file is obsolete. Returns: The path of the .keep file, as a string. """ keepfile_name = f"{self._basename}.keep" with GitFile(keepfile_name, "wb") as keepfile: if msg: keepfile.write(msg) keepfile.write(b"\n") return keepfile_name def get_ref(self, sha: bytes) -> tuple[Optional[int], int, OldUnpackedObject]: """Get the object for a ref SHA, only looking in this pack.""" # TODO: cache these results try: offset = self.index.object_offset(sha) except KeyError: offset = None if offset: type, obj = self.data.get_object_at(offset) elif self.resolve_ext_ref: type, obj = self.resolve_ext_ref(sha) else: raise KeyError(sha) return offset, type, obj def resolve_object( self, offset: int, type: int, obj, get_ref=None ) -> tuple[int, Iterable[bytes]]: """Resolve an object, possibly resolving deltas when necessary. Returns: Tuple with object type and contents. """ # Walk down the delta chain, building a stack of deltas to reach # the requested object. base_offset = offset base_type = type base_obj = obj delta_stack = [] while base_type in DELTA_TYPES: prev_offset = base_offset if get_ref is None: get_ref = self.get_ref if base_type == OFS_DELTA: (delta_offset, delta) = base_obj # TODO: clean up asserts and replace with nicer error messages base_offset = base_offset - delta_offset base_type, base_obj = self.data.get_object_at(base_offset) assert isinstance(base_type, int) elif base_type == REF_DELTA: (basename, delta) = base_obj assert isinstance(basename, bytes) and len(basename) == 20 base_offset, base_type, base_obj = get_ref(basename) assert isinstance(base_type, int) if base_offset == prev_offset: # object is based on itself raise UnresolvedDeltas(sha_to_hex(basename)) delta_stack.append((prev_offset, base_type, delta)) # Now grab the base object (mustn't be a delta) and apply the # deltas all the way up the stack. chunks = base_obj for prev_offset, delta_type, delta in reversed(delta_stack): chunks = apply_delta(chunks, delta) # TODO(dborowitz): This can result in poor performance if # large base objects are separated from deltas in the pack. # We should reorganize so that we apply deltas to all # objects in a chain one after the other to optimize cache # performance. if prev_offset is not None: self.data._offset_cache[prev_offset] = base_type, chunks return base_type, chunks def entries( self, progress: Optional[ProgressFn] = None ) -> Iterator[PackIndexEntry]: """Yield entries summarizing the contents of this pack. Args: progress: Progress function, called with current and total object count. Returns: iterator of tuples with (sha, offset, crc32) """ return self.data.iterentries( progress=progress, resolve_ext_ref=self.resolve_ext_ref ) def sorted_entries( self, progress: Optional[ProgressFn] = None ) -> Iterator[PackIndexEntry]: """Return entries in this pack, sorted by SHA. Args: progress: Progress function, called with current and total object count Returns: Iterator of tuples with (sha, offset, crc32) """ return self.data.sorted_entries( progress=progress, resolve_ext_ref=self.resolve_ext_ref ) def get_unpacked_object( self, sha: bytes, *, include_comp: bool = False, convert_ofs_delta: bool = True ) -> UnpackedObject: """Get the unpacked object for a sha. Args: sha: SHA of object to fetch include_comp: Whether to include compression data in UnpackedObject """ offset = self.index.object_offset(sha) unpacked = self.data.get_unpacked_object_at(offset, include_comp=include_comp) if unpacked.pack_type_num == OFS_DELTA and convert_ofs_delta: assert isinstance(unpacked.delta_base, int) unpacked.delta_base = self.index.object_sha1(offset - unpacked.delta_base) unpacked.pack_type_num = REF_DELTA return unpacked def extend_pack( f: BinaryIO, object_ids: set[ObjectID], get_raw, *, compression_level=-1, progress=None, ) -> tuple[bytes, list]: """Extend a pack file with more objects. The caller should make sure that object_ids does not contain any objects that are already in the pack """ # Update the header with the new number of objects. f.seek(0) _version, num_objects = read_pack_header(f.read) if object_ids: f.seek(0) write_pack_header(f.write, num_objects + len(object_ids)) # Must flush before reading (http://bugs.python.org/issue3207) f.flush() # Rescan the rest of the pack, computing the SHA with the new header. new_sha = compute_file_sha(f, end_ofs=-20) # Must reposition before writing (http://bugs.python.org/issue3207) f.seek(0, os.SEEK_CUR) extra_entries = [] # Complete the pack. for i, object_id in enumerate(object_ids): if progress is not None: progress( (f"writing extra base objects: {i}/{len(object_ids)}\r").encode("ascii") ) assert len(object_id) == 20 type_num, data = get_raw(object_id) offset = f.tell() crc32 = write_pack_object( f.write, type_num, data, sha=new_sha, compression_level=compression_level, ) extra_entries.append((object_id, offset, crc32)) pack_sha = new_sha.digest() f.write(pack_sha) return pack_sha, extra_entries try: from dulwich._pack import ( # type: ignore apply_delta, # type: ignore bisect_find_sha, # type: ignore ) except ImportError: pass ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/patch.py0000644000175100002000000003057614731042555015762 0ustar00runnerdocker# patch.py -- For dealing with packed-style patches. # Copyright (C) 2009-2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Classes for dealing with git am-style patches. These patches are basically unified diffs with some extra metadata tacked on. """ import email.parser import time from difflib import SequenceMatcher from typing import BinaryIO, Optional, TextIO, Union from .objects import S_ISGITLINK, Blob, Commit from .pack import ObjectContainer FIRST_FEW_BYTES = 8000 def write_commit_patch( f, commit, contents, progress, version=None, encoding=None ) -> None: """Write a individual file patch. Args: commit: Commit object progress: Tuple with current patch number and total. Returns: tuple with filename and contents """ encoding = encoding or getattr(f, "encoding", "ascii") if isinstance(contents, str): contents = contents.encode(encoding) (num, total) = progress f.write( b"From " + commit.id + b" " + time.ctime(commit.commit_time).encode(encoding) + b"\n" ) f.write(b"From: " + commit.author + b"\n") f.write( b"Date: " + time.strftime("%a, %d %b %Y %H:%M:%S %Z").encode(encoding) + b"\n" ) f.write( (f"Subject: [PATCH {num}/{total}] ").encode(encoding) + commit.message + b"\n" ) f.write(b"\n") f.write(b"---\n") try: import subprocess p = subprocess.Popen( ["diffstat"], stdout=subprocess.PIPE, stdin=subprocess.PIPE ) except (ImportError, OSError): pass # diffstat not available? else: (diffstat, _) = p.communicate(contents) f.write(diffstat) f.write(b"\n") f.write(contents) f.write(b"-- \n") if version is None: from dulwich import __version__ as dulwich_version f.write(b"Dulwich %d.%d.%d\n" % dulwich_version) else: f.write(version.encode(encoding) + b"\n") def get_summary(commit): """Determine the summary line for use in a filename. Args: commit: Commit Returns: Summary string """ decoded = commit.message.decode(errors="replace") return decoded.splitlines()[0].replace(" ", "-") # Unified Diff def _format_range_unified(start, stop) -> str: """Convert range to the "ed" format.""" # Per the diff spec at http://www.unix.org/single_unix_specification/ beginning = start + 1 # lines start numbering with one length = stop - start if length == 1: return f"{beginning}" if not length: beginning -= 1 # empty ranges begin at line just before the range return f"{beginning},{length}" def unified_diff( a, b, fromfile="", tofile="", fromfiledate="", tofiledate="", n=3, lineterm="\n", tree_encoding="utf-8", output_encoding="utf-8", ): """difflib.unified_diff that can detect "No newline at end of file" as original "git diff" does. Based on the same function in Python2.7 difflib.py """ started = False for group in SequenceMatcher(None, a, b).get_grouped_opcodes(n): if not started: started = True fromdate = f"\t{fromfiledate}" if fromfiledate else "" todate = f"\t{tofiledate}" if tofiledate else "" yield f"--- {fromfile.decode(tree_encoding)}{fromdate}{lineterm}".encode( output_encoding ) yield f"+++ {tofile.decode(tree_encoding)}{todate}{lineterm}".encode( output_encoding ) first, last = group[0], group[-1] file1_range = _format_range_unified(first[1], last[2]) file2_range = _format_range_unified(first[3], last[4]) yield f"@@ -{file1_range} +{file2_range} @@{lineterm}".encode(output_encoding) for tag, i1, i2, j1, j2 in group: if tag == "equal": for line in a[i1:i2]: yield b" " + line continue if tag in ("replace", "delete"): for line in a[i1:i2]: if not line[-1:] == b"\n": line += b"\n\\ No newline at end of file\n" yield b"-" + line if tag in ("replace", "insert"): for line in b[j1:j2]: if not line[-1:] == b"\n": line += b"\n\\ No newline at end of file\n" yield b"+" + line def is_binary(content): """See if the first few bytes contain any null characters. Args: content: Bytestring to check for binary content """ return b"\0" in content[:FIRST_FEW_BYTES] def shortid(hexsha): if hexsha is None: return b"0" * 7 else: return hexsha[:7] def patch_filename(p, root): if p is None: return b"/dev/null" else: return root + b"/" + p def write_object_diff( f, store: ObjectContainer, old_file, new_file, diff_binary=False ) -> None: """Write the diff for an object. Args: f: File-like object to write to store: Store to retrieve objects from, if necessary old_file: (path, mode, hexsha) tuple new_file: (path, mode, hexsha) tuple diff_binary: Whether to diff files even if they are considered binary files by is_binary(). Note: the tuple elements should be None for nonexistent files """ (old_path, old_mode, old_id) = old_file (new_path, new_mode, new_id) = new_file patched_old_path = patch_filename(old_path, b"a") patched_new_path = patch_filename(new_path, b"b") def content(mode, hexsha): if hexsha is None: return Blob.from_string(b"") elif S_ISGITLINK(mode): return Blob.from_string(b"Subproject commit " + hexsha + b"\n") else: return store[hexsha] def lines(content): if not content: return [] else: return content.splitlines() f.writelines( gen_diff_header((old_path, new_path), (old_mode, new_mode), (old_id, new_id)) ) old_content = content(old_mode, old_id) new_content = content(new_mode, new_id) if not diff_binary and (is_binary(old_content.data) or is_binary(new_content.data)): binary_diff = ( b"Binary files " + patched_old_path + b" and " + patched_new_path + b" differ\n" ) f.write(binary_diff) else: f.writelines( unified_diff( lines(old_content), lines(new_content), patched_old_path, patched_new_path, ) ) # TODO(jelmer): Support writing unicode, rather than bytes. def gen_diff_header(paths, modes, shas): """Write a blob diff header. Args: paths: Tuple with old and new path modes: Tuple with old and new modes shas: Tuple with old and new shas """ (old_path, new_path) = paths (old_mode, new_mode) = modes (old_sha, new_sha) = shas if old_path is None and new_path is not None: old_path = new_path if new_path is None and old_path is not None: new_path = old_path old_path = patch_filename(old_path, b"a") new_path = patch_filename(new_path, b"b") yield b"diff --git " + old_path + b" " + new_path + b"\n" if old_mode != new_mode: if new_mode is not None: if old_mode is not None: yield (f"old file mode {old_mode:o}\n").encode("ascii") yield (f"new file mode {new_mode:o}\n").encode("ascii") else: yield (f"deleted file mode {old_mode:o}\n").encode("ascii") yield b"index " + shortid(old_sha) + b".." + shortid(new_sha) if new_mode is not None and old_mode is not None: yield (f" {new_mode:o}").encode("ascii") yield b"\n" # TODO(jelmer): Support writing unicode, rather than bytes. def write_blob_diff(f, old_file, new_file) -> None: """Write blob diff. Args: f: File-like object to write to old_file: (path, mode, hexsha) tuple (None if nonexisting) new_file: (path, mode, hexsha) tuple (None if nonexisting) Note: The use of write_object_diff is recommended over this function. """ (old_path, old_mode, old_blob) = old_file (new_path, new_mode, new_blob) = new_file patched_old_path = patch_filename(old_path, b"a") patched_new_path = patch_filename(new_path, b"b") def lines(blob): if blob is not None: return blob.splitlines() else: return [] f.writelines( gen_diff_header( (old_path, new_path), (old_mode, new_mode), (getattr(old_blob, "id", None), getattr(new_blob, "id", None)), ) ) old_contents = lines(old_blob) new_contents = lines(new_blob) f.writelines( unified_diff(old_contents, new_contents, patched_old_path, patched_new_path) ) def write_tree_diff(f, store, old_tree, new_tree, diff_binary=False) -> None: """Write tree diff. Args: f: File-like object to write to. old_tree: Old tree id new_tree: New tree id diff_binary: Whether to diff files even if they are considered binary files by is_binary(). """ changes = store.tree_changes(old_tree, new_tree) for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes: write_object_diff( f, store, (oldpath, oldmode, oldsha), (newpath, newmode, newsha), diff_binary=diff_binary, ) def git_am_patch_split(f: Union[TextIO, BinaryIO], encoding: Optional[str] = None): """Parse a git-am-style patch and split it up into bits. Args: f: File-like object to parse encoding: Encoding to use when creating Git objects Returns: Tuple with commit object, diff contents and git version """ encoding = encoding or getattr(f, "encoding", "ascii") encoding = encoding or "ascii" contents = f.read() if isinstance(contents, bytes): bparser = email.parser.BytesParser() msg = bparser.parsebytes(contents) else: uparser = email.parser.Parser() msg = uparser.parsestr(contents) return parse_patch_message(msg, encoding) def parse_patch_message(msg, encoding=None): """Extract a Commit object and patch from an e-mail message. Args: msg: An email message (email.message.Message) encoding: Encoding to use to encode Git commits Returns: Tuple with commit object, diff contents and git version """ c = Commit() c.author = msg["from"].encode(encoding) c.committer = msg["from"].encode(encoding) try: patch_tag_start = msg["subject"].index("[PATCH") except ValueError: subject = msg["subject"] else: close = msg["subject"].index("] ", patch_tag_start) subject = msg["subject"][close + 2 :] c.message = (subject.replace("\n", "") + "\n").encode(encoding) first = True body = msg.get_payload(decode=True) lines = body.splitlines(True) line_iter = iter(lines) for line in line_iter: if line == b"---\n": break if first: if line.startswith(b"From: "): c.author = line[len(b"From: ") :].rstrip() else: c.message += b"\n" + line first = False else: c.message += line diff = b"" for line in line_iter: if line == b"-- \n": break diff += line try: version = next(line_iter).rstrip(b"\n") except StopIteration: version = None return c, diff, version ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/porcelain.py0000644000175100002000000021304214731042555016626 0ustar00runnerdocker# porcelain.py -- Porcelain-like layer on top of Dulwich # Copyright (C) 2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Simple wrapper that provides porcelain-like functions on top of Dulwich. Currently implemented: * archive * add * branch{_create,_delete,_list} * check-ignore * checkout_branch * clone * commit * commit-tree * daemon * describe * diff-tree * fetch * for-each-ref * init * ls-files * ls-remote * ls-tree * pull * push * rm * remote{_add} * receive-pack * reset * submodule_add * submodule_init * submodule_list * rev-list * tag{_create,_delete,_list} * upload-pack * update-server-info * status * symbolic-ref These functions are meant to behave similarly to the git subcommands. Differences in behaviour are considered bugs. Note: one of the consequences of this is that paths tend to be interpreted relative to the current working directory rather than relative to the repository root. Functions should generally accept both unicode strings and bytestrings """ import datetime import fnmatch import os import posixpath import stat import sys import time from collections import namedtuple from contextlib import closing, contextmanager from io import BytesIO, RawIOBase from pathlib import Path from typing import Optional, Union from .archive import tar_stream from .client import get_transport_and_path from .config import Config, ConfigFile, StackedConfig, read_submodules from .diff_tree import ( CHANGE_ADD, CHANGE_COPY, CHANGE_DELETE, CHANGE_MODIFY, CHANGE_RENAME, RENAME_CHANGE_TYPES, ) from .errors import SendPackError from .file import ensure_dir_exists from .graph import can_fast_forward from .ignore import IgnoreFilterManager from .index import ( _fs_to_tree_path, blob_from_path_and_stat, build_file_from_blob, get_unstaged_changes, index_entry_from_stat, ) from .object_store import iter_tree_contents, tree_lookup_path from .objects import ( Commit, Tag, format_timezone, parse_timezone, pretty_format_tree_entry, ) from .objectspec import ( parse_commit, parse_object, parse_ref, parse_reftuples, parse_tree, to_bytes, ) from .pack import write_pack_from_container, write_pack_index from .patch import write_tree_diff from .protocol import ZERO_SHA, Protocol from .refs import ( LOCAL_BRANCH_PREFIX, LOCAL_REMOTE_PREFIX, LOCAL_TAG_PREFIX, _import_remote_refs, ) from .repo import BaseRepo, Repo, get_user_identity from .server import ( FileSystemBackend, ReceivePackHandler, TCPGitServer, UploadPackHandler, ) from .server import update_server_info as server_update_server_info # Module level tuple definition for status output GitStatus = namedtuple("GitStatus", "staged unstaged untracked") class NoneStream(RawIOBase): """Fallback if stdout or stderr are unavailable, does nothing.""" def read(self, size=-1) -> None: return None def readall(self) -> bytes: return b"" def readinto(self, b) -> None: return None def write(self, b) -> None: return None default_bytes_out_stream = getattr(sys.stdout, "buffer", None) or NoneStream() default_bytes_err_stream = getattr(sys.stderr, "buffer", None) or NoneStream() DEFAULT_ENCODING = "utf-8" class Error(Exception): """Porcelain-based error.""" def __init__(self, msg) -> None: super().__init__(msg) class RemoteExists(Error): """Raised when the remote already exists.""" class TimezoneFormatError(Error): """Raised when the timezone cannot be determined from a given string.""" class CheckoutError(Error): """Indicates that a checkout cannot be performed.""" def parse_timezone_format(tz_str): """Parse given string and attempt to return a timezone offset. Different formats are considered in the following order: - Git internal format: - RFC 2822: e.g. Mon, 20 Nov 1995 19:12:08 -0500 - ISO 8601: e.g. 1995-11-20T19:12:08-0500 Args: tz_str: datetime string Returns: Timezone offset as integer Raises: TimezoneFormatError: if timezone information cannot be extracted """ import re # Git internal format internal_format_pattern = re.compile("^[0-9]+ [+-][0-9]{,4}$") if re.match(internal_format_pattern, tz_str): try: tz_internal = parse_timezone(tz_str.split(" ")[1].encode(DEFAULT_ENCODING)) return tz_internal[0] except ValueError: pass # RFC 2822 import email.utils rfc_2822 = email.utils.parsedate_tz(tz_str) if rfc_2822: return rfc_2822[9] # ISO 8601 # Supported offsets: # sHHMM, sHH:MM, sHH iso_8601_pattern = re.compile( "[0-9] ?([+-])([0-9]{2})(?::(?=[0-9]{2}))?([0-9]{2})?$" ) match = re.search(iso_8601_pattern, tz_str) total_secs = 0 if match: sign, hours, minutes = match.groups() total_secs += int(hours) * 3600 if minutes: total_secs += int(minutes) * 60 total_secs = -total_secs if sign == "-" else total_secs return total_secs # YYYY.MM.DD, MM/DD/YYYY, DD.MM.YYYY contain no timezone information raise TimezoneFormatError(tz_str) def get_user_timezones(): """Retrieve local timezone as described in https://raw.githubusercontent.com/git/git/v2.3.0/Documentation/date-formats.txt Returns: A tuple containing author timezone, committer timezone. """ local_timezone = time.localtime().tm_gmtoff if os.environ.get("GIT_AUTHOR_DATE"): author_timezone = parse_timezone_format(os.environ["GIT_AUTHOR_DATE"]) else: author_timezone = local_timezone if os.environ.get("GIT_COMMITTER_DATE"): commit_timezone = parse_timezone_format(os.environ["GIT_COMMITTER_DATE"]) else: commit_timezone = local_timezone return author_timezone, commit_timezone def open_repo(path_or_repo): """Open an argument that can be a repository or a path for a repository.""" if isinstance(path_or_repo, BaseRepo): return path_or_repo return Repo(path_or_repo) @contextmanager def _noop_context_manager(obj): """Context manager that has the same api as closing but does nothing.""" yield obj def open_repo_closing(path_or_repo): """Open an argument that can be a repository or a path for a repository. returns a context manager that will close the repo on exit if the argument is a path, else does nothing if the argument is a repo. """ if isinstance(path_or_repo, BaseRepo): return _noop_context_manager(path_or_repo) return closing(Repo(path_or_repo)) def path_to_tree_path(repopath, path, tree_encoding=DEFAULT_ENCODING): """Convert a path to a path usable in an index, e.g. bytes and relative to the repository root. Args: repopath: Repository path, absolute or relative to the cwd path: A path, absolute or relative to the cwd Returns: A path formatted for use in e.g. an index """ # Resolve might returns a relative path on Windows # https://bugs.python.org/issue38671 if sys.platform == "win32": path = os.path.abspath(path) path = Path(path) resolved_path = path.resolve() # Resolve and abspath seems to behave differently regarding symlinks, # as we are doing abspath on the file path, we need to do the same on # the repo path or they might not match if sys.platform == "win32": repopath = os.path.abspath(repopath) repopath = Path(repopath).resolve() try: relpath = resolved_path.relative_to(repopath) except ValueError: # If path is a symlink that points to a file outside the repo, we # want the relpath for the link itself, not the resolved target if path.is_symlink(): parent = path.parent.resolve() relpath = (parent / path.name).relative_to(repopath) else: raise if sys.platform == "win32": return str(relpath).replace(os.path.sep, "/").encode(tree_encoding) else: return bytes(relpath) class DivergedBranches(Error): """Branches have diverged and fast-forward is not possible.""" def __init__(self, current_sha, new_sha) -> None: self.current_sha = current_sha self.new_sha = new_sha def check_diverged(repo, current_sha, new_sha) -> None: """Check if updating to a sha can be done with fast forwarding. Args: repo: Repository object current_sha: Current head sha new_sha: New head sha """ try: can = can_fast_forward(repo, current_sha, new_sha) except KeyError: can = False if not can: raise DivergedBranches(current_sha, new_sha) def archive( repo, committish=None, outstream=default_bytes_out_stream, errstream=default_bytes_err_stream, ) -> None: """Create an archive. Args: repo: Path of repository for which to generate an archive. committish: Commit SHA1 or ref to use outstream: Output stream (defaults to stdout) errstream: Error stream (defaults to stderr) """ if committish is None: committish = "HEAD" with open_repo_closing(repo) as repo_obj: c = parse_commit(repo_obj, committish) for chunk in tar_stream( repo_obj.object_store, repo_obj.object_store[c.tree], c.commit_time ): outstream.write(chunk) def update_server_info(repo=".") -> None: """Update server info files for a repository. Args: repo: path to the repository """ with open_repo_closing(repo) as r: server_update_server_info(r) def symbolic_ref(repo, ref_name, force=False) -> None: """Set git symbolic ref into HEAD. Args: repo: path to the repository ref_name: short name of the new ref force: force settings without checking if it exists in refs/heads """ with open_repo_closing(repo) as repo_obj: ref_path = _make_branch_ref(ref_name) if not force and ref_path not in repo_obj.refs.keys(): raise Error(f"fatal: ref `{ref_name}` is not a ref") repo_obj.refs.set_symbolic_ref(b"HEAD", ref_path) def pack_refs(repo, all=False) -> None: with open_repo_closing(repo) as repo_obj: refs = repo_obj.refs packed_refs = { ref: refs[ref] for ref in refs if (all or ref.startswith(LOCAL_TAG_PREFIX)) and ref != b"HEAD" } refs.add_packed_refs(packed_refs) def commit( repo=".", message=None, author=None, author_timezone=None, committer=None, commit_timezone=None, encoding=None, no_verify=False, signoff=False, ): """Create a new commit. Args: repo: Path to repository message: Optional commit message author: Optional author name and email author_timezone: Author timestamp timezone committer: Optional committer name and email commit_timezone: Commit timestamp timezone no_verify: Skip pre-commit and commit-msg hooks signoff: GPG Sign the commit (bool, defaults to False, pass True to use default GPG key, pass a str containing Key ID to use a specific GPG key) Returns: SHA1 of the new commit """ # FIXME: Support --all argument if getattr(message, "encode", None): message = message.encode(encoding or DEFAULT_ENCODING) if getattr(author, "encode", None): author = author.encode(encoding or DEFAULT_ENCODING) if getattr(committer, "encode", None): committer = committer.encode(encoding or DEFAULT_ENCODING) local_timezone = get_user_timezones() if author_timezone is None: author_timezone = local_timezone[0] if commit_timezone is None: commit_timezone = local_timezone[1] with open_repo_closing(repo) as r: return r.do_commit( message=message, author=author, author_timezone=author_timezone, committer=committer, commit_timezone=commit_timezone, encoding=encoding, no_verify=no_verify, sign=signoff if isinstance(signoff, (str, bool)) else None, ) def commit_tree(repo, tree, message=None, author=None, committer=None): """Create a new commit object. Args: repo: Path to repository tree: An existing tree object author: Optional author name and email committer: Optional committer name and email """ with open_repo_closing(repo) as r: return r.do_commit( message=message, tree=tree, committer=committer, author=author ) def init(path=".", *, bare=False, symlinks: Optional[bool] = None): """Create a new git repository. Args: path: Path to repository. bare: Whether to create a bare repository. symlinks: Whether to create actual symlinks (defaults to autodetect) Returns: A Repo instance """ if not os.path.exists(path): os.mkdir(path) if bare: return Repo.init_bare(path) else: return Repo.init(path, symlinks=symlinks) def clone( source, target=None, bare=False, checkout=None, errstream=default_bytes_err_stream, outstream=None, origin: Optional[str] = "origin", depth: Optional[int] = None, branch: Optional[Union[str, bytes]] = None, config: Optional[Config] = None, filter_spec=None, protocol_version: Optional[int] = None, **kwargs, ): """Clone a local or remote git repository. Args: source: Path or URL for source repository target: Path to target repository (optional) bare: Whether or not to create a bare repository checkout: Whether or not to check-out HEAD after cloning errstream: Optional stream to write progress to outstream: Optional stream to write progress to (deprecated) origin: Name of remote from the repository used to clone depth: Depth to fetch at branch: Optional branch or tag to be used as HEAD in the new repository instead of the cloned repository's HEAD. config: Configuration to use refspecs: refspecs to fetch. Can be a bytestring, a string, or a list of bytestring/string. filter_spec: A git-rev-list-style object filter spec, as an ASCII string. Only used if the server supports the Git protocol-v2 'filter' feature, and ignored otherwise. protocol_version: desired Git protocol version. By default the highest mutually supported protocol version will be used. Returns: The new repository """ if outstream is not None: import warnings warnings.warn( "outstream= has been deprecated in favour of errstream=.", DeprecationWarning, stacklevel=3, ) # TODO(jelmer): Capture logging output and stream to errstream if config is None: config = StackedConfig.default() if checkout is None: checkout = not bare if checkout and bare: raise Error("checkout and bare are incompatible") if target is None: target = source.split("/")[-1] if isinstance(branch, str): branch = branch.encode(DEFAULT_ENCODING) mkdir = not os.path.exists(target) (client, path) = get_transport_and_path(source, config=config, **kwargs) if filter_spec: filter_spec = filter_spec.encode("ascii") return client.clone( path, target, mkdir=mkdir, bare=bare, origin=origin, checkout=checkout, branch=branch, progress=errstream.write, depth=depth, filter_spec=filter_spec, protocol_version=protocol_version, ) def add(repo=".", paths=None): """Add files to the staging area. Args: repo: Repository for the files paths: Paths to add. No value passed stages all modified files. Returns: Tuple with set of added files and ignored files If the repository contains ignored directories, the returned set will contain the path to an ignored directory (with trailing slash). Individual files within ignored directories will not be returned. """ ignored = set() with open_repo_closing(repo) as r: repo_path = Path(r.path).resolve() ignore_manager = IgnoreFilterManager.from_repo(r) if not paths: paths = list( get_untracked_paths( str(Path(os.getcwd()).resolve()), str(repo_path), r.open_index(), ) ) relpaths = [] if not isinstance(paths, list): paths = [paths] for p in paths: path = Path(p) relpath = str(path.resolve().relative_to(repo_path)) # FIXME: Support patterns if path.is_dir(): relpath = os.path.join(relpath, "") if ignore_manager.is_ignored(relpath): ignored.add(relpath) continue relpaths.append(relpath) r.stage(relpaths) return (relpaths, ignored) def _is_subdir(subdir, parentdir): """Check whether subdir is parentdir or a subdir of parentdir. If parentdir or subdir is a relative path, it will be disamgibuated relative to the pwd. """ parentdir_abs = os.path.realpath(parentdir) + os.path.sep subdir_abs = os.path.realpath(subdir) + os.path.sep return subdir_abs.startswith(parentdir_abs) # TODO: option to remove ignored files also, in line with `git clean -fdx` def clean(repo=".", target_dir=None) -> None: """Remove any untracked files from the target directory recursively. Equivalent to running ``git clean -fd`` in target_dir. Args: repo: Repository where the files may be tracked target_dir: Directory to clean - current directory if None """ if target_dir is None: target_dir = os.getcwd() with open_repo_closing(repo) as r: if not _is_subdir(target_dir, r.path): raise Error("target_dir must be in the repo's working dir") config = r.get_config_stack() config.get_boolean((b"clean",), b"requireForce", True) # TODO(jelmer): if require_force is set, then make sure that -f, -i or # -n is specified. index = r.open_index() ignore_manager = IgnoreFilterManager.from_repo(r) paths_in_wd = _walk_working_dir_paths(target_dir, r.path) # Reverse file visit order, so that files and subdirectories are # removed before containing directory for ap, is_dir in reversed(list(paths_in_wd)): if is_dir: # All subdirectories and files have been removed if untracked, # so dir contains no tracked files iff it is empty. is_empty = len(os.listdir(ap)) == 0 if is_empty: os.rmdir(ap) else: ip = path_to_tree_path(r.path, ap) is_tracked = ip in index rp = os.path.relpath(ap, r.path) is_ignored = ignore_manager.is_ignored(rp) if not is_tracked and not is_ignored: os.remove(ap) def remove(repo=".", paths=None, cached=False) -> None: """Remove files from the staging area. Args: repo: Repository for the files paths: Paths to remove """ with open_repo_closing(repo) as r: index = r.open_index() for p in paths: full_path = os.fsencode(os.path.abspath(p)) tree_path = path_to_tree_path(r.path, p) try: index_sha = index[tree_path].sha except KeyError as exc: raise Error(f"{p} did not match any files") from exc if not cached: try: st = os.lstat(full_path) except OSError: pass else: try: blob = blob_from_path_and_stat(full_path, st) except OSError: pass else: try: committed_sha = tree_lookup_path( r.__getitem__, r[r.head()].tree, tree_path )[1] except KeyError: committed_sha = None if blob.id != index_sha and index_sha != committed_sha: raise Error( "file has staged content differing " f"from both the file and head: {p}" ) if index_sha != committed_sha: raise Error(f"file has staged changes: {p}") os.remove(full_path) del index[tree_path] index.write() rm = remove def commit_decode(commit, contents, default_encoding=DEFAULT_ENCODING): if commit.encoding: encoding = commit.encoding.decode("ascii") else: encoding = default_encoding return contents.decode(encoding, "replace") def commit_encode(commit, contents, default_encoding=DEFAULT_ENCODING): if commit.encoding: encoding = commit.encoding.decode("ascii") else: encoding = default_encoding return contents.encode(encoding) def print_commit(commit, decode, outstream=sys.stdout) -> None: """Write a human-readable commit log entry. Args: commit: A `Commit` object outstream: A stream file to write to """ outstream.write("-" * 50 + "\n") outstream.write("commit: " + commit.id.decode("ascii") + "\n") if len(commit.parents) > 1: outstream.write( "merge: " + "...".join([c.decode("ascii") for c in commit.parents[1:]]) + "\n" ) outstream.write("Author: " + decode(commit.author) + "\n") if commit.author != commit.committer: outstream.write("Committer: " + decode(commit.committer) + "\n") time_tuple = time.gmtime(commit.author_time + commit.author_timezone) time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple) timezone_str = format_timezone(commit.author_timezone).decode("ascii") outstream.write("Date: " + time_str + " " + timezone_str + "\n") outstream.write("\n") outstream.write(decode(commit.message) + "\n") outstream.write("\n") def print_tag(tag, decode, outstream=sys.stdout) -> None: """Write a human-readable tag. Args: tag: A `Tag` object decode: Function for decoding bytes to unicode string outstream: A stream to write to """ outstream.write("Tagger: " + decode(tag.tagger) + "\n") time_tuple = time.gmtime(tag.tag_time + tag.tag_timezone) time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple) timezone_str = format_timezone(tag.tag_timezone).decode("ascii") outstream.write("Date: " + time_str + " " + timezone_str + "\n") outstream.write("\n") outstream.write(decode(tag.message)) outstream.write("\n") def show_blob(repo, blob, decode, outstream=sys.stdout) -> None: """Write a blob to a stream. Args: repo: A `Repo` object blob: A `Blob` object decode: Function for decoding bytes to unicode string outstream: A stream file to write to """ outstream.write(decode(blob.data)) def show_commit(repo, commit, decode, outstream=sys.stdout) -> None: """Show a commit to a stream. Args: repo: A `Repo` object commit: A `Commit` object decode: Function for decoding bytes to unicode string outstream: Stream to write to """ print_commit(commit, decode=decode, outstream=outstream) if commit.parents: parent_commit = repo[commit.parents[0]] base_tree = parent_commit.tree else: base_tree = None diffstream = BytesIO() write_tree_diff(diffstream, repo.object_store, base_tree, commit.tree) diffstream.seek(0) outstream.write(commit_decode(commit, diffstream.getvalue())) def show_tree(repo, tree, decode, outstream=sys.stdout) -> None: """Print a tree to a stream. Args: repo: A `Repo` object tree: A `Tree` object decode: Function for decoding bytes to unicode string outstream: Stream to write to """ for n in tree: outstream.write(decode(n) + "\n") def show_tag(repo, tag, decode, outstream=sys.stdout) -> None: """Print a tag to a stream. Args: repo: A `Repo` object tag: A `Tag` object decode: Function for decoding bytes to unicode string outstream: Stream to write to """ print_tag(tag, decode, outstream) show_object(repo, repo[tag.object[1]], decode, outstream) def show_object(repo, obj, decode, outstream): return { b"tree": show_tree, b"blob": show_blob, b"commit": show_commit, b"tag": show_tag, }[obj.type_name](repo, obj, decode, outstream) def print_name_status(changes): """Print a simple status summary, listing changed files.""" for change in changes: if not change: continue if isinstance(change, list): change = change[0] if change.type == CHANGE_ADD: path1 = change.new.path path2 = "" kind = "A" elif change.type == CHANGE_DELETE: path1 = change.old.path path2 = "" kind = "D" elif change.type == CHANGE_MODIFY: path1 = change.new.path path2 = "" kind = "M" elif change.type in RENAME_CHANGE_TYPES: path1 = change.old.path path2 = change.new.path if change.type == CHANGE_RENAME: kind = "R" elif change.type == CHANGE_COPY: kind = "C" yield "%-8s%-20s%-20s" % (kind, path1, path2) # noqa: UP031 def log( repo=".", paths=None, outstream=sys.stdout, max_entries=None, reverse=False, name_status=False, ) -> None: """Write commit logs. Args: repo: Path to repository paths: Optional set of specific paths to print entries for outstream: Stream to write log output to reverse: Reverse order in which entries are printed name_status: Print name status max_entries: Optional maximum number of entries to display """ with open_repo_closing(repo) as r: walker = r.get_walker(max_entries=max_entries, paths=paths, reverse=reverse) for entry in walker: def decode(x): return commit_decode(entry.commit, x) print_commit(entry.commit, decode, outstream) if name_status: outstream.writelines( [line + "\n" for line in print_name_status(entry.changes())] ) # TODO(jelmer): better default for encoding? def show( repo=".", objects=None, outstream=sys.stdout, default_encoding=DEFAULT_ENCODING, ) -> None: """Print the changes in a commit. Args: repo: Path to repository objects: Objects to show (defaults to [HEAD]) outstream: Stream to write to default_encoding: Default encoding to use if none is set in the commit """ if objects is None: objects = ["HEAD"] if not isinstance(objects, list): objects = [objects] with open_repo_closing(repo) as r: for objectish in objects: o = parse_object(r, objectish) if isinstance(o, Commit): def decode(x): return commit_decode(o, x, default_encoding) else: def decode(x): return x.decode(default_encoding) show_object(r, o, decode, outstream) def diff_tree(repo, old_tree, new_tree, outstream=default_bytes_out_stream) -> None: """Compares the content and mode of blobs found via two tree objects. Args: repo: Path to repository old_tree: Id of old tree new_tree: Id of new tree outstream: Stream to write to """ with open_repo_closing(repo) as r: write_tree_diff(outstream, r.object_store, old_tree, new_tree) def rev_list(repo, commits, outstream=sys.stdout) -> None: """Lists commit objects in reverse chronological order. Args: repo: Path to repository commits: Commits over which to iterate outstream: Stream to write to """ with open_repo_closing(repo) as r: for entry in r.get_walker(include=[r[c].id for c in commits]): outstream.write(entry.commit.id + b"\n") def _canonical_part(url: str) -> str: name = url.rsplit("/", 1)[-1] if name.endswith(".git"): name = name[:-4] return name def submodule_add(repo, url, path=None, name=None) -> None: """Add a new submodule. Args: repo: Path to repository url: URL of repository to add as submodule path: Path where submodule should live """ with open_repo_closing(repo) as r: if path is None: path = os.path.relpath(_canonical_part(url), r.path) if name is None: name = path # TODO(jelmer): Move this logic to dulwich.submodule gitmodules_path = os.path.join(r.path, ".gitmodules") try: config = ConfigFile.from_path(gitmodules_path) except FileNotFoundError: config = ConfigFile() config.path = gitmodules_path config.set(("submodule", name), "url", url) config.set(("submodule", name), "path", path) config.write_to_path() def submodule_init(repo) -> None: """Initialize submodules. Args: repo: Path to repository """ with open_repo_closing(repo) as r: config = r.get_config() gitmodules_path = os.path.join(r.path, ".gitmodules") for path, url, name in read_submodules(gitmodules_path): config.set((b"submodule", name), b"active", True) config.set((b"submodule", name), b"url", url) config.write_to_path() def submodule_list(repo): """List submodules. Args: repo: Path to repository """ from .submodule import iter_cached_submodules with open_repo_closing(repo) as r: for path, sha in iter_cached_submodules(r.object_store, r[r.head()].tree): yield path, sha.decode(DEFAULT_ENCODING) def tag_create( repo, tag, author=None, message=None, annotated=False, objectish="HEAD", tag_time=None, tag_timezone=None, sign=False, encoding=DEFAULT_ENCODING, ) -> None: """Creates a tag in git via dulwich calls. Args: repo: Path to repository tag: tag string author: tag author (optional, if annotated is set) message: tag message (optional) annotated: whether to create an annotated tag objectish: object the tag should point at, defaults to HEAD tag_time: Optional time for annotated tag tag_timezone: Optional timezone for annotated tag sign: GPG Sign the tag (bool, defaults to False, pass True to use default GPG key, pass a str containing Key ID to use a specific GPG key) """ with open_repo_closing(repo) as r: object = parse_object(r, objectish) if annotated: # Create the tag object tag_obj = Tag() if author is None: author = get_user_identity(r.get_config_stack()) tag_obj.tagger = author tag_obj.message = message + "\n".encode(encoding) tag_obj.name = tag tag_obj.object = (type(object), object.id) if tag_time is None: tag_time = int(time.time()) tag_obj.tag_time = tag_time if tag_timezone is None: tag_timezone = get_user_timezones()[1] elif isinstance(tag_timezone, str): tag_timezone = parse_timezone(tag_timezone) tag_obj.tag_timezone = tag_timezone if sign: tag_obj.sign(sign if isinstance(sign, str) else None) r.object_store.add_object(tag_obj) tag_id = tag_obj.id else: tag_id = object.id r.refs[_make_tag_ref(tag)] = tag_id def tag_list(repo, outstream=sys.stdout): """List all tags. Args: repo: Path to repository outstream: Stream to write tags to """ with open_repo_closing(repo) as r: tags = sorted(r.refs.as_dict(b"refs/tags")) return tags def tag_delete(repo, name) -> None: """Remove a tag. Args: repo: Path to repository name: Name of tag to remove """ with open_repo_closing(repo) as r: if isinstance(name, bytes): names = [name] elif isinstance(name, list): names = name else: raise Error(f"Unexpected tag name type {name!r}") for name in names: del r.refs[_make_tag_ref(name)] def reset(repo, mode, treeish="HEAD") -> None: """Reset current HEAD to the specified state. Args: repo: Path to repository mode: Mode ("hard", "soft", "mixed") treeish: Treeish to reset to """ if mode != "hard": raise Error("hard is the only mode currently supported") with open_repo_closing(repo) as r: tree = parse_tree(r, treeish) r.reset_index(tree.id) def get_remote_repo( repo: Repo, remote_location: Optional[Union[str, bytes]] = None ) -> tuple[Optional[str], str]: config = repo.get_config() if remote_location is None: remote_location = get_branch_remote(repo) if isinstance(remote_location, str): encoded_location = remote_location.encode() else: encoded_location = remote_location section = (b"remote", encoded_location) remote_name: Optional[str] = None if config.has_section(section): remote_name = encoded_location.decode() encoded_location = config.get(section, "url") else: remote_name = None return (remote_name, encoded_location.decode()) def push( repo, remote_location=None, refspecs=None, outstream=default_bytes_out_stream, errstream=default_bytes_err_stream, force=False, **kwargs, ) -> None: """Remote push with dulwich via dulwich.client. Args: repo: Path to repository remote_location: Location of the remote refspecs: Refs to push to remote outstream: A stream file to write output errstream: A stream file to write errors force: Force overwriting refs """ # Open the repo with open_repo_closing(repo) as r: if refspecs is None: refspecs = [active_branch(r)] (remote_name, remote_location) = get_remote_repo(r, remote_location) # Get the client and path client, path = get_transport_and_path( remote_location, config=r.get_config_stack(), **kwargs ) selected_refs = [] remote_changed_refs = {} def update_refs(refs): selected_refs.extend(parse_reftuples(r.refs, refs, refspecs, force=force)) new_refs = {} # TODO: Handle selected_refs == {None: None} for lh, rh, force_ref in selected_refs: if lh is None: new_refs[rh] = ZERO_SHA remote_changed_refs[rh] = None else: try: localsha = r.refs[lh] except KeyError as exc: raise Error(f"No valid ref {lh} in local repository") from exc if not force_ref and rh in refs: check_diverged(r, refs[rh], localsha) new_refs[rh] = localsha remote_changed_refs[rh] = localsha return new_refs err_encoding = getattr(errstream, "encoding", None) or DEFAULT_ENCODING remote_location = client.get_url(path) try: result = client.send_pack( path, update_refs, generate_pack_data=r.generate_pack_data, progress=errstream.write, ) except SendPackError as exc: raise Error( "Push to " + remote_location + " failed -> " + exc.args[0].decode(), ) from exc else: errstream.write( b"Push to " + remote_location.encode(err_encoding) + b" successful.\n" ) for ref, error in (result.ref_status or {}).items(): if error is not None: errstream.write( b"Push of ref %s failed: %s\n" % (ref, error.encode(err_encoding)) ) else: errstream.write(b"Ref %s updated\n" % ref) if remote_name is not None: _import_remote_refs(r.refs, remote_name, remote_changed_refs) def pull( repo, remote_location=None, refspecs=None, outstream=default_bytes_out_stream, errstream=default_bytes_err_stream, fast_forward=True, force=False, filter_spec=None, protocol_version=None, **kwargs, ) -> None: """Pull from remote via dulwich.client. Args: repo: Path to repository remote_location: Location of the remote refspecs: refspecs to fetch. Can be a bytestring, a string, or a list of bytestring/string. outstream: A stream file to write to output errstream: A stream file to write to errors filter_spec: A git-rev-list-style object filter spec, as an ASCII string. Only used if the server supports the Git protocol-v2 'filter' feature, and ignored otherwise. protocol_version: desired Git protocol version. By default the highest mutually supported protocol version will be used """ # Open the repo with open_repo_closing(repo) as r: (remote_name, remote_location) = get_remote_repo(r, remote_location) selected_refs = [] if refspecs is None: refspecs = [b"HEAD"] def determine_wants(remote_refs, *args, **kwargs): selected_refs.extend( parse_reftuples(remote_refs, r.refs, refspecs, force=force) ) return [ remote_refs[lh] for (lh, rh, force_ref) in selected_refs if remote_refs[lh] not in r.object_store ] client, path = get_transport_and_path( remote_location, config=r.get_config_stack(), **kwargs ) if filter_spec: filter_spec = filter_spec.encode("ascii") fetch_result = client.fetch( path, r, progress=errstream.write, determine_wants=determine_wants, filter_spec=filter_spec, protocol_version=protocol_version, ) for lh, rh, force_ref in selected_refs: if not force_ref and rh in r.refs: try: check_diverged(r, r.refs.follow(rh)[1], fetch_result.refs[lh]) except DivergedBranches as exc: if fast_forward: raise else: raise NotImplementedError("merge is not yet supported") from exc r.refs[rh] = fetch_result.refs[lh] if selected_refs: r[b"HEAD"] = fetch_result.refs[selected_refs[0][1]] # Perform 'git checkout .' - syncs staged changes tree = r[b"HEAD"].tree r.reset_index(tree=tree) if remote_name is not None: _import_remote_refs(r.refs, remote_name, fetch_result.refs) def status(repo=".", ignored=False, untracked_files="all"): """Returns staged, unstaged, and untracked changes relative to the HEAD. Args: repo: Path to repository or repository object ignored: Whether to include ignored files in untracked untracked_files: How to handle untracked files, defaults to "all": "no": do not return untracked files "all": include all files in untracked directories Using untracked_files="no" can be faster than "all" when the worktreee contains many untracked files/directories. Note: untracked_files="normal" (git's default) is not implemented. Returns: GitStatus tuple, staged - dict with lists of staged paths (diff index/HEAD) unstaged - list of unstaged paths (diff index/working-tree) untracked - list of untracked, un-ignored & non-.git paths """ with open_repo_closing(repo) as r: # 1. Get status of staged tracked_changes = get_tree_changes(r) # 2. Get status of unstaged index = r.open_index() normalizer = r.get_blob_normalizer() filter_callback = normalizer.checkin_normalize unstaged_changes = list(get_unstaged_changes(index, r.path, filter_callback)) untracked_paths = get_untracked_paths( r.path, r.path, index, exclude_ignored=not ignored, untracked_files=untracked_files, ) if sys.platform == "win32": untracked_changes = [ path.replace(os.path.sep, "/") for path in untracked_paths ] else: untracked_changes = list(untracked_paths) return GitStatus(tracked_changes, unstaged_changes, untracked_changes) def _walk_working_dir_paths(frompath, basepath, prune_dirnames=None): """Get path, is_dir for files in working dir from frompath. Args: frompath: Path to begin walk basepath: Path to compare to prune_dirnames: Optional callback to prune dirnames during os.walk dirnames will be set to result of prune_dirnames(dirpath, dirnames) """ for dirpath, dirnames, filenames in os.walk(frompath): # Skip .git and below. if ".git" in dirnames: dirnames.remove(".git") if dirpath != basepath: continue if ".git" in filenames: filenames.remove(".git") if dirpath != basepath: continue if dirpath != frompath: yield dirpath, True for filename in filenames: filepath = os.path.join(dirpath, filename) yield filepath, False if prune_dirnames: dirnames[:] = prune_dirnames(dirpath, dirnames) def get_untracked_paths( frompath, basepath, index, exclude_ignored=False, untracked_files="all" ): """Get untracked paths. Args: frompath: Path to walk basepath: Path to compare to index: Index to check against exclude_ignored: Whether to exclude ignored paths untracked_files: How to handle untracked files: - "no": return an empty list - "all": return all files in untracked directories - "normal": Not implemented Note: ignored directories will never be walked for performance reasons. If exclude_ignored is False, only the path to an ignored directory will be yielded, no files inside the directory will be returned """ if untracked_files == "normal": raise NotImplementedError("normal is not yet supported") if untracked_files not in ("no", "all"): raise ValueError("untracked_files must be one of (no, all)") if untracked_files == "no": return with open_repo_closing(basepath) as r: ignore_manager = IgnoreFilterManager.from_repo(r) ignored_dirs = [] def prune_dirnames(dirpath, dirnames): for i in range(len(dirnames) - 1, -1, -1): path = os.path.join(dirpath, dirnames[i]) ip = os.path.join(os.path.relpath(path, basepath), "") if ignore_manager.is_ignored(ip): if not exclude_ignored: ignored_dirs.append( os.path.join(os.path.relpath(path, frompath), "") ) del dirnames[i] return dirnames for ap, is_dir in _walk_working_dir_paths( frompath, basepath, prune_dirnames=prune_dirnames ): if not is_dir: ip = path_to_tree_path(basepath, ap) if ip not in index: if not exclude_ignored or not ignore_manager.is_ignored( os.path.relpath(ap, basepath) ): yield os.path.relpath(ap, frompath) yield from ignored_dirs def get_tree_changes(repo): """Return add/delete/modify changes to tree by comparing index to HEAD. Args: repo: repo path or object Returns: dict with lists for each type of change """ with open_repo_closing(repo) as r: index = r.open_index() # Compares the Index to the HEAD & determines changes # Iterate through the changes and report add/delete/modify # TODO: call out to dulwich.diff_tree somehow. tracked_changes = { "add": [], "delete": [], "modify": [], } try: tree_id = r[b"HEAD"].tree except KeyError: tree_id = None for change in index.changes_from_tree(r.object_store, tree_id): if not change[0][0]: tracked_changes["add"].append(change[0][1]) elif not change[0][1]: tracked_changes["delete"].append(change[0][0]) elif change[0][0] == change[0][1]: tracked_changes["modify"].append(change[0][0]) else: raise NotImplementedError("git mv ops not yet supported") return tracked_changes def daemon(path=".", address=None, port=None) -> None: """Run a daemon serving Git requests over TCP/IP. Args: path: Path to the directory to serve. address: Optional address to listen on (defaults to ::) port: Optional port to listen on (defaults to TCP_GIT_PORT) """ # TODO(jelmer): Support git-daemon-export-ok and --export-all. backend = FileSystemBackend(path) server = TCPGitServer(backend, address, port) server.serve_forever() def web_daemon(path=".", address=None, port=None) -> None: """Run a daemon serving Git requests over HTTP. Args: path: Path to the directory to serve address: Optional address to listen on (defaults to ::) port: Optional port to listen on (defaults to 80) """ from .web import ( WSGIRequestHandlerLogger, WSGIServerLogger, make_server, make_wsgi_chain, ) backend = FileSystemBackend(path) app = make_wsgi_chain(backend) server = make_server( address, port, app, handler_class=WSGIRequestHandlerLogger, server_class=WSGIServerLogger, ) server.serve_forever() def upload_pack(path=".", inf=None, outf=None) -> int: """Upload a pack file after negotiating its contents using smart protocol. Args: path: Path to the repository inf: Input stream to communicate with client outf: Output stream to communicate with client """ if outf is None: outf = getattr(sys.stdout, "buffer", sys.stdout) if inf is None: inf = getattr(sys.stdin, "buffer", sys.stdin) path = os.path.expanduser(path) backend = FileSystemBackend(path) def send_fn(data) -> None: outf.write(data) outf.flush() proto = Protocol(inf.read, send_fn) handler = UploadPackHandler(backend, [path], proto) # FIXME: Catch exceptions and write a single-line summary to outf. handler.handle() return 0 def receive_pack(path=".", inf=None, outf=None) -> int: """Receive a pack file after negotiating its contents using smart protocol. Args: path: Path to the repository inf: Input stream to communicate with client outf: Output stream to communicate with client """ if outf is None: outf = getattr(sys.stdout, "buffer", sys.stdout) if inf is None: inf = getattr(sys.stdin, "buffer", sys.stdin) path = os.path.expanduser(path) backend = FileSystemBackend(path) def send_fn(data) -> None: outf.write(data) outf.flush() proto = Protocol(inf.read, send_fn) handler = ReceivePackHandler(backend, [path], proto) # FIXME: Catch exceptions and write a single-line summary to outf. handler.handle() return 0 def _make_branch_ref(name): if getattr(name, "encode", None): name = name.encode(DEFAULT_ENCODING) return LOCAL_BRANCH_PREFIX + name def _make_tag_ref(name): if getattr(name, "encode", None): name = name.encode(DEFAULT_ENCODING) return LOCAL_TAG_PREFIX + name def branch_delete(repo, name) -> None: """Delete a branch. Args: repo: Path to the repository name: Name of the branch """ with open_repo_closing(repo) as r: if isinstance(name, list): names = name else: names = [name] for name in names: del r.refs[_make_branch_ref(name)] def branch_create(repo, name, objectish=None, force=False) -> None: """Create a branch. Args: repo: Path to the repository name: Name of the new branch objectish: Target object to point new branch at (defaults to HEAD) force: Force creation of branch, even if it already exists """ with open_repo_closing(repo) as r: if objectish is None: objectish = "HEAD" object = parse_object(r, objectish) refname = _make_branch_ref(name) ref_message = b"branch: Created from " + objectish.encode(DEFAULT_ENCODING) if force: r.refs.set_if_equals(refname, None, object.id, message=ref_message) else: if not r.refs.add_if_new(refname, object.id, message=ref_message): raise Error(f"Branch with name {name} already exists.") def branch_list(repo): """List all branches. Args: repo: Path to the repository """ with open_repo_closing(repo) as r: return r.refs.keys(base=LOCAL_BRANCH_PREFIX) def active_branch(repo): """Return the active branch in the repository, if any. Args: repo: Repository to open Returns: branch name Raises: KeyError: if the repository does not have a working tree IndexError: if HEAD is floating """ with open_repo_closing(repo) as r: active_ref = r.refs.follow(b"HEAD")[0][1] if not active_ref.startswith(LOCAL_BRANCH_PREFIX): raise ValueError(active_ref) return active_ref[len(LOCAL_BRANCH_PREFIX) :] def get_branch_remote(repo): """Return the active branch's remote name, if any. Args: repo: Repository to open Returns: remote name Raises: KeyError: if the repository does not have a working tree """ with open_repo_closing(repo) as r: branch_name = active_branch(r.path) config = r.get_config() try: remote_name = config.get((b"branch", branch_name), b"remote") except KeyError: remote_name = b"origin" return remote_name def fetch( repo, remote_location=None, outstream=sys.stdout, errstream=default_bytes_err_stream, message=None, depth=None, prune=False, prune_tags=False, force=False, **kwargs, ): """Fetch objects from a remote server. Args: repo: Path to the repository remote_location: String identifying a remote server outstream: Output stream (defaults to stdout) errstream: Error stream (defaults to stderr) message: Reflog message (defaults to b"fetch: from ") depth: Depth to fetch at prune: Prune remote removed refs prune_tags: Prune reomte removed tags Returns: Dictionary with refs on the remote """ with open_repo_closing(repo) as r: (remote_name, remote_location) = get_remote_repo(r, remote_location) if message is None: message = b"fetch: from " + remote_location.encode(DEFAULT_ENCODING) client, path = get_transport_and_path( remote_location, config=r.get_config_stack(), **kwargs ) fetch_result = client.fetch(path, r, progress=errstream.write, depth=depth) if remote_name is not None: _import_remote_refs( r.refs, remote_name, fetch_result.refs, message, prune=prune, prune_tags=prune_tags, ) return fetch_result def for_each_ref( repo: Union[Repo, str] = ".", pattern: Optional[Union[str, bytes]] = None, ) -> list[tuple[bytes, bytes, bytes]]: """Iterate over all refs that match the (optional) pattern. Args: repo: Path to the repository pattern: Optional glob (7) patterns to filter the refs with Returns: List of bytes tuples with: (sha, object_type, ref_name) """ if isinstance(pattern, str): pattern = os.fsencode(pattern) with open_repo_closing(repo) as r: refs = r.get_refs() if pattern: matching_refs: dict[bytes, bytes] = {} pattern_parts = pattern.split(b"/") for ref, sha in refs.items(): matches = False # git for-each-ref uses glob (7) style patterns, but fnmatch # is greedy and also matches slashes, unlike glob.glob. # We have to check parts of the pattern individually. # See https://github.com/python/cpython/issues/72904 ref_parts = ref.split(b"/") if len(ref_parts) > len(pattern_parts): continue for pat, ref_part in zip(pattern_parts, ref_parts): matches = fnmatch.fnmatchcase(ref_part, pat) if not matches: break if matches: matching_refs[ref] = sha refs = matching_refs ret: list[tuple[bytes, bytes, bytes]] = [ (sha, r.get_object(sha).type_name, ref) for ref, sha in sorted( refs.items(), key=lambda ref_sha: ref_sha[0], ) if ref != b"HEAD" ] return ret def ls_remote(remote, config: Optional[Config] = None, **kwargs): """List the refs in a remote. Args: remote: Remote repository location config: Configuration to use Returns: Dictionary with remote refs """ if config is None: config = StackedConfig.default() client, host_path = get_transport_and_path(remote, config=config, **kwargs) return client.get_refs(host_path) def repack(repo) -> None: """Repack loose files in a repository. Currently this only packs loose objects. Args: repo: Path to the repository """ with open_repo_closing(repo) as r: r.object_store.pack_loose_objects() def pack_objects( repo, object_ids, packf, idxf, delta_window_size=None, deltify=None, reuse_deltas=True, ) -> None: """Pack objects into a file. Args: repo: Path to the repository object_ids: List of object ids to write packf: File-like object to write to idxf: File-like object to write to (can be None) delta_window_size: Sliding window size for searching for deltas; Set to None for default window size. deltify: Whether to deltify objects reuse_deltas: Allow reuse of existing deltas while deltifying """ with open_repo_closing(repo) as r: entries, data_sum = write_pack_from_container( packf.write, r.object_store, [(oid, None) for oid in object_ids], deltify=deltify, delta_window_size=delta_window_size, reuse_deltas=reuse_deltas, ) if idxf is not None: entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()]) write_pack_index(idxf, entries, data_sum) def ls_tree( repo, treeish=b"HEAD", outstream=sys.stdout, recursive=False, name_only=False, ) -> None: """List contents of a tree. Args: repo: Path to the repository treeish: Tree id to list outstream: Output stream (defaults to stdout) recursive: Whether to recursively list files name_only: Only print item name """ def list_tree(store, treeid, base) -> None: for name, mode, sha in store[treeid].iteritems(): if base: name = posixpath.join(base, name) if name_only: outstream.write(name + b"\n") else: outstream.write(pretty_format_tree_entry(name, mode, sha)) if stat.S_ISDIR(mode) and recursive: list_tree(store, sha, name) with open_repo_closing(repo) as r: tree = parse_tree(r, treeish) list_tree(r.object_store, tree.id, "") def remote_add(repo, name: Union[bytes, str], url: Union[bytes, str]) -> None: """Add a remote. Args: repo: Path to the repository name: Remote name url: Remote URL """ if not isinstance(name, bytes): name = name.encode(DEFAULT_ENCODING) if not isinstance(url, bytes): url = url.encode(DEFAULT_ENCODING) with open_repo_closing(repo) as r: c = r.get_config() section = (b"remote", name) if c.has_section(section): raise RemoteExists(section) c.set(section, b"url", url) c.write_to_path() def remote_remove(repo: Repo, name: Union[bytes, str]) -> None: """Remove a remote. Args: repo: Path to the repository name: Remote name """ if not isinstance(name, bytes): name = name.encode(DEFAULT_ENCODING) with open_repo_closing(repo) as r: c = r.get_config() section = (b"remote", name) del c[section] c.write_to_path() def check_ignore(repo, paths, no_index=False): """Debug gitignore files. Args: repo: Path to the repository paths: List of paths to check for no_index: Don't check index Returns: List of ignored files """ with open_repo_closing(repo) as r: index = r.open_index() ignore_manager = IgnoreFilterManager.from_repo(r) for path in paths: if not no_index and path_to_tree_path(r.path, path) in index: continue if os.path.isabs(path): path = os.path.relpath(path, r.path) if ignore_manager.is_ignored(path): yield path def update_head(repo, target, detached=False, new_branch=None) -> None: """Update HEAD to point at a new branch/commit. Note that this does not actually update the working tree. Args: repo: Path to the repository detached: Create a detached head target: Branch or committish to switch to new_branch: New branch to create """ with open_repo_closing(repo) as r: if new_branch is not None: to_set = _make_branch_ref(new_branch) else: to_set = b"HEAD" if detached: # TODO(jelmer): Provide some way so that the actual ref gets # updated rather than what it points to, so the delete isn't # necessary. del r.refs[to_set] r.refs[to_set] = parse_commit(r, target).id else: r.refs.set_symbolic_ref(to_set, parse_ref(r, target)) if new_branch is not None: r.refs.set_symbolic_ref(b"HEAD", to_set) def reset_file(repo, file_path: str, target: bytes = b"HEAD", symlink_fn=None) -> None: """Reset the file to specific commit or branch. Args: repo: dulwich Repo object file_path: file to reset, relative to the repository path target: branch or commit or b'HEAD' to reset """ tree = parse_tree(repo, treeish=target) tree_path = _fs_to_tree_path(file_path) file_entry = tree.lookup_path(repo.object_store.__getitem__, tree_path) full_path = os.path.join(os.fsencode(repo.path), tree_path) blob = repo.object_store[file_entry[1]] mode = file_entry[0] build_file_from_blob(blob, mode, full_path, symlink_fn=symlink_fn) def _update_head_during_checkout_branch(repo, target): checkout_target = None if target == b"HEAD": # Do not update head while trying to checkout to HEAD. pass elif target in repo.refs.keys(base=LOCAL_BRANCH_PREFIX): update_head(repo, target) else: # If checking out a remote branch, create a local one without the remote name prefix. config = repo.get_config() name = target.split(b"/")[0] section = (b"remote", name) if config.has_section(section): checkout_target = target.replace(name + b"/", b"") try: branch_create( repo, checkout_target, (LOCAL_REMOTE_PREFIX + target).decode() ) except Error: pass update_head(repo, LOCAL_BRANCH_PREFIX + checkout_target) else: update_head(repo, target, detached=True) return checkout_target def checkout_branch(repo, target: Union[bytes, str], force: bool = False) -> None: """Switch branches or restore working tree files. The implementation of this function will probably not scale well for branches with lots of local changes. This is due to the analysis of a diff between branches before any changes are applied. Args: repo: dulwich Repo object target: branch name or commit sha to checkout force: true or not to force checkout """ target = to_bytes(target) current_tree = parse_tree(repo, repo.head()) target_tree = parse_tree(repo, target) if force: repo.reset_index(target_tree.id) _update_head_during_checkout_branch(repo, target) else: status_report = status(repo) changes = list( set( status_report[0]["add"] + status_report[0]["delete"] + status_report[0]["modify"] + status_report[1] ) ) index = 0 while index < len(changes): change = changes[index] try: current_tree.lookup_path(repo.object_store.__getitem__, change) try: target_tree.lookup_path(repo.object_store.__getitem__, change) index += 1 except KeyError: raise CheckoutError( "Your local changes to the following files would be overwritten by checkout: " + change.decode() ) except KeyError: changes.pop(index) # Update head. checkout_target = _update_head_during_checkout_branch(repo, target) if checkout_target is not None: target_tree = parse_tree(repo, checkout_target) dealt_with = set() repo_index = repo.open_index() for entry in iter_tree_contents(repo.object_store, target_tree.id): dealt_with.add(entry.path) if entry.path in changes: continue full_path = os.path.join(os.fsencode(repo.path), entry.path) blob = repo.object_store[entry.sha] ensure_dir_exists(os.path.dirname(full_path)) st = build_file_from_blob(blob, entry.mode, full_path) repo_index[entry.path] = index_entry_from_stat(st, entry.sha) repo_index.write() for entry in iter_tree_contents(repo.object_store, current_tree.id): if entry.path not in dealt_with: repo.unstage([entry.path]) # Remove the untracked files which are in the current_file_set. repo_index = repo.open_index() for change in repo_index.changes_from_tree(repo.object_store, current_tree.id): path_change = change[0] if path_change[1] is None: file_name = path_change[0] full_path = os.path.join(repo.path, file_name.decode()) if os.path.isfile(full_path): os.remove(full_path) dir_path = os.path.dirname(full_path) while dir_path != repo.path: is_empty = len(os.listdir(dir_path)) == 0 if is_empty: os.rmdir(dir_path) dir_path = os.path.dirname(dir_path) def check_mailmap(repo, contact): """Check canonical name and email of contact. Args: repo: Path to the repository contact: Contact name and/or email Returns: Canonical contact data """ with open_repo_closing(repo) as r: from .mailmap import Mailmap try: mailmap = Mailmap.from_path(os.path.join(r.path, ".mailmap")) except FileNotFoundError: mailmap = Mailmap() return mailmap.lookup(contact) def fsck(repo): """Check a repository. Args: repo: A path to the repository Returns: Iterator over errors/warnings """ with open_repo_closing(repo) as r: # TODO(jelmer): check pack files # TODO(jelmer): check graph # TODO(jelmer): check refs for sha in r.object_store: o = r.object_store[sha] try: o.check() except Exception as e: yield (sha, e) def stash_list(repo): """List all stashes in a repository.""" with open_repo_closing(repo) as r: from .stash import Stash stash = Stash.from_repo(r) return enumerate(list(stash.stashes())) def stash_push(repo) -> None: """Push a new stash onto the stack.""" with open_repo_closing(repo) as r: from .stash import Stash stash = Stash.from_repo(r) stash.push() def stash_pop(repo) -> None: """Pop a stash from the stack.""" with open_repo_closing(repo) as r: from .stash import Stash stash = Stash.from_repo(r) stash.pop() def stash_drop(repo, index) -> None: """Drop a stash from the stack.""" with open_repo_closing(repo) as r: from .stash import Stash stash = Stash.from_repo(r) stash.drop(index) def ls_files(repo): """List all files in an index.""" with open_repo_closing(repo) as r: return sorted(r.open_index()) def find_unique_abbrev(object_store, object_id): """For now, just return 7 characters.""" # TODO(jelmer): Add some logic here to return a number of characters that # scales relative with the size of the repository return object_id.decode("ascii")[:7] def describe(repo, abbrev=7): """Describe the repository version. Args: repo: git repository abbrev: number of characters of commit to take, default is 7 Returns: a string description of the current git revision Examples: "gabcdefh", "v0.1" or "v0.1-5-gabcdefh". """ # Get the repository with open_repo_closing(repo) as r: # Get a list of all tags refs = r.get_refs() tags = {} for key, value in refs.items(): key = key.decode() obj = r.get_object(value) if "tags" not in key: continue _, tag = key.rsplit("/", 1) try: commit = obj.object except AttributeError: continue else: commit = r.get_object(commit[1]) tags[tag] = [ datetime.datetime(*time.gmtime(commit.commit_time)[:6]), commit.id.decode("ascii"), ] sorted_tags = sorted(tags.items(), key=lambda tag: tag[1][0], reverse=True) # If there are no tags, return the current commit if len(sorted_tags) == 0: return f"g{find_unique_abbrev(r.object_store, r[r.head()].id)}" # We're now 0 commits from the top commit_count = 0 # Get the latest commit latest_commit = r[r.head()] # Walk through all commits walker = r.get_walker() for entry in walker: # Check if tag commit_id = entry.commit.id.decode("ascii") for tag in sorted_tags: tag_name = tag[0] tag_commit = tag[1][1] if commit_id == tag_commit: if commit_count == 0: return tag_name else: return "{}-{}-g{}".format( tag_name, commit_count, latest_commit.id.decode("ascii")[:abbrev], ) commit_count += 1 # Return plain commit if no parent tag can be found return "g{}".format(latest_commit.id.decode("ascii")[:abbrev]) def get_object_by_path(repo, path, committish=None): """Get an object by path. Args: repo: A path to the repository path: Path to look up committish: Commit to look up path in Returns: A `ShaFile` object """ if committish is None: committish = "HEAD" # Get the repository with open_repo_closing(repo) as r: commit = parse_commit(r, committish) base_tree = commit.tree if not isinstance(path, bytes): path = commit_encode(commit, path) (mode, sha) = tree_lookup_path(r.object_store.__getitem__, base_tree, path) return r[sha] def write_tree(repo): """Write a tree object from the index. Args: repo: Repository for which to write tree Returns: tree id for the tree that was written """ with open_repo_closing(repo) as r: return r.open_index().commit(r.object_store) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/protocol.py0000644000175100002000000004636614731042555016530 0ustar00runnerdocker# protocol.py -- Shared parts of the git protocols # Copyright (C) 2008 John Carr # Copyright (C) 2008-2012 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Generic functions for talking the git smart server protocol.""" from io import BytesIO from os import SEEK_END from typing import Optional import dulwich from .errors import GitProtocolError, HangupException TCP_GIT_PORT = 9418 # Git protocol version 0 is the original Git protocol, which lacked a # version number until Git protocol version 1 was introduced by Brandon # Williams in 2017. # # Protocol version 1 is simply the original v0 protocol with the addition of # a single packet line, which precedes the ref advertisement, indicating the # protocol version being used. This was done in preparation for protocol v2. # # Git protocol version 2 was first introduced by Brandon Williams in 2018 and # adds many features. See the gitprotocol-v2(5) manual page for details. # As of 2024, Git only implements version 2 during 'git fetch' and still uses # version 0 during 'git push'. GIT_PROTOCOL_VERSIONS = [0, 1, 2] DEFAULT_GIT_PROTOCOL_VERSION_FETCH = 2 DEFAULT_GIT_PROTOCOL_VERSION_SEND = 0 ZERO_SHA = b"0" * 40 SINGLE_ACK = 0 MULTI_ACK = 1 MULTI_ACK_DETAILED = 2 # pack data SIDE_BAND_CHANNEL_DATA = 1 # progress messages SIDE_BAND_CHANNEL_PROGRESS = 2 # fatal error message just before stream aborts SIDE_BAND_CHANNEL_FATAL = 3 CAPABILITY_ATOMIC = b"atomic" CAPABILITY_DEEPEN_SINCE = b"deepen-since" CAPABILITY_DEEPEN_NOT = b"deepen-not" CAPABILITY_DEEPEN_RELATIVE = b"deepen-relative" CAPABILITY_DELETE_REFS = b"delete-refs" CAPABILITY_INCLUDE_TAG = b"include-tag" CAPABILITY_MULTI_ACK = b"multi_ack" CAPABILITY_MULTI_ACK_DETAILED = b"multi_ack_detailed" CAPABILITY_NO_DONE = b"no-done" CAPABILITY_NO_PROGRESS = b"no-progress" CAPABILITY_OFS_DELTA = b"ofs-delta" CAPABILITY_QUIET = b"quiet" CAPABILITY_REPORT_STATUS = b"report-status" CAPABILITY_SHALLOW = b"shallow" CAPABILITY_SIDE_BAND = b"side-band" CAPABILITY_SIDE_BAND_64K = b"side-band-64k" CAPABILITY_THIN_PACK = b"thin-pack" CAPABILITY_AGENT = b"agent" CAPABILITY_SYMREF = b"symref" CAPABILITY_ALLOW_TIP_SHA1_IN_WANT = b"allow-tip-sha1-in-want" CAPABILITY_ALLOW_REACHABLE_SHA1_IN_WANT = b"allow-reachable-sha1-in-want" CAPABILITY_FETCH = b"fetch" CAPABILITY_FILTER = b"filter" # Magic ref that is used to attach capabilities to when # there are no refs. Should always be ste to ZERO_SHA. CAPABILITIES_REF = b"capabilities^{}" COMMON_CAPABILITIES = [ CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND, CAPABILITY_SIDE_BAND_64K, CAPABILITY_AGENT, CAPABILITY_NO_PROGRESS, ] KNOWN_UPLOAD_CAPABILITIES = set( [ *COMMON_CAPABILITIES, CAPABILITY_THIN_PACK, CAPABILITY_MULTI_ACK, CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_INCLUDE_TAG, CAPABILITY_DEEPEN_SINCE, CAPABILITY_SYMREF, CAPABILITY_SHALLOW, CAPABILITY_DEEPEN_NOT, CAPABILITY_DEEPEN_RELATIVE, CAPABILITY_ALLOW_TIP_SHA1_IN_WANT, CAPABILITY_ALLOW_REACHABLE_SHA1_IN_WANT, CAPABILITY_FETCH, ] ) KNOWN_RECEIVE_CAPABILITIES = set( [ *COMMON_CAPABILITIES, CAPABILITY_REPORT_STATUS, CAPABILITY_DELETE_REFS, CAPABILITY_QUIET, CAPABILITY_ATOMIC, ] ) DEPTH_INFINITE = 0x7FFFFFFF NAK_LINE = b"NAK\n" def agent_string(): return ("dulwich/" + ".".join(map(str, dulwich.__version__))).encode("ascii") def capability_agent(): return CAPABILITY_AGENT + b"=" + agent_string() def capability_symref(from_ref, to_ref): return CAPABILITY_SYMREF + b"=" + from_ref + b":" + to_ref def extract_capability_names(capabilities): return {parse_capability(c)[0] for c in capabilities} def parse_capability(capability): parts = capability.split(b"=", 1) if len(parts) == 1: return (parts[0], None) return tuple(parts) def symref_capabilities(symrefs): return [capability_symref(*k) for k in symrefs] COMMAND_DEEPEN = b"deepen" COMMAND_SHALLOW = b"shallow" COMMAND_UNSHALLOW = b"unshallow" COMMAND_DONE = b"done" COMMAND_WANT = b"want" COMMAND_HAVE = b"have" def format_cmd_pkt(cmd, *args): return cmd + b" " + b"".join([(a + b"\0") for a in args]) def parse_cmd_pkt(line): splice_at = line.find(b" ") cmd, args = line[:splice_at], line[splice_at + 1 :] assert args[-1:] == b"\x00" return cmd, args[:-1].split(b"\0") def pkt_line(data): """Wrap data in a pkt-line. Args: data: The data to wrap, as a str or None. Returns: The data prefixed with its length in pkt-line format; if data was None, returns the flush-pkt ('0000'). """ if data is None: return b"0000" return ("%04x" % (len(data) + 4)).encode("ascii") + data def pkt_seq(*seq): """Wrap a sequence of data in pkt-lines. Args: seq: An iterable of strings to wrap. """ return b"".join([pkt_line(s) for s in seq]) + pkt_line(None) def filter_ref_prefix(refs, prefixes): """Filter refs to only include those with a given prefix. Args: refs: A list of refs. prefix: The prefix to filter by. """ return {k: v for k, v in refs.items() if any(k.startswith(p) for p in prefixes)} class Protocol: """Class for interacting with a remote git process over the wire. Parts of the git wire protocol use 'pkt-lines' to communicate. A pkt-line consists of the length of the line as a 4-byte hex string, followed by the payload data. The length includes the 4-byte header. The special line '0000' indicates the end of a section of input and is called a 'flush-pkt'. For details on the pkt-line format, see the cgit distribution: Documentation/technical/protocol-common.txt """ def __init__(self, read, write, close=None, report_activity=None) -> None: self.read = read self.write = write self._close = close self.report_activity = report_activity self._readahead: Optional[BytesIO] = None def close(self) -> None: if self._close: self._close() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def read_pkt_line(self): """Reads a pkt-line from the remote git process. This method may read from the readahead buffer; see unread_pkt_line. Returns: The next string from the stream, without the length prefix, or None for a flush-pkt ('0000') or delim-pkt ('0001'). """ if self._readahead is None: read = self.read else: read = self._readahead.read self._readahead = None try: sizestr = read(4) if not sizestr: raise HangupException size = int(sizestr, 16) if size == 0 or size == 1: # flush-pkt or delim-pkt if self.report_activity: self.report_activity(4, "read") return None if self.report_activity: self.report_activity(size, "read") pkt_contents = read(size - 4) except ConnectionResetError as exc: raise HangupException from exc except OSError as exc: raise GitProtocolError(str(exc)) from exc else: if len(pkt_contents) + 4 != size: raise GitProtocolError( f"Length of pkt read {len(pkt_contents) + 4:04x} does not match length prefix {size:04x}" ) return pkt_contents def eof(self) -> bool: """Test whether the protocol stream has reached EOF. Note that this refers to the actual stream EOF and not just a flush-pkt. Returns: True if the stream is at EOF, False otherwise. """ try: next_line = self.read_pkt_line() except HangupException: return True self.unread_pkt_line(next_line) return False def unread_pkt_line(self, data) -> None: """Unread a single line of data into the readahead buffer. This method can be used to unread a single pkt-line into a fixed readahead buffer. Args: data: The data to unread, without the length prefix. Raises: ValueError: If more than one pkt-line is unread. """ if self._readahead is not None: raise ValueError("Attempted to unread multiple pkt-lines.") self._readahead = BytesIO(pkt_line(data)) def read_pkt_seq(self): """Read a sequence of pkt-lines from the remote git process. Returns: Yields each line of data up to but not including the next flush-pkt. """ pkt = self.read_pkt_line() while pkt: yield pkt pkt = self.read_pkt_line() def write_pkt_line(self, line) -> None: """Sends a pkt-line to the remote git process. Args: line: A string containing the data to send, without the length prefix. """ try: line = pkt_line(line) self.write(line) if self.report_activity: self.report_activity(len(line), "write") except OSError as exc: raise GitProtocolError(str(exc)) from exc def write_sideband(self, channel, blob) -> None: """Write multiplexed data to the sideband. Args: channel: An int specifying the channel to write to. blob: A blob of data (as a string) to send on this channel. """ # a pktline can be a max of 65520. a sideband line can therefore be # 65520-5 = 65515 # WTF: Why have the len in ASCII, but the channel in binary. while blob: self.write_pkt_line(bytes(bytearray([channel])) + blob[:65515]) blob = blob[65515:] def send_cmd(self, cmd, *args) -> None: """Send a command and some arguments to a git server. Only used for the TCP git protocol (git://). Args: cmd: The remote service to access. args: List of arguments to send to remove service. """ self.write_pkt_line(format_cmd_pkt(cmd, *args)) def read_cmd(self): """Read a command and some arguments from the git client. Only used for the TCP git protocol (git://). Returns: A tuple of (command, [list of arguments]). """ line = self.read_pkt_line() return parse_cmd_pkt(line) _RBUFSIZE = 8192 # Default read buffer size. class ReceivableProtocol(Protocol): """Variant of Protocol that allows reading up to a size without blocking. This class has a recv() method that behaves like socket.recv() in addition to a read() method. If you want to read n bytes from the wire and block until exactly n bytes (or EOF) are read, use read(n). If you want to read at most n bytes from the wire but don't care if you get less, use recv(n). Note that recv(n) will still block until at least one byte is read. """ def __init__( self, recv, write, close=None, report_activity=None, rbufsize=_RBUFSIZE ) -> None: super().__init__(self.read, write, close=close, report_activity=report_activity) self._recv = recv self._rbuf = BytesIO() self._rbufsize = rbufsize def read(self, size): # From _fileobj.read in socket.py in the Python 2.6.5 standard library, # with the following modifications: # - omit the size <= 0 branch # - seek back to start rather than 0 in case some buffer has been # consumed. # - use SEEK_END instead of the magic number. # Copyright (c) 2001-2010 Python Software Foundation; All Rights # Reserved # Licensed under the Python Software Foundation License. # TODO: see if buffer is more efficient than cBytesIO. assert size > 0 # Our use of BytesIO rather than lists of string objects returned by # recv() minimizes memory usage and fragmentation that occurs when # rbufsize is large compared to the typical return value of recv(). buf = self._rbuf start = buf.tell() buf.seek(0, SEEK_END) # buffer may have been partially consumed by recv() buf_len = buf.tell() - start if buf_len >= size: # Already have size bytes in our buffer? Extract and return. buf.seek(start) rv = buf.read(size) self._rbuf = BytesIO() self._rbuf.write(buf.read()) self._rbuf.seek(0) return rv self._rbuf = BytesIO() # reset _rbuf. we consume it via buf. while True: left = size - buf_len # recv() will malloc the amount of memory given as its # parameter even though it often returns much less data # than that. The returned data string is short lived # as we copy it into a BytesIO and free it. This avoids # fragmentation issues on many platforms. data = self._recv(left) if not data: break n = len(data) if n == size and not buf_len: # Shortcut. Avoid buffer data copies when: # - We have no data in our buffer. # AND # - Our call to recv returned exactly the # number of bytes we were asked to read. return data if n == left: buf.write(data) del data # explicit free break assert n <= left, f"_recv({left}) returned {n} bytes" buf.write(data) buf_len += n del data # explicit free # assert buf_len == buf.tell() buf.seek(start) return buf.read() def recv(self, size): assert size > 0 buf = self._rbuf start = buf.tell() buf.seek(0, SEEK_END) buf_len = buf.tell() buf.seek(start) left = buf_len - start if not left: # only read from the wire if our read buffer is exhausted data = self._recv(self._rbufsize) if len(data) == size: # shortcut: skip the buffer if we read exactly size bytes return data buf = BytesIO() buf.write(data) buf.seek(0) del data # explicit free self._rbuf = buf return buf.read(size) def extract_capabilities(text): """Extract a capabilities list from a string, if present. Args: text: String to extract from Returns: Tuple with text with capabilities removed and list of capabilities """ if b"\0" not in text: return text, [] text, capabilities = text.rstrip().split(b"\0") return (text, capabilities.strip().split(b" ")) def extract_want_line_capabilities(text): """Extract a capabilities list from a want line, if present. Note that want lines have capabilities separated from the rest of the line by a space instead of a null byte. Thus want lines have the form: want obj-id cap1 cap2 ... Args: text: Want line to extract from Returns: Tuple with text with capabilities removed and list of capabilities """ split_text = text.rstrip().split(b" ") if len(split_text) < 3: return text, [] return (b" ".join(split_text[:2]), split_text[2:]) def ack_type(capabilities): """Extract the ack type from a capabilities list.""" if b"multi_ack_detailed" in capabilities: return MULTI_ACK_DETAILED elif b"multi_ack" in capabilities: return MULTI_ACK return SINGLE_ACK class BufferedPktLineWriter: """Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length prefix) reach the buffer size. """ def __init__(self, write, bufsize=65515) -> None: """Initialize the BufferedPktLineWriter. Args: write: A write callback for the underlying writer. bufsize: The internal buffer size, including length prefixes. """ self._write = write self._bufsize = bufsize self._wbuf = BytesIO() self._buflen = 0 def write(self, data) -> None: """Write data, wrapping it in a pkt-line.""" line = pkt_line(data) line_len = len(line) over = self._buflen + line_len - self._bufsize if over >= 0: start = line_len - over self._wbuf.write(line[:start]) self.flush() else: start = 0 saved = line[start:] self._wbuf.write(saved) self._buflen += len(saved) def flush(self) -> None: """Flush all data from the buffer.""" data = self._wbuf.getvalue() if data: self._write(data) self._len = 0 self._wbuf = BytesIO() class PktLineParser: """Packet line parser that hands completed packets off to a callback.""" def __init__(self, handle_pkt) -> None: self.handle_pkt = handle_pkt self._readahead = BytesIO() def parse(self, data) -> None: """Parse a fragment of data and call back for any completed packets.""" self._readahead.write(data) buf = self._readahead.getvalue() if len(buf) < 4: return while len(buf) >= 4: size = int(buf[:4], 16) if size == 0: self.handle_pkt(None) buf = buf[4:] elif size <= len(buf): self.handle_pkt(buf[4:size]) buf = buf[size:] else: break self._readahead = BytesIO() self._readahead.write(buf) def get_tail(self): """Read back any unused data.""" return self._readahead.getvalue() def format_capability_line(capabilities): return b"".join([b" " + c for c in capabilities]) def format_ref_line(ref, sha, capabilities=None): if capabilities is None: return sha + b" " + ref + b"\n" else: return sha + b" " + ref + b"\0" + format_capability_line(capabilities) + b"\n" def format_shallow_line(sha): return COMMAND_SHALLOW + b" " + sha def format_unshallow_line(sha): return COMMAND_UNSHALLOW + b" " + sha def format_ack_line(sha, ack_type=b""): if ack_type: ack_type = b" " + ack_type return b"ACK " + sha + ack_type + b"\n" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/py.typed0000644000175100002000000000000014731042555015763 0ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/reflog.py0000644000175100002000000001013514731042555016126 0ustar00runnerdocker# reflog.py -- Parsing and writing reflog files # Copyright (C) 2015 Jelmer Vernooij and others. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Utilities for reading and generating reflogs.""" import collections from .objects import ZERO_SHA, format_timezone, parse_timezone Entry = collections.namedtuple( "Entry", ["old_sha", "new_sha", "committer", "timestamp", "timezone", "message"], ) def format_reflog_line(old_sha, new_sha, committer, timestamp, timezone, message): """Generate a single reflog line. Args: old_sha: Old Commit SHA new_sha: New Commit SHA committer: Committer name and e-mail timestamp: Timestamp timezone: Timezone message: Message """ if old_sha is None: old_sha = ZERO_SHA return ( old_sha + b" " + new_sha + b" " + committer + b" " + str(int(timestamp)).encode("ascii") + b" " + format_timezone(timezone) + b"\t" + message ) def parse_reflog_line(line): """Parse a reflog line. Args: line: Line to parse Returns: Tuple of (old_sha, new_sha, committer, timestamp, timezone, message) """ (begin, message) = line.split(b"\t", 1) (old_sha, new_sha, rest) = begin.split(b" ", 2) (committer, timestamp_str, timezone_str) = rest.rsplit(b" ", 2) return Entry( old_sha, new_sha, committer, int(timestamp_str), parse_timezone(timezone_str)[0], message, ) def read_reflog(f): """Read reflog. Args: f: File-like object Returns: Iterator over Entry objects """ for line in f: yield parse_reflog_line(line) def drop_reflog_entry(f, index, rewrite=False) -> None: """Drop the specified reflog entry. Args: f: File-like object index: Reflog entry index (in Git reflog reverse 0-indexed order) rewrite: If a reflog entry's predecessor is removed, set its old SHA to the new SHA of the entry that now precedes it """ if index < 0: raise ValueError(f"Invalid reflog index {index}") log = [] offset = f.tell() for line in f: log.append((offset, parse_reflog_line(line))) offset = f.tell() inverse_index = len(log) - index - 1 write_offset = log[inverse_index][0] f.seek(write_offset) if index == 0: f.truncate() return del log[inverse_index] if rewrite and index > 0 and log: if inverse_index == 0: previous_new = ZERO_SHA else: previous_new = log[inverse_index - 1][1].new_sha offset, entry = log[inverse_index] log[inverse_index] = ( offset, Entry( previous_new, entry.new_sha, entry.committer, entry.timestamp, entry.timezone, entry.message, ), ) for _, entry in log[inverse_index:]: f.write( format_reflog_line( entry.old_sha, entry.new_sha, entry.committer, entry.timestamp, entry.timezone, entry.message, ) ) f.truncate() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/refs.py0000644000175100002000000011773414731042555015624 0ustar00runnerdocker# refs.py -- For dealing with git refs # Copyright (C) 2008-2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Ref handling.""" import os import warnings from collections.abc import Iterator from contextlib import suppress from typing import Any, Optional from .errors import PackedRefsException, RefFormatError from .file import GitFile, ensure_dir_exists from .objects import ZERO_SHA, ObjectID, Tag, git_line, valid_hexsha from .pack import ObjectContainer Ref = bytes HEADREF = b"HEAD" SYMREF = b"ref: " LOCAL_BRANCH_PREFIX = b"refs/heads/" LOCAL_TAG_PREFIX = b"refs/tags/" LOCAL_REMOTE_PREFIX = b"refs/remotes/" BAD_REF_CHARS = set(b"\177 ~^:?*[") PEELED_TAG_SUFFIX = b"^{}" # For backwards compatibility ANNOTATED_TAG_SUFFIX = PEELED_TAG_SUFFIX class SymrefLoop(Exception): """There is a loop between one or more symrefs.""" def __init__(self, ref, depth) -> None: self.ref = ref self.depth = depth def parse_symref_value(contents: bytes) -> bytes: """Parse a symref value. Args: contents: Contents to parse Returns: Destination """ if contents.startswith(SYMREF): return contents[len(SYMREF) :].rstrip(b"\r\n") raise ValueError(contents) def check_ref_format(refname: Ref) -> bool: """Check if a refname is correctly formatted. Implements all the same rules as git-check-ref-format[1]. [1] http://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html Args: refname: The refname to check Returns: True if refname is valid, False otherwise """ # These could be combined into one big expression, but are listed # separately to parallel [1]. if b"/." in refname or refname.startswith(b"."): return False if b"/" not in refname: return False if b".." in refname: return False for i, c in enumerate(refname): if ord(refname[i : i + 1]) < 0o40 or c in BAD_REF_CHARS: return False if refname[-1] in b"/.": return False if refname.endswith(b".lock"): return False if b"@{" in refname: return False if b"\\" in refname: return False return True class RefsContainer: """A container for refs.""" def __init__(self, logger=None) -> None: self._logger = logger def _log( self, ref, old_sha, new_sha, committer=None, timestamp=None, timezone=None, message=None, ) -> None: if self._logger is None: return if message is None: return self._logger(ref, old_sha, new_sha, committer, timestamp, timezone, message) def set_symbolic_ref( self, name, other, committer=None, timestamp=None, timezone=None, message=None, ) -> None: """Make a ref point at another ref. Args: name: Name of the ref to set other: Name of the ref to point at message: Optional message """ raise NotImplementedError(self.set_symbolic_ref) def get_packed_refs(self) -> dict[Ref, ObjectID]: """Get contents of the packed-refs file. Returns: Dictionary mapping ref names to SHA1s Note: Will return an empty dictionary when no packed-refs file is present. """ raise NotImplementedError(self.get_packed_refs) def add_packed_refs(self, new_refs: dict[Ref, Optional[ObjectID]]) -> None: """Add the given refs as packed refs. Args: new_refs: A mapping of ref names to targets; if a target is None that means remove the ref """ raise NotImplementedError(self.add_packed_refs) def get_peeled(self, name) -> Optional[ObjectID]: """Return the cached peeled value of a ref, if available. Args: name: Name of the ref to peel Returns: The peeled value of the ref. If the ref is known not point to a tag, this will be the SHA the ref refers to. If the ref may point to a tag, but no cached information is available, None is returned. """ return None def import_refs( self, base: Ref, other: dict[Ref, ObjectID], committer: Optional[bytes] = None, timestamp: Optional[bytes] = None, timezone: Optional[bytes] = None, message: Optional[bytes] = None, prune: bool = False, ) -> None: if prune: to_delete = set(self.subkeys(base)) else: to_delete = set() for name, value in other.items(): if value is None: to_delete.add(name) else: self.set_if_equals( b"/".join((base, name)), None, value, message=message ) if to_delete: try: to_delete.remove(name) except KeyError: pass for ref in to_delete: self.remove_if_equals(b"/".join((base, ref)), None, message=message) def allkeys(self) -> Iterator[Ref]: """All refs present in this container.""" raise NotImplementedError(self.allkeys) def __iter__(self): return iter(self.allkeys()) def keys(self, base=None): """Refs present in this container. Args: base: An optional base to return refs under. Returns: An unsorted set of valid refs in this container, including packed refs. """ if base is not None: return self.subkeys(base) else: return self.allkeys() def subkeys(self, base): """Refs present in this container under a base. Args: base: The base to return refs under. Returns: A set of valid refs in this container under the base; the base prefix is stripped from the ref names returned. """ keys = set() base_len = len(base) + 1 for refname in self.allkeys(): if refname.startswith(base): keys.add(refname[base_len:]) return keys def as_dict(self, base=None) -> dict[Ref, ObjectID]: """Return the contents of this container as a dictionary.""" ret = {} keys = self.keys(base) if base is None: base = b"" else: base = base.rstrip(b"/") for key in keys: try: ret[key] = self[(base + b"/" + key).strip(b"/")] except (SymrefLoop, KeyError): continue # Unable to resolve return ret def _check_refname(self, name) -> None: """Ensure a refname is valid and lives in refs or is HEAD. HEAD is not a valid refname according to git-check-ref-format, but this class needs to be able to touch HEAD. Also, check_ref_format expects refnames without the leading 'refs/', but this class requires that so it cannot touch anything outside the refs dir (or HEAD). Args: name: The name of the reference. Raises: KeyError: if a refname is not HEAD or is otherwise not valid. """ if name in (HEADREF, b"refs/stash"): return if not name.startswith(b"refs/") or not check_ref_format(name[5:]): raise RefFormatError(name) def read_ref(self, refname): """Read a reference without following any references. Args: refname: The name of the reference Returns: The contents of the ref file, or None if it does not exist. """ contents = self.read_loose_ref(refname) if not contents: contents = self.get_packed_refs().get(refname, None) return contents def read_loose_ref(self, name) -> bytes: """Read a loose reference and return its contents. Args: name: the refname to read Returns: The contents of the ref file, or None if it does not exist. """ raise NotImplementedError(self.read_loose_ref) def follow(self, name) -> tuple[list[bytes], bytes]: """Follow a reference name. Returns: a tuple of (refnames, sha), wheres refnames are the names of references in the chain """ contents = SYMREF + name depth = 0 refnames = [] while contents.startswith(SYMREF): refname = contents[len(SYMREF) :] refnames.append(refname) contents = self.read_ref(refname) if not contents: break depth += 1 if depth > 5: raise SymrefLoop(name, depth) return refnames, contents def __contains__(self, refname) -> bool: if self.read_ref(refname): return True return False def __getitem__(self, name) -> ObjectID: """Get the SHA1 for a reference name. This method follows all symbolic references. """ _, sha = self.follow(name) if sha is None: raise KeyError(name) return sha def set_if_equals( self, name, old_ref, new_ref, committer=None, timestamp=None, timezone=None, message=None, ) -> bool: """Set a refname to new_ref only if it currently equals old_ref. This method follows all symbolic references if applicable for the subclass, and can be used to perform an atomic compare-and-swap operation. Args: name: The refname to set. old_ref: The old sha the refname must refer to, or None to set unconditionally. new_ref: The new sha the refname will refer to. message: Message for reflog Returns: True if the set was successful, False otherwise. """ raise NotImplementedError(self.set_if_equals) def add_if_new( self, name, ref, committer=None, timestamp=None, timezone=None, message=None ) -> bool: """Add a new reference only if it does not already exist. Args: name: Ref name ref: Ref value """ raise NotImplementedError(self.add_if_new) def __setitem__(self, name, ref) -> None: """Set a reference name to point to the given SHA1. This method follows all symbolic references if applicable for the subclass. Note: This method unconditionally overwrites the contents of a reference. To update atomically only if the reference has not changed, use set_if_equals(). Args: name: The refname to set. ref: The new sha the refname will refer to. """ if not (valid_hexsha(ref) or ref.startswith(SYMREF)): raise ValueError(f"{ref!r} must be a valid sha (40 chars) or a symref") self.set_if_equals(name, None, ref) def remove_if_equals( self, name, old_ref, committer=None, timestamp=None, timezone=None, message=None, ) -> bool: """Remove a refname only if it currently equals old_ref. This method does not follow symbolic references, even if applicable for the subclass. It can be used to perform an atomic compare-and-delete operation. Args: name: The refname to delete. old_ref: The old sha the refname must refer to, or None to delete unconditionally. message: Message for reflog Returns: True if the delete was successful, False otherwise. """ raise NotImplementedError(self.remove_if_equals) def __delitem__(self, name) -> None: """Remove a refname. This method does not follow symbolic references, even if applicable for the subclass. Note: This method unconditionally deletes the contents of a reference. To delete atomically only if the reference has not changed, use remove_if_equals(). Args: name: The refname to delete. """ self.remove_if_equals(name, None) def get_symrefs(self): """Get a dict with all symrefs in this container. Returns: Dictionary mapping source ref to target ref """ ret = {} for src in self.allkeys(): try: dst = parse_symref_value(self.read_ref(src)) except ValueError: pass else: ret[src] = dst return ret class DictRefsContainer(RefsContainer): """RefsContainer backed by a simple dict. This container does not support symbolic or packed references and is not threadsafe. """ def __init__(self, refs, logger=None) -> None: super().__init__(logger=logger) self._refs = refs self._peeled: dict[bytes, ObjectID] = {} self._watchers: set[Any] = set() def allkeys(self): return self._refs.keys() def read_loose_ref(self, name): return self._refs.get(name, None) def get_packed_refs(self): return {} def _notify(self, ref, newsha) -> None: for watcher in self._watchers: watcher._notify((ref, newsha)) def set_symbolic_ref( self, name: Ref, other: Ref, committer=None, timestamp=None, timezone=None, message=None, ) -> None: old = self.follow(name)[-1] new = SYMREF + other self._refs[name] = new self._notify(name, new) self._log( name, old, new, committer=committer, timestamp=timestamp, timezone=timezone, message=message, ) def set_if_equals( self, name, old_ref, new_ref, committer=None, timestamp=None, timezone=None, message=None, ) -> bool: if old_ref is not None and self._refs.get(name, ZERO_SHA) != old_ref: return False realnames, _ = self.follow(name) for realname in realnames: self._check_refname(realname) old = self._refs.get(realname) self._refs[realname] = new_ref self._notify(realname, new_ref) self._log( realname, old, new_ref, committer=committer, timestamp=timestamp, timezone=timezone, message=message, ) return True def add_if_new( self, name: Ref, ref: ObjectID, committer=None, timestamp=None, timezone=None, message: Optional[bytes] = None, ) -> bool: if name in self._refs: return False self._refs[name] = ref self._notify(name, ref) self._log( name, None, ref, committer=committer, timestamp=timestamp, timezone=timezone, message=message, ) return True def remove_if_equals( self, name, old_ref, committer=None, timestamp=None, timezone=None, message=None, ) -> bool: if old_ref is not None and self._refs.get(name, ZERO_SHA) != old_ref: return False try: old = self._refs.pop(name) except KeyError: pass else: self._notify(name, None) self._log( name, old, None, committer=committer, timestamp=timestamp, timezone=timezone, message=message, ) return True def get_peeled(self, name): return self._peeled.get(name) def _update(self, refs) -> None: """Update multiple refs; intended only for testing.""" # TODO(dborowitz): replace this with a public function that uses # set_if_equal. for ref, sha in refs.items(): self.set_if_equals(ref, None, sha) def _update_peeled(self, peeled) -> None: """Update cached peeled refs; intended only for testing.""" self._peeled.update(peeled) class InfoRefsContainer(RefsContainer): """Refs container that reads refs from a info/refs file.""" def __init__(self, f) -> None: self._refs = {} self._peeled = {} refs = read_info_refs(f) (self._refs, self._peeled) = split_peeled_refs(refs) def allkeys(self): return self._refs.keys() def read_loose_ref(self, name): return self._refs.get(name, None) def get_packed_refs(self): return {} def get_peeled(self, name): try: return self._peeled[name] except KeyError: return self._refs[name] class DiskRefsContainer(RefsContainer): """Refs container that reads refs from disk.""" def __init__(self, path, worktree_path=None, logger=None) -> None: super().__init__(logger=logger) if getattr(path, "encode", None) is not None: path = os.fsencode(path) self.path = path if worktree_path is None: worktree_path = path if getattr(worktree_path, "encode", None) is not None: worktree_path = os.fsencode(worktree_path) self.worktree_path = worktree_path self._packed_refs = None self._peeled_refs = None def __repr__(self) -> str: return f"{self.__class__.__name__}({self.path!r})" def subkeys(self, base): subkeys = set() path = self.refpath(base) for root, unused_dirs, files in os.walk(path): dir = root[len(path) :] if os.path.sep != "/": dir = dir.replace(os.fsencode(os.path.sep), b"/") dir = dir.strip(b"/") for filename in files: refname = b"/".join(([dir] if dir else []) + [filename]) # check_ref_format requires at least one /, so we prepend the # base before calling it. if check_ref_format(base + b"/" + refname): subkeys.add(refname) for key in self.get_packed_refs(): if key.startswith(base): subkeys.add(key[len(base) :].strip(b"/")) return subkeys def allkeys(self): allkeys = set() if os.path.exists(self.refpath(HEADREF)): allkeys.add(HEADREF) path = self.refpath(b"") refspath = self.refpath(b"refs") for root, unused_dirs, files in os.walk(refspath): dir = root[len(path) :] if os.path.sep != "/": dir = dir.replace(os.fsencode(os.path.sep), b"/") for filename in files: refname = b"/".join([dir, filename]) if check_ref_format(refname): allkeys.add(refname) allkeys.update(self.get_packed_refs()) return allkeys def refpath(self, name): """Return the disk path of a ref.""" if os.path.sep != "/": name = name.replace(b"/", os.fsencode(os.path.sep)) # TODO: as the 'HEAD' reference is working tree specific, it # should actually not be a part of RefsContainer if name == HEADREF: return os.path.join(self.worktree_path, name) else: return os.path.join(self.path, name) def get_packed_refs(self): """Get contents of the packed-refs file. Returns: Dictionary mapping ref names to SHA1s Note: Will return an empty dictionary when no packed-refs file is present. """ # TODO: invalidate the cache on repacking if self._packed_refs is None: # set both to empty because we want _peeled_refs to be # None if and only if _packed_refs is also None. self._packed_refs = {} self._peeled_refs = {} path = os.path.join(self.path, b"packed-refs") try: f = GitFile(path, "rb") except FileNotFoundError: return {} with f: first_line = next(iter(f)).rstrip() if first_line.startswith(b"# pack-refs") and b" peeled" in first_line: for sha, name, peeled in read_packed_refs_with_peeled(f): self._packed_refs[name] = sha if peeled: self._peeled_refs[name] = peeled else: f.seek(0) for sha, name in read_packed_refs(f): self._packed_refs[name] = sha return self._packed_refs def add_packed_refs(self, new_refs: dict[Ref, Optional[ObjectID]]) -> None: """Add the given refs as packed refs. Args: new_refs: A mapping of ref names to targets; if a target is None that means remove the ref """ if not new_refs: return path = os.path.join(self.path, b"packed-refs") with GitFile(path, "wb") as f: # reread cached refs from disk, while holding the lock packed_refs = self.get_packed_refs().copy() for ref, target in new_refs.items(): # sanity check if ref == HEADREF: raise ValueError("cannot pack HEAD") # remove any loose refs pointing to this one -- please # note that this bypasses remove_if_equals as we don't # want to affect packed refs in here with suppress(OSError): os.remove(self.refpath(ref)) if target is not None: packed_refs[ref] = target else: packed_refs.pop(ref, None) write_packed_refs(f, packed_refs, self._peeled_refs) self._packed_refs = packed_refs def get_peeled(self, name): """Return the cached peeled value of a ref, if available. Args: name: Name of the ref to peel Returns: The peeled value of the ref. If the ref is known not point to a tag, this will be the SHA the ref refers to. If the ref may point to a tag, but no cached information is available, None is returned. """ self.get_packed_refs() if self._peeled_refs is None or name not in self._packed_refs: # No cache: no peeled refs were read, or this ref is loose return None if name in self._peeled_refs: return self._peeled_refs[name] else: # Known not peelable return self[name] def read_loose_ref(self, name): """Read a reference file and return its contents. If the reference file a symbolic reference, only read the first line of the file. Otherwise, only read the first 40 bytes. Args: name: the refname to read, relative to refpath Returns: The contents of the ref file, or None if the file does not exist. Raises: IOError: if any other error occurs """ filename = self.refpath(name) try: with GitFile(filename, "rb") as f: header = f.read(len(SYMREF)) if header == SYMREF: # Read only the first line return header + next(iter(f)).rstrip(b"\r\n") else: # Read only the first 40 bytes return header + f.read(40 - len(SYMREF)) except (OSError, UnicodeError): # don't assume anything specific about the error; in # particular, invalid or forbidden paths can raise weird # errors depending on the specific operating system return None def _remove_packed_ref(self, name) -> None: if self._packed_refs is None: return filename = os.path.join(self.path, b"packed-refs") # reread cached refs from disk, while holding the lock f = GitFile(filename, "wb") try: self._packed_refs = None self.get_packed_refs() if name not in self._packed_refs: return del self._packed_refs[name] with suppress(KeyError): del self._peeled_refs[name] write_packed_refs(f, self._packed_refs, self._peeled_refs) f.close() finally: f.abort() def set_symbolic_ref( self, name, other, committer=None, timestamp=None, timezone=None, message=None, ) -> None: """Make a ref point at another ref. Args: name: Name of the ref to set other: Name of the ref to point at message: Optional message to describe the change """ self._check_refname(name) self._check_refname(other) filename = self.refpath(name) f = GitFile(filename, "wb") try: f.write(SYMREF + other + b"\n") sha = self.follow(name)[-1] self._log( name, sha, sha, committer=committer, timestamp=timestamp, timezone=timezone, message=message, ) except BaseException: f.abort() raise else: f.close() def set_if_equals( self, name, old_ref, new_ref, committer=None, timestamp=None, timezone=None, message=None, ) -> bool: """Set a refname to new_ref only if it currently equals old_ref. This method follows all symbolic references, and can be used to perform an atomic compare-and-swap operation. Args: name: The refname to set. old_ref: The old sha the refname must refer to, or None to set unconditionally. new_ref: The new sha the refname will refer to. message: Set message for reflog Returns: True if the set was successful, False otherwise. """ self._check_refname(name) try: realnames, _ = self.follow(name) realname = realnames[-1] except (KeyError, IndexError, SymrefLoop): realname = name filename = self.refpath(realname) # make sure none of the ancestor folders is in packed refs probe_ref = os.path.dirname(realname) packed_refs = self.get_packed_refs() while probe_ref: if packed_refs.get(probe_ref, None) is not None: raise NotADirectoryError(filename) probe_ref = os.path.dirname(probe_ref) ensure_dir_exists(os.path.dirname(filename)) with GitFile(filename, "wb") as f: if old_ref is not None: try: # read again while holding the lock orig_ref = self.read_loose_ref(realname) if orig_ref is None: orig_ref = self.get_packed_refs().get(realname, ZERO_SHA) if orig_ref != old_ref: f.abort() return False except OSError: f.abort() raise try: f.write(new_ref + b"\n") except OSError: f.abort() raise self._log( realname, old_ref, new_ref, committer=committer, timestamp=timestamp, timezone=timezone, message=message, ) return True def add_if_new( self, name: bytes, ref: bytes, committer=None, timestamp=None, timezone=None, message: Optional[bytes] = None, ) -> bool: """Add a new reference only if it does not already exist. This method follows symrefs, and only ensures that the last ref in the chain does not exist. Args: name: The refname to set. ref: The new sha the refname will refer to. message: Optional message for reflog Returns: True if the add was successful, False otherwise. """ try: realnames, contents = self.follow(name) if contents is not None: return False realname = realnames[-1] except (KeyError, IndexError): realname = name self._check_refname(realname) filename = self.refpath(realname) ensure_dir_exists(os.path.dirname(filename)) with GitFile(filename, "wb") as f: if os.path.exists(filename) or name in self.get_packed_refs(): f.abort() return False try: f.write(ref + b"\n") except OSError: f.abort() raise else: self._log( name, None, ref, committer=committer, timestamp=timestamp, timezone=timezone, message=message, ) return True def remove_if_equals( self, name, old_ref, committer=None, timestamp=None, timezone=None, message=None, ) -> bool: """Remove a refname only if it currently equals old_ref. This method does not follow symbolic references. It can be used to perform an atomic compare-and-delete operation. Args: name: The refname to delete. old_ref: The old sha the refname must refer to, or None to delete unconditionally. message: Optional message Returns: True if the delete was successful, False otherwise. """ self._check_refname(name) filename = self.refpath(name) ensure_dir_exists(os.path.dirname(filename)) f = GitFile(filename, "wb") try: if old_ref is not None: orig_ref = self.read_loose_ref(name) if orig_ref is None: orig_ref = self.get_packed_refs().get(name, ZERO_SHA) if orig_ref != old_ref: return False # remove the reference file itself try: found = os.path.lexists(filename) except OSError: # may only be packed, or otherwise unstorable found = False if found: os.remove(filename) self._remove_packed_ref(name) self._log( name, old_ref, None, committer=committer, timestamp=timestamp, timezone=timezone, message=message, ) finally: # never write, we just wanted the lock f.abort() # outside of the lock, clean-up any parent directory that might now # be empty. this ensures that re-creating a reference of the same # name of what was previously a directory works as expected parent = name while True: try: parent, _ = parent.rsplit(b"/", 1) except ValueError: break if parent == b"refs": break parent_filename = self.refpath(parent) try: os.rmdir(parent_filename) except OSError: # this can be caused by the parent directory being # removed by another process, being not empty, etc. # in any case, this is non fatal because we already # removed the reference, just ignore it break return True def _split_ref_line(line): """Split a single ref line into a tuple of SHA1 and name.""" fields = line.rstrip(b"\n\r").split(b" ") if len(fields) != 2: raise PackedRefsException(f"invalid ref line {line!r}") sha, name = fields if not valid_hexsha(sha): raise PackedRefsException(f"Invalid hex sha {sha!r}") if not check_ref_format(name): raise PackedRefsException(f"invalid ref name {name!r}") return (sha, name) def read_packed_refs(f): """Read a packed refs file. Args: f: file-like object to read from Returns: Iterator over tuples with SHA1s and ref names. """ for line in f: if line.startswith(b"#"): # Comment continue if line.startswith(b"^"): raise PackedRefsException("found peeled ref in packed-refs without peeled") yield _split_ref_line(line) def read_packed_refs_with_peeled(f): """Read a packed refs file including peeled refs. Assumes the "# pack-refs with: peeled" line was already read. Yields tuples with ref names, SHA1s, and peeled SHA1s (or None). Args: f: file-like object to read from, seek'ed to the second line """ last = None for line in f: if line[0] == b"#": continue line = line.rstrip(b"\r\n") if line.startswith(b"^"): if not last: raise PackedRefsException("unexpected peeled ref line") if not valid_hexsha(line[1:]): raise PackedRefsException(f"Invalid hex sha {line[1:]!r}") sha, name = _split_ref_line(last) last = None yield (sha, name, line[1:]) else: if last: sha, name = _split_ref_line(last) yield (sha, name, None) last = line if last: sha, name = _split_ref_line(last) yield (sha, name, None) def write_packed_refs(f, packed_refs, peeled_refs=None) -> None: """Write a packed refs file. Args: f: empty file-like object to write to packed_refs: dict of refname to sha of packed refs to write peeled_refs: dict of refname to peeled value of sha """ if peeled_refs is None: peeled_refs = {} else: f.write(b"# pack-refs with: peeled\n") for refname in sorted(packed_refs.keys()): f.write(git_line(packed_refs[refname], refname)) if refname in peeled_refs: f.write(b"^" + peeled_refs[refname] + b"\n") def read_info_refs(f): ret = {} for line in f.readlines(): (sha, name) = line.rstrip(b"\r\n").split(b"\t", 1) ret[name] = sha return ret def write_info_refs(refs, store: ObjectContainer): """Generate info refs.""" # TODO: Avoid recursive import :( from .object_store import peel_sha for name, sha in sorted(refs.items()): # get_refs() includes HEAD as a special case, but we don't want to # advertise it if name == HEADREF: continue try: o = store[sha] except KeyError: continue unpeeled, peeled = peel_sha(store, sha) yield o.id + b"\t" + name + b"\n" if o.id != peeled.id: yield peeled.id + b"\t" + name + PEELED_TAG_SUFFIX + b"\n" def is_local_branch(x): return x.startswith(LOCAL_BRANCH_PREFIX) def strip_peeled_refs(refs): """Remove all peeled refs.""" return { ref: sha for (ref, sha) in refs.items() if not ref.endswith(PEELED_TAG_SUFFIX) } def split_peeled_refs(refs): """Split peeled refs from regular refs.""" peeled = {} regular = {} for ref, sha in refs.items(): if ref.endswith(PEELED_TAG_SUFFIX): peeled[ref[: -len(PEELED_TAG_SUFFIX)]] = sha else: regular[ref] = sha return regular, peeled def _set_origin_head(refs, origin, origin_head) -> None: # set refs/remotes/origin/HEAD origin_base = b"refs/remotes/" + origin + b"/" if origin_head and origin_head.startswith(LOCAL_BRANCH_PREFIX): origin_ref = origin_base + HEADREF target_ref = origin_base + origin_head[len(LOCAL_BRANCH_PREFIX) :] if target_ref in refs: refs.set_symbolic_ref(origin_ref, target_ref) def _set_default_branch( refs: RefsContainer, origin: bytes, origin_head: Optional[bytes], branch: bytes, ref_message: Optional[bytes], ) -> bytes: """Set the default branch.""" origin_base = b"refs/remotes/" + origin + b"/" if branch: origin_ref = origin_base + branch if origin_ref in refs: local_ref = LOCAL_BRANCH_PREFIX + branch refs.add_if_new(local_ref, refs[origin_ref], ref_message) head_ref = local_ref elif LOCAL_TAG_PREFIX + branch in refs: head_ref = LOCAL_TAG_PREFIX + branch else: raise ValueError(f"{os.fsencode(branch)!r} is not a valid branch or tag") elif origin_head: head_ref = origin_head if origin_head.startswith(LOCAL_BRANCH_PREFIX): origin_ref = origin_base + origin_head[len(LOCAL_BRANCH_PREFIX) :] else: origin_ref = origin_head try: refs.add_if_new(head_ref, refs[origin_ref], ref_message) except KeyError: pass else: raise ValueError("neither origin_head nor branch are provided") return head_ref def _set_head(refs, head_ref, ref_message): if head_ref.startswith(LOCAL_TAG_PREFIX): # detach HEAD at specified tag head = refs[head_ref] if isinstance(head, Tag): _cls, obj = head.object head = obj.get_object(obj).id del refs[HEADREF] refs.set_if_equals(HEADREF, None, head, message=ref_message) else: # set HEAD to specific branch try: head = refs[head_ref] refs.set_symbolic_ref(HEADREF, head_ref) refs.set_if_equals(HEADREF, None, head, message=ref_message) except KeyError: head = None return head def _import_remote_refs( refs_container: RefsContainer, remote_name: str, refs: dict[str, str], message: Optional[bytes] = None, prune: bool = False, prune_tags: bool = False, ) -> None: stripped_refs = strip_peeled_refs(refs) branches = { n[len(LOCAL_BRANCH_PREFIX) :]: v for (n, v) in stripped_refs.items() if n.startswith(LOCAL_BRANCH_PREFIX) } refs_container.import_refs( b"refs/remotes/" + remote_name.encode(), branches, message=message, prune=prune, ) tags = { n[len(LOCAL_TAG_PREFIX) :]: v for (n, v) in stripped_refs.items() if n.startswith(LOCAL_TAG_PREFIX) and not n.endswith(PEELED_TAG_SUFFIX) } refs_container.import_refs( LOCAL_TAG_PREFIX, tags, message=message, prune=prune_tags ) def serialize_refs(store, refs): # TODO: Avoid recursive import :( from .object_store import peel_sha ret = {} for ref, sha in refs.items(): try: unpeeled, peeled = peel_sha(store, sha) except KeyError: warnings.warn( "ref {} points at non-present sha {}".format( ref.decode("utf-8", "replace"), sha.decode("ascii") ), UserWarning, ) continue else: if isinstance(unpeeled, Tag): ret[ref + PEELED_TAG_SUFFIX] = peeled.id ret[ref] = unpeeled.id return ret ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/repo.py0000644000175100002000000017505114731042555015626 0ustar00runnerdocker# repo.py -- For dealing with git repositories. # Copyright (C) 2007 James Westby # Copyright (C) 2008-2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Repository access. This module contains the base class for git repositories (BaseRepo) and an implementation which uses a repository on local disk (Repo). """ import os import stat import sys import time import warnings from collections.abc import Iterable from io import BytesIO from typing import ( TYPE_CHECKING, Any, BinaryIO, Callable, Optional, Union, ) if TYPE_CHECKING: # There are no circular imports here, but we try to defer imports as long # as possible to reduce start-up time for anything that doesn't need # these imports. from .config import ConfigFile, StackedConfig from .index import Index from .errors import ( CommitError, HookError, NoIndexPresent, NotBlobError, NotCommitError, NotGitRepository, NotTagError, NotTreeError, RefFormatError, ) from .file import GitFile from .hooks import ( CommitMsgShellHook, Hook, PostCommitShellHook, PostReceiveShellHook, PreCommitShellHook, ) from .line_ending import BlobNormalizer, TreeBlobNormalizer from .object_store import ( DiskObjectStore, MemoryObjectStore, MissingObjectFinder, ObjectStoreGraphWalker, PackBasedObjectStore, peel_sha, ) from .objects import ( Blob, Commit, ObjectID, ShaFile, Tag, Tree, check_hexsha, valid_hexsha, ) from .pack import generate_unpacked_objects from .refs import ( ANNOTATED_TAG_SUFFIX, # noqa: F401 LOCAL_BRANCH_PREFIX, LOCAL_TAG_PREFIX, # noqa: F401 SYMREF, # noqa: F401 DictRefsContainer, DiskRefsContainer, InfoRefsContainer, # noqa: F401 Ref, RefsContainer, _set_default_branch, _set_head, _set_origin_head, check_ref_format, # noqa: F401 read_packed_refs, # noqa: F401 read_packed_refs_with_peeled, # noqa: F401 serialize_refs, write_packed_refs, # noqa: F401 ) CONTROLDIR = ".git" OBJECTDIR = "objects" REFSDIR = "refs" REFSDIR_TAGS = "tags" REFSDIR_HEADS = "heads" INDEX_FILENAME = "index" COMMONDIR = "commondir" GITDIR = "gitdir" WORKTREES = "worktrees" BASE_DIRECTORIES = [ ["branches"], [REFSDIR], [REFSDIR, REFSDIR_TAGS], [REFSDIR, REFSDIR_HEADS], ["hooks"], ["info"], ] DEFAULT_BRANCH = b"master" class InvalidUserIdentity(Exception): """User identity is not of the format 'user '.""" def __init__(self, identity) -> None: self.identity = identity class DefaultIdentityNotFound(Exception): """Default identity could not be determined.""" # TODO(jelmer): Cache? def _get_default_identity() -> tuple[str, str]: import socket for name in ("LOGNAME", "USER", "LNAME", "USERNAME"): username = os.environ.get(name) if username: break else: username = None try: import pwd except ImportError: fullname = None else: try: entry = pwd.getpwuid(os.getuid()) # type: ignore except KeyError: fullname = None else: if getattr(entry, "gecos", None): fullname = entry.pw_gecos.split(",")[0] else: fullname = None if username is None: username = entry.pw_name if not fullname: if username is None: raise DefaultIdentityNotFound("no username found") fullname = username email = os.environ.get("EMAIL") if email is None: if username is None: raise DefaultIdentityNotFound("no username found") email = f"{username}@{socket.gethostname()}" return (fullname, email) def get_user_identity(config: "StackedConfig", kind: Optional[str] = None) -> bytes: """Determine the identity to use for new commits. If kind is set, this first checks GIT_${KIND}_NAME and GIT_${KIND}_EMAIL. If those variables are not set, then it will fall back to reading the user.name and user.email settings from the specified configuration. If that also fails, then it will fall back to using the current users' identity as obtained from the host system (e.g. the gecos field, $EMAIL, $USER@$(hostname -f). Args: kind: Optional kind to return identity for, usually either "AUTHOR" or "COMMITTER". Returns: A user identity """ user: Optional[bytes] = None email: Optional[bytes] = None if kind: user_uc = os.environ.get("GIT_" + kind + "_NAME") if user_uc is not None: user = user_uc.encode("utf-8") email_uc = os.environ.get("GIT_" + kind + "_EMAIL") if email_uc is not None: email = email_uc.encode("utf-8") if user is None: try: user = config.get(("user",), "name") except KeyError: user = None if email is None: try: email = config.get(("user",), "email") except KeyError: email = None default_user, default_email = _get_default_identity() if user is None: user = default_user.encode("utf-8") if email is None: email = default_email.encode("utf-8") if email.startswith(b"<") and email.endswith(b">"): email = email[1:-1] return user + b" <" + email + b">" def check_user_identity(identity) -> None: """Verify that a user identity is formatted correctly. Args: identity: User identity bytestring Raises: InvalidUserIdentity: Raised when identity is invalid """ try: fst, snd = identity.split(b" <", 1) except ValueError as exc: raise InvalidUserIdentity(identity) from exc if b">" not in snd: raise InvalidUserIdentity(identity) if b"\0" in identity or b"\n" in identity: raise InvalidUserIdentity(identity) def parse_graftpoints( graftpoints: Iterable[bytes], ) -> dict[bytes, list[bytes]]: """Convert a list of graftpoints into a dict. Args: graftpoints: Iterator of graftpoint lines Each line is formatted as: []* Resulting dictionary is: : [*] https://git.wiki.kernel.org/index.php/GraftPoint """ grafts = {} for line in graftpoints: raw_graft = line.split(None, 1) commit = raw_graft[0] if len(raw_graft) == 2: parents = raw_graft[1].split() else: parents = [] for sha in [commit, *parents]: check_hexsha(sha, "Invalid graftpoint") grafts[commit] = parents return grafts def serialize_graftpoints(graftpoints: dict[bytes, list[bytes]]) -> bytes: """Convert a dictionary of grafts into string. The graft dictionary is: : [*] Each line is formatted as: []* https://git.wiki.kernel.org/index.php/GraftPoint """ graft_lines = [] for commit, parents in graftpoints.items(): if parents: graft_lines.append(commit + b" " + b" ".join(parents)) else: graft_lines.append(commit) return b"\n".join(graft_lines) def _set_filesystem_hidden(path) -> None: """Mark path as to be hidden if supported by platform and filesystem. On win32 uses SetFileAttributesW api: """ if sys.platform == "win32": import ctypes from ctypes.wintypes import BOOL, DWORD, LPCWSTR FILE_ATTRIBUTE_HIDDEN = 2 SetFileAttributesW = ctypes.WINFUNCTYPE(BOOL, LPCWSTR, DWORD)( ("SetFileAttributesW", ctypes.windll.kernel32) ) if isinstance(path, bytes): path = os.fsdecode(path) if not SetFileAttributesW(path, FILE_ATTRIBUTE_HIDDEN): pass # Could raise or log `ctypes.WinError()` here # Could implement other platform specific filesystem hiding here class ParentsProvider: def __init__(self, store, grafts={}, shallows=[]) -> None: self.store = store self.grafts = grafts self.shallows = set(shallows) def get_parents(self, commit_id, commit=None): try: return self.grafts[commit_id] except KeyError: pass if commit_id in self.shallows: return [] if commit is None: commit = self.store[commit_id] return commit.parents class BaseRepo: """Base class for a git repository. This base class is meant to be used for Repository implementations that e.g. work on top of a different transport than a standard filesystem path. Attributes: object_store: Dictionary-like object for accessing the objects refs: Dictionary-like object with the refs in this repository """ def __init__(self, object_store: PackBasedObjectStore, refs: RefsContainer) -> None: """Open a repository. This shouldn't be called directly, but rather through one of the base classes, such as MemoryRepo or Repo. Args: object_store: Object store to use refs: Refs container to use """ self.object_store = object_store self.refs = refs self._graftpoints: dict[bytes, list[bytes]] = {} self.hooks: dict[str, Hook] = {} def _determine_file_mode(self) -> bool: """Probe the file-system to determine whether permissions can be trusted. Returns: True if permissions can be trusted, False otherwise. """ raise NotImplementedError(self._determine_file_mode) def _determine_symlinks(self) -> bool: """Probe the filesystem to determine whether symlinks can be created. Returns: True if symlinks can be created, False otherwise. """ # For now, just mimic the old behaviour return sys.platform != "win32" def _init_files(self, bare: bool, symlinks: Optional[bool] = None) -> None: """Initialize a default set of named files.""" from .config import ConfigFile self._put_named_file("description", b"Unnamed repository") f = BytesIO() cf = ConfigFile() cf.set("core", "repositoryformatversion", "0") if self._determine_file_mode(): cf.set("core", "filemode", True) else: cf.set("core", "filemode", False) if symlinks is None and not bare: symlinks = self._determine_symlinks() if symlinks is False: cf.set("core", "symlinks", symlinks) cf.set("core", "bare", bare) cf.set("core", "logallrefupdates", True) cf.write_to_file(f) self._put_named_file("config", f.getvalue()) self._put_named_file(os.path.join("info", "exclude"), b"") def get_named_file(self, path: str) -> Optional[BinaryIO]: """Get a file from the control dir with a specific name. Although the filename should be interpreted as a filename relative to the control dir in a disk-based Repo, the object returned need not be pointing to a file in that location. Args: path: The path to the file, relative to the control dir. Returns: An open file object, or None if the file does not exist. """ raise NotImplementedError(self.get_named_file) def _put_named_file(self, path: str, contents: bytes) -> None: """Write a file to the control dir with the given name and contents. Args: path: The path to the file, relative to the control dir. contents: A string to write to the file. """ raise NotImplementedError(self._put_named_file) def _del_named_file(self, path: str) -> None: """Delete a file in the control directory with the given name.""" raise NotImplementedError(self._del_named_file) def open_index(self) -> "Index": """Open the index for this repository. Raises: NoIndexPresent: If no index is present Returns: The matching `Index` """ raise NotImplementedError(self.open_index) def fetch(self, target, determine_wants=None, progress=None, depth=None): """Fetch objects into another repository. Args: target: The target repository determine_wants: Optional function to determine what refs to fetch. progress: Optional progress function depth: Optional shallow fetch depth Returns: The local refs """ if determine_wants is None: determine_wants = target.object_store.determine_wants_all count, pack_data = self.fetch_pack_data( determine_wants, target.get_graph_walker(), progress=progress, depth=depth, ) target.object_store.add_pack_data(count, pack_data, progress) return self.get_refs() def fetch_pack_data( self, determine_wants, graph_walker, progress, get_tagged=None, depth=None, ): """Fetch the pack data required for a set of revisions. Args: determine_wants: Function that takes a dictionary with heads and returns the list of heads to fetch. graph_walker: Object that can iterate over the list of revisions to fetch and has an "ack" method that will be called to acknowledge that a revision is present. progress: Simple progress function that will be called with updated progress strings. get_tagged: Function that returns a dict of pointed-to sha -> tag sha for including tags. depth: Shallow fetch depth Returns: count and iterator over pack data """ missing_objects = self.find_missing_objects( determine_wants, graph_walker, progress, get_tagged, depth=depth ) remote_has = missing_objects.get_remote_has() object_ids = list(missing_objects) return len(object_ids), generate_unpacked_objects( self.object_store, object_ids, progress=progress, other_haves=remote_has ) def find_missing_objects( self, determine_wants, graph_walker, progress, get_tagged=None, depth=None, ) -> Optional[MissingObjectFinder]: """Fetch the missing objects required for a set of revisions. Args: determine_wants: Function that takes a dictionary with heads and returns the list of heads to fetch. graph_walker: Object that can iterate over the list of revisions to fetch and has an "ack" method that will be called to acknowledge that a revision is present. progress: Simple progress function that will be called with updated progress strings. get_tagged: Function that returns a dict of pointed-to sha -> tag sha for including tags. depth: Shallow fetch depth Returns: iterator over objects, with __len__ implemented """ if depth not in (None, 0): raise NotImplementedError("depth not supported yet") refs = serialize_refs(self.object_store, self.get_refs()) wants = determine_wants(refs) if not isinstance(wants, list): raise TypeError("determine_wants() did not return a list") shallows: frozenset[ObjectID] = getattr(graph_walker, "shallow", frozenset()) unshallows: frozenset[ObjectID] = getattr( graph_walker, "unshallow", frozenset() ) if wants == []: # TODO(dborowitz): find a way to short-circuit that doesn't change # this interface. if shallows or unshallows: # Do not send a pack in shallow short-circuit path return None class DummyMissingObjectFinder: def get_remote_has(self) -> None: return None def __len__(self) -> int: return 0 def __iter__(self): yield from [] return DummyMissingObjectFinder() # type: ignore # If the graph walker is set up with an implementation that can # ACK/NAK to the wire, it will write data to the client through # this call as a side-effect. haves = self.object_store.find_common_revisions(graph_walker) # Deal with shallow requests separately because the haves do # not reflect what objects are missing if shallows or unshallows: # TODO: filter the haves commits from iter_shas. the specific # commits aren't missing. haves = [] parents_provider = ParentsProvider(self.object_store, shallows=shallows) def get_parents(commit): return parents_provider.get_parents(commit.id, commit) return MissingObjectFinder( self.object_store, haves=haves, wants=wants, shallow=self.get_shallow(), progress=progress, get_tagged=get_tagged, get_parents=get_parents, ) def generate_pack_data( self, have: list[ObjectID], want: list[ObjectID], progress: Optional[Callable[[str], None]] = None, ofs_delta: Optional[bool] = None, ): """Generate pack data objects for a set of wants/haves. Args: have: List of SHA1s of objects that should not be sent want: List of SHA1s of objects that should be sent ofs_delta: Whether OFS deltas can be included progress: Optional progress reporting method """ return self.object_store.generate_pack_data( have, want, shallow=self.get_shallow(), progress=progress, ofs_delta=ofs_delta, ) def get_graph_walker( self, heads: Optional[list[ObjectID]] = None ) -> ObjectStoreGraphWalker: """Retrieve a graph walker. A graph walker is used by a remote repository (or proxy) to find out which objects are present in this repository. Args: heads: Repository heads to use (optional) Returns: A graph walker object """ if heads is None: heads = [ sha for sha in self.refs.as_dict(b"refs/heads").values() if sha in self.object_store ] parents_provider = ParentsProvider(self.object_store) return ObjectStoreGraphWalker( heads, parents_provider.get_parents, shallow=self.get_shallow() ) def get_refs(self) -> dict[bytes, bytes]: """Get dictionary with all refs. Returns: A ``dict`` mapping ref names to SHA1s """ return self.refs.as_dict() def head(self) -> bytes: """Return the SHA1 pointed at by HEAD.""" return self.refs[b"HEAD"] def _get_object(self, sha, cls): assert len(sha) in (20, 40) ret = self.get_object(sha) if not isinstance(ret, cls): if cls is Commit: raise NotCommitError(ret) elif cls is Blob: raise NotBlobError(ret) elif cls is Tree: raise NotTreeError(ret) elif cls is Tag: raise NotTagError(ret) else: raise Exception(f"Type invalid: {ret.type_name!r} != {cls.type_name!r}") return ret def get_object(self, sha: bytes) -> ShaFile: """Retrieve the object with the specified SHA. Args: sha: SHA to retrieve Returns: A ShaFile object Raises: KeyError: when the object can not be found """ return self.object_store[sha] def parents_provider(self) -> ParentsProvider: return ParentsProvider( self.object_store, grafts=self._graftpoints, shallows=self.get_shallow(), ) def get_parents(self, sha: bytes, commit: Optional[Commit] = None) -> list[bytes]: """Retrieve the parents of a specific commit. If the specific commit is a graftpoint, the graft parents will be returned instead. Args: sha: SHA of the commit for which to retrieve the parents commit: Optional commit matching the sha Returns: List of parents """ return self.parents_provider().get_parents(sha, commit) def get_config(self) -> "ConfigFile": """Retrieve the config object. Returns: `ConfigFile` object for the ``.git/config`` file. """ raise NotImplementedError(self.get_config) def get_worktree_config(self) -> "ConfigFile": """Retrieve the worktree config object.""" raise NotImplementedError(self.get_worktree_config) def get_description(self) -> Optional[str]: """Retrieve the description for this repository. Returns: String with the description of the repository as set by the user. """ raise NotImplementedError(self.get_description) def set_description(self, description) -> None: """Set the description for this repository. Args: description: Text to set as description for this repository. """ raise NotImplementedError(self.set_description) def get_config_stack(self) -> "StackedConfig": """Return a config stack for this repository. This stack accesses the configuration for both this repository itself (.git/config) and the global configuration, which usually lives in ~/.gitconfig. Returns: `Config` instance for this repository """ from .config import ConfigFile, StackedConfig local_config = self.get_config() backends: list[ConfigFile] = [local_config] if local_config.get_boolean((b"extensions",), b"worktreeconfig", False): backends.append(self.get_worktree_config()) backends += StackedConfig.default_backends() return StackedConfig(backends, writable=local_config) def get_shallow(self) -> set[ObjectID]: """Get the set of shallow commits. Returns: Set of shallow commits. """ f = self.get_named_file("shallow") if f is None: return set() with f: return {line.strip() for line in f} def update_shallow(self, new_shallow, new_unshallow) -> None: """Update the list of shallow objects. Args: new_shallow: Newly shallow objects new_unshallow: Newly no longer shallow objects """ shallow = self.get_shallow() if new_shallow: shallow.update(new_shallow) if new_unshallow: shallow.difference_update(new_unshallow) if shallow: self._put_named_file("shallow", b"".join([sha + b"\n" for sha in shallow])) else: self._del_named_file("shallow") def get_peeled(self, ref: Ref) -> ObjectID: """Get the peeled value of a ref. Args: ref: The refname to peel. Returns: The fully-peeled SHA1 of a tag object, after peeling all intermediate tags; if the original ref does not point to a tag, this will equal the original SHA1. """ cached = self.refs.get_peeled(ref) if cached is not None: return cached return peel_sha(self.object_store, self.refs[ref])[1].id def get_walker(self, include: Optional[list[bytes]] = None, *args, **kwargs): """Obtain a walker for this repository. Args: include: Iterable of SHAs of commits to include along with their ancestors. Defaults to [HEAD] exclude: Iterable of SHAs of commits to exclude along with their ancestors, overriding includes. order: ORDER_* constant specifying the order of results. Anything other than ORDER_DATE may result in O(n) memory usage. reverse: If True, reverse the order of output, requiring O(n) memory. max_entries: The maximum number of entries to yield, or None for no limit. paths: Iterable of file or subtree paths to show entries for. rename_detector: diff.RenameDetector object for detecting renames. follow: If True, follow path across renames/copies. Forces a default rename_detector. since: Timestamp to list commits after. until: Timestamp to list commits before. queue_cls: A class to use for a queue of commits, supporting the iterator protocol. The constructor takes a single argument, the Walker. Returns: A `Walker` object """ from .walk import Walker if include is None: include = [self.head()] kwargs["get_parents"] = lambda commit: self.get_parents(commit.id, commit) return Walker(self.object_store, include, *args, **kwargs) def __getitem__(self, name: Union[ObjectID, Ref]): """Retrieve a Git object by SHA1 or ref. Args: name: A Git object SHA1 or a ref name Returns: A `ShaFile` object, such as a Commit or Blob Raises: KeyError: when the specified ref or object does not exist """ if not isinstance(name, bytes): raise TypeError(f"'name' must be bytestring, not {type(name).__name__:.80}") if len(name) in (20, 40): try: return self.object_store[name] except (KeyError, ValueError): pass try: return self.object_store[self.refs[name]] except RefFormatError as exc: raise KeyError(name) from exc def __contains__(self, name: bytes) -> bool: """Check if a specific Git object or ref is present. Args: name: Git object SHA1 or ref name """ if len(name) == 20 or (len(name) == 40 and valid_hexsha(name)): return name in self.object_store or name in self.refs else: return name in self.refs def __setitem__(self, name: bytes, value: Union[ShaFile, bytes]) -> None: """Set a ref. Args: name: ref name value: Ref value - either a ShaFile object, or a hex sha """ if name.startswith(b"refs/") or name == b"HEAD": if isinstance(value, ShaFile): self.refs[name] = value.id elif isinstance(value, bytes): self.refs[name] = value else: raise TypeError(value) else: raise ValueError(name) def __delitem__(self, name: bytes) -> None: """Remove a ref. Args: name: Name of the ref to remove """ if name.startswith(b"refs/") or name == b"HEAD": del self.refs[name] else: raise ValueError(name) def _get_user_identity( self, config: "StackedConfig", kind: Optional[str] = None ) -> bytes: """Determine the identity to use for new commits.""" warnings.warn( "use get_user_identity() rather than Repo._get_user_identity", DeprecationWarning, ) return get_user_identity(config) def _add_graftpoints(self, updated_graftpoints: dict[bytes, list[bytes]]) -> None: """Add or modify graftpoints. Args: updated_graftpoints: Dict of commit shas to list of parent shas """ # Simple validation for commit, parents in updated_graftpoints.items(): for sha in [commit, *parents]: check_hexsha(sha, "Invalid graftpoint") self._graftpoints.update(updated_graftpoints) def _remove_graftpoints(self, to_remove: list[bytes] = []) -> None: """Remove graftpoints. Args: to_remove: List of commit shas """ for sha in to_remove: del self._graftpoints[sha] def _read_heads(self, name): f = self.get_named_file(name) if f is None: return [] with f: return [line.strip() for line in f.readlines() if line.strip()] def do_commit( self, message: Optional[bytes] = None, committer: Optional[bytes] = None, author: Optional[bytes] = None, commit_timestamp=None, commit_timezone=None, author_timestamp=None, author_timezone=None, tree: Optional[ObjectID] = None, encoding: Optional[bytes] = None, ref: Ref = b"HEAD", merge_heads: Optional[list[ObjectID]] = None, no_verify: bool = False, sign: bool = False, ): """Create a new commit. If not specified, committer and author default to get_user_identity(..., 'COMMITTER') and get_user_identity(..., 'AUTHOR') respectively. Args: message: Commit message committer: Committer fullname author: Author fullname commit_timestamp: Commit timestamp (defaults to now) commit_timezone: Commit timestamp timezone (defaults to GMT) author_timestamp: Author timestamp (defaults to commit timestamp) author_timezone: Author timestamp timezone (defaults to commit timestamp timezone) tree: SHA1 of the tree root to use (if not specified the current index will be committed). encoding: Encoding ref: Optional ref to commit to (defaults to current branch) merge_heads: Merge heads (defaults to .git/MERGE_HEAD) no_verify: Skip pre-commit and commit-msg hooks sign: GPG Sign the commit (bool, defaults to False, pass True to use default GPG key, pass a str containing Key ID to use a specific GPG key) Returns: New commit SHA1 """ try: if not no_verify: self.hooks["pre-commit"].execute() except HookError as exc: raise CommitError(exc) from exc except KeyError: # no hook defined, silent fallthrough pass c = Commit() if tree is None: index = self.open_index() c.tree = index.commit(self.object_store) else: if len(tree) != 40: raise ValueError("tree must be a 40-byte hex sha string") c.tree = tree config = self.get_config_stack() if merge_heads is None: merge_heads = self._read_heads("MERGE_HEAD") if committer is None: committer = get_user_identity(config, kind="COMMITTER") check_user_identity(committer) c.committer = committer if commit_timestamp is None: # FIXME: Support GIT_COMMITTER_DATE environment variable commit_timestamp = time.time() c.commit_time = int(commit_timestamp) if commit_timezone is None: # FIXME: Use current user timezone rather than UTC commit_timezone = 0 c.commit_timezone = commit_timezone if author is None: author = get_user_identity(config, kind="AUTHOR") c.author = author check_user_identity(author) if author_timestamp is None: # FIXME: Support GIT_AUTHOR_DATE environment variable author_timestamp = commit_timestamp c.author_time = int(author_timestamp) if author_timezone is None: author_timezone = commit_timezone c.author_timezone = author_timezone if encoding is None: try: encoding = config.get(("i18n",), "commitEncoding") except KeyError: pass # No dice if encoding is not None: c.encoding = encoding if message is None: # FIXME: Try to read commit message from .git/MERGE_MSG raise ValueError("No commit message specified") try: if no_verify: c.message = message else: c.message = self.hooks["commit-msg"].execute(message) if c.message is None: c.message = message except HookError as exc: raise CommitError(exc) from exc except KeyError: # no hook defined, message not modified c.message = message keyid = sign if isinstance(sign, str) else None if ref is None: # Create a dangling commit c.parents = merge_heads if sign: c.sign(keyid) self.object_store.add_object(c) else: try: old_head = self.refs[ref] c.parents = [old_head, *merge_heads] if sign: c.sign(keyid) self.object_store.add_object(c) ok = self.refs.set_if_equals( ref, old_head, c.id, message=b"commit: " + message, committer=committer, timestamp=commit_timestamp, timezone=commit_timezone, ) except KeyError: c.parents = merge_heads if sign: c.sign(keyid) self.object_store.add_object(c) ok = self.refs.add_if_new( ref, c.id, message=b"commit: " + message, committer=committer, timestamp=commit_timestamp, timezone=commit_timezone, ) if not ok: # Fail if the atomic compare-and-swap failed, leaving the # commit and all its objects as garbage. raise CommitError(f"{ref!r} changed during commit") self._del_named_file("MERGE_HEAD") try: self.hooks["post-commit"].execute() except HookError as e: # silent failure warnings.warn(f"post-commit hook failed: {e}", UserWarning) except KeyError: # no hook defined, silent fallthrough pass return c.id def read_gitfile(f): """Read a ``.git`` file. The first line of the file should start with "gitdir: " Args: f: File-like object to read from Returns: A path """ cs = f.read() if not cs.startswith("gitdir: "): raise ValueError("Expected file to start with 'gitdir: '") return cs[len("gitdir: ") :].rstrip("\n") class UnsupportedVersion(Exception): """Unsupported repository version.""" def __init__(self, version) -> None: self.version = version class UnsupportedExtension(Exception): """Unsupported repository extension.""" def __init__(self, extension) -> None: self.extension = extension class Repo(BaseRepo): """A git repository backed by local disk. To open an existing repository, call the constructor with the path of the repository. To create a new repository, use the Repo.init class method. Note that a repository object may hold on to resources such as file handles for performance reasons; call .close() to free up those resources. Attributes: path: Path to the working copy (if it exists) or repository control directory (if the repository is bare) bare: Whether this is a bare repository """ path: str bare: bool def __init__( self, root: str, object_store: Optional[PackBasedObjectStore] = None, bare: Optional[bool] = None, ) -> None: hidden_path = os.path.join(root, CONTROLDIR) if bare is None: if os.path.isfile(hidden_path) or os.path.isdir( os.path.join(hidden_path, OBJECTDIR) ): bare = False elif os.path.isdir(os.path.join(root, OBJECTDIR)) and os.path.isdir( os.path.join(root, REFSDIR) ): bare = True else: raise NotGitRepository( "No git repository was found at {path}".format(**dict(path=root)) ) self.bare = bare if bare is False: if os.path.isfile(hidden_path): with open(hidden_path) as f: path = read_gitfile(f) self._controldir = os.path.join(root, path) else: self._controldir = hidden_path else: self._controldir = root commondir = self.get_named_file(COMMONDIR) if commondir is not None: with commondir: self._commondir = os.path.join( self.controldir(), os.fsdecode(commondir.read().rstrip(b"\r\n")), ) else: self._commondir = self._controldir self.path = root config = self.get_config() try: repository_format_version = config.get("core", "repositoryformatversion") format_version = ( 0 if repository_format_version is None else int(repository_format_version) ) except KeyError: format_version = 0 if format_version not in (0, 1): raise UnsupportedVersion(format_version) for extension, _value in config.items((b"extensions",)): if extension.lower() not in (b"worktreeconfig",): raise UnsupportedExtension(extension) if object_store is None: object_store = DiskObjectStore.from_config( os.path.join(self.commondir(), OBJECTDIR), config ) refs = DiskRefsContainer( self.commondir(), self._controldir, logger=self._write_reflog ) BaseRepo.__init__(self, object_store, refs) self._graftpoints = {} graft_file = self.get_named_file( os.path.join("info", "grafts"), basedir=self.commondir() ) if graft_file: with graft_file: self._graftpoints.update(parse_graftpoints(graft_file)) graft_file = self.get_named_file("shallow", basedir=self.commondir()) if graft_file: with graft_file: self._graftpoints.update(parse_graftpoints(graft_file)) self.hooks["pre-commit"] = PreCommitShellHook(self.path, self.controldir()) self.hooks["commit-msg"] = CommitMsgShellHook(self.controldir()) self.hooks["post-commit"] = PostCommitShellHook(self.controldir()) self.hooks["post-receive"] = PostReceiveShellHook(self.controldir()) def _write_reflog( self, ref, old_sha, new_sha, committer, timestamp, timezone, message ) -> None: from .reflog import format_reflog_line path = os.path.join(self.controldir(), "logs", os.fsdecode(ref)) try: os.makedirs(os.path.dirname(path)) except FileExistsError: pass if committer is None: config = self.get_config_stack() committer = get_user_identity(config) check_user_identity(committer) if timestamp is None: timestamp = int(time.time()) if timezone is None: timezone = 0 # FIXME with open(path, "ab") as f: f.write( format_reflog_line( old_sha, new_sha, committer, timestamp, timezone, message ) + b"\n" ) @classmethod def discover(cls, start="."): """Iterate parent directories to discover a repository. Return a Repo object for the first parent directory that looks like a Git repository. Args: start: The directory to start discovery from (defaults to '.') """ remaining = True path = os.path.abspath(start) while remaining: try: return cls(path) except NotGitRepository: path, remaining = os.path.split(path) raise NotGitRepository( "No git repository was found at {path}".format(**dict(path=start)) ) def controldir(self): """Return the path of the control directory.""" return self._controldir def commondir(self): """Return the path of the common directory. For a main working tree, it is identical to controldir(). For a linked working tree, it is the control directory of the main working tree. """ return self._commondir def _determine_file_mode(self): """Probe the file-system to determine whether permissions can be trusted. Returns: True if permissions can be trusted, False otherwise. """ fname = os.path.join(self.path, ".probe-permissions") with open(fname, "w") as f: f.write("") st1 = os.lstat(fname) try: os.chmod(fname, st1.st_mode ^ stat.S_IXUSR) except PermissionError: return False st2 = os.lstat(fname) os.unlink(fname) mode_differs = st1.st_mode != st2.st_mode st2_has_exec = (st2.st_mode & stat.S_IXUSR) != 0 return mode_differs and st2_has_exec def _determine_symlinks(self): """Probe the filesystem to determine whether symlinks can be created. Returns: True if symlinks can be created, False otherwise. """ # TODO(jelmer): Actually probe disk / look at filesystem return sys.platform != "win32" def _put_named_file(self, path, contents) -> None: """Write a file to the control dir with the given name and contents. Args: path: The path to the file, relative to the control dir. contents: A string to write to the file. """ path = path.lstrip(os.path.sep) with GitFile(os.path.join(self.controldir(), path), "wb") as f: f.write(contents) def _del_named_file(self, path) -> None: try: os.unlink(os.path.join(self.controldir(), path)) except FileNotFoundError: return def get_named_file(self, path, basedir=None): """Get a file from the control dir with a specific name. Although the filename should be interpreted as a filename relative to the control dir in a disk-based Repo, the object returned need not be pointing to a file in that location. Args: path: The path to the file, relative to the control dir. basedir: Optional argument that specifies an alternative to the control dir. Returns: An open file object, or None if the file does not exist. """ # TODO(dborowitz): sanitize filenames, since this is used directly by # the dumb web serving code. if basedir is None: basedir = self.controldir() path = path.lstrip(os.path.sep) try: return open(os.path.join(basedir, path), "rb") except FileNotFoundError: return None def index_path(self): """Return path to the index file.""" return os.path.join(self.controldir(), INDEX_FILENAME) def open_index(self) -> "Index": """Open the index for this repository. Raises: NoIndexPresent: If no index is present Returns: The matching `Index` """ from .index import Index if not self.has_index(): raise NoIndexPresent return Index(self.index_path()) def has_index(self) -> bool: """Check if an index is present.""" # Bare repos must never have index files; non-bare repos may have a # missing index file, which is treated as empty. return not self.bare def stage( self, fs_paths: Union[ str, bytes, os.PathLike, Iterable[Union[str, bytes, os.PathLike]] ], ) -> None: """Stage a set of paths. Args: fs_paths: List of paths, relative to the repository path """ root_path_bytes = os.fsencode(self.path) if isinstance(fs_paths, (str, bytes, os.PathLike)): fs_paths = [fs_paths] fs_paths = list(fs_paths) from .index import ( _fs_to_tree_path, blob_from_path_and_stat, index_entry_from_directory, index_entry_from_stat, ) index = self.open_index() blob_normalizer = self.get_blob_normalizer() for fs_path in fs_paths: if not isinstance(fs_path, bytes): fs_path = os.fsencode(fs_path) if os.path.isabs(fs_path): raise ValueError( f"path {fs_path!r} should be relative to " "repository root, not absolute" ) tree_path = _fs_to_tree_path(fs_path) full_path = os.path.join(root_path_bytes, fs_path) try: st = os.lstat(full_path) except OSError: # File no longer exists try: del index[tree_path] except KeyError: pass # already removed else: if stat.S_ISDIR(st.st_mode): entry = index_entry_from_directory(st, full_path) if entry: index[tree_path] = entry else: try: del index[tree_path] except KeyError: pass elif not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode): try: del index[tree_path] except KeyError: pass else: blob = blob_from_path_and_stat(full_path, st) blob = blob_normalizer.checkin_normalize(blob, fs_path) self.object_store.add_object(blob) index[tree_path] = index_entry_from_stat(st, blob.id) index.write() def unstage(self, fs_paths: list[str]) -> None: """Unstage specific file in the index Args: fs_paths: a list of files to unstage, relative to the repository path. """ from .index import IndexEntry, _fs_to_tree_path index = self.open_index() try: tree_id = self[b"HEAD"].tree except KeyError: # no head mean no commit in the repo for fs_path in fs_paths: tree_path = _fs_to_tree_path(fs_path) del index[tree_path] index.write() return for fs_path in fs_paths: tree_path = _fs_to_tree_path(fs_path) try: tree = self.object_store[tree_id] assert isinstance(tree, Tree) tree_entry = tree.lookup_path(self.object_store.__getitem__, tree_path) except KeyError: # if tree_entry didn't exist, this file was being added, so # remove index entry try: del index[tree_path] continue except KeyError as exc: raise KeyError(f"file '{tree_path.decode()}' not in index") from exc st = None try: st = os.lstat(os.path.join(self.path, fs_path)) except FileNotFoundError: pass index_entry = IndexEntry( ctime=(self[b"HEAD"].commit_time, 0), mtime=(self[b"HEAD"].commit_time, 0), dev=st.st_dev if st else 0, ino=st.st_ino if st else 0, mode=tree_entry[0], uid=st.st_uid if st else 0, gid=st.st_gid if st else 0, size=len(self[tree_entry[1]].data), sha=tree_entry[1], ) index[tree_path] = index_entry index.write() def clone( self, target_path, *, mkdir=True, bare=False, origin=b"origin", checkout=None, branch=None, progress=None, depth=None, symlinks=None, ) -> "Repo": """Clone this repository. Args: target_path: Target path mkdir: Create the target directory bare: Whether to create a bare repository checkout: Whether or not to check-out HEAD after cloning origin: Base name for refs in target repository cloned from this repository branch: Optional branch or tag to be used as HEAD in the new repository instead of this repository's HEAD. progress: Optional progress function depth: Depth at which to fetch symlinks: Symlinks setting (default to autodetect) Returns: Created repository as `Repo` """ encoded_path = os.fsencode(self.path) if mkdir: os.mkdir(target_path) try: if not bare: target = Repo.init(target_path, symlinks=symlinks) if checkout is None: checkout = True else: if checkout: raise ValueError("checkout and bare are incompatible") target = Repo.init_bare(target_path) try: target_config = target.get_config() target_config.set((b"remote", origin), b"url", encoded_path) target_config.set( (b"remote", origin), b"fetch", b"+refs/heads/*:refs/remotes/" + origin + b"/*", ) target_config.write_to_path() ref_message = b"clone: from " + encoded_path self.fetch(target, depth=depth) target.refs.import_refs( b"refs/remotes/" + origin, self.refs.as_dict(b"refs/heads"), message=ref_message, ) target.refs.import_refs( b"refs/tags", self.refs.as_dict(b"refs/tags"), message=ref_message ) head_chain, origin_sha = self.refs.follow(b"HEAD") origin_head = head_chain[-1] if head_chain else None if origin_sha and not origin_head: # set detached HEAD target.refs[b"HEAD"] = origin_sha else: _set_origin_head(target.refs, origin, origin_head) head_ref = _set_default_branch( target.refs, origin, origin_head, branch, ref_message ) # Update target head if head_ref: head = _set_head(target.refs, head_ref, ref_message) else: head = None if checkout and head is not None: target.reset_index() except BaseException: target.close() raise except BaseException: if mkdir: import shutil shutil.rmtree(target_path) raise return target def reset_index(self, tree: Optional[bytes] = None): """Reset the index back to a specific tree. Args: tree: Tree SHA to reset to, None for current HEAD tree. """ from .index import ( build_index_from_tree, symlink, validate_path_element_default, validate_path_element_ntfs, ) if tree is None: head = self[b"HEAD"] if isinstance(head, Tag): _cls, obj = head.object head = self.get_object(obj) tree = head.tree config = self.get_config() honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt") if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"): validate_path_element = validate_path_element_ntfs else: validate_path_element = validate_path_element_default if config.get_boolean(b"core", b"symlinks", True): symlink_fn = symlink else: def symlink_fn(source, target) -> None: # type: ignore with open( target, "w" + ("b" if isinstance(source, bytes) else "") ) as f: f.write(source) return build_index_from_tree( self.path, self.index_path(), self.object_store, tree, honor_filemode=honor_filemode, validate_path_element=validate_path_element, symlink_fn=symlink_fn, ) def get_worktree_config(self) -> "ConfigFile": from .config import ConfigFile path = os.path.join(self.commondir(), "config.worktree") try: return ConfigFile.from_path(path) except FileNotFoundError: cf = ConfigFile() cf.path = path return cf def get_config(self) -> "ConfigFile": """Retrieve the config object. Returns: `ConfigFile` object for the ``.git/config`` file. """ from .config import ConfigFile path = os.path.join(self._commondir, "config") try: return ConfigFile.from_path(path) except FileNotFoundError: ret = ConfigFile() ret.path = path return ret def get_description(self): """Retrieve the description of this repository. Returns: A string describing the repository or None. """ path = os.path.join(self._controldir, "description") try: with GitFile(path, "rb") as f: return f.read() except FileNotFoundError: return None def __repr__(self) -> str: return f"" def set_description(self, description) -> None: """Set the description for this repository. Args: description: Text to set as description for this repository. """ self._put_named_file("description", description) @classmethod def _init_maybe_bare( cls, path, controldir, bare, object_store=None, config=None, default_branch=None, symlinks: Optional[bool] = None, ): for d in BASE_DIRECTORIES: os.mkdir(os.path.join(controldir, *d)) if object_store is None: object_store = DiskObjectStore.init(os.path.join(controldir, OBJECTDIR)) ret = cls(path, bare=bare, object_store=object_store) if default_branch is None: if config is None: from .config import StackedConfig config = StackedConfig.default() try: default_branch = config.get("init", "defaultBranch") except KeyError: default_branch = DEFAULT_BRANCH ret.refs.set_symbolic_ref(b"HEAD", LOCAL_BRANCH_PREFIX + default_branch) ret._init_files(bare=bare, symlinks=symlinks) return ret @classmethod def init( cls, path: str, *, mkdir: bool = False, config=None, default_branch=None, symlinks: Optional[bool] = None, ) -> "Repo": """Create a new repository. Args: path: Path in which to create the repository mkdir: Whether to create the directory Returns: `Repo` instance """ if mkdir: os.mkdir(path) controldir = os.path.join(path, CONTROLDIR) os.mkdir(controldir) _set_filesystem_hidden(controldir) return cls._init_maybe_bare( path, controldir, False, config=config, default_branch=default_branch, symlinks=symlinks, ) @classmethod def _init_new_working_directory(cls, path, main_repo, identifier=None, mkdir=False): """Create a new working directory linked to a repository. Args: path: Path in which to create the working tree. main_repo: Main repository to reference identifier: Worktree identifier mkdir: Whether to create the directory Returns: `Repo` instance """ if mkdir: os.mkdir(path) if identifier is None: identifier = os.path.basename(path) main_worktreesdir = os.path.join(main_repo.controldir(), WORKTREES) worktree_controldir = os.path.join(main_worktreesdir, identifier) gitdirfile = os.path.join(path, CONTROLDIR) with open(gitdirfile, "wb") as f: f.write(b"gitdir: " + os.fsencode(worktree_controldir) + b"\n") try: os.mkdir(main_worktreesdir) except FileExistsError: pass try: os.mkdir(worktree_controldir) except FileExistsError: pass with open(os.path.join(worktree_controldir, GITDIR), "wb") as f: f.write(os.fsencode(gitdirfile) + b"\n") with open(os.path.join(worktree_controldir, COMMONDIR), "wb") as f: f.write(b"../..\n") with open(os.path.join(worktree_controldir, "HEAD"), "wb") as f: f.write(main_repo.head() + b"\n") r = cls(path) r.reset_index() return r @classmethod def init_bare( cls, path, *, mkdir=False, object_store=None, config=None, default_branch=None ): """Create a new bare repository. ``path`` should already exist and be an empty directory. Args: path: Path to create bare repository in Returns: a `Repo` instance """ if mkdir: os.mkdir(path) return cls._init_maybe_bare( path, path, True, object_store=object_store, config=config, default_branch=default_branch, ) create = init_bare def close(self) -> None: """Close any files opened by this repository.""" self.object_store.close() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def get_blob_normalizer(self): """Return a BlobNormalizer object.""" # TODO Parse the git attributes files git_attributes = {} config_stack = self.get_config_stack() try: tree = self.object_store[self.refs[b"HEAD"]].tree return TreeBlobNormalizer( config_stack, git_attributes, self.object_store, tree, ) except KeyError: return BlobNormalizer(config_stack, git_attributes) class MemoryRepo(BaseRepo): """Repo that stores refs, objects, and named files in memory. MemoryRepos are always bare: they have no working tree and no index, since those have a stronger dependency on the filesystem. """ def __init__(self) -> None: from .config import ConfigFile self._reflog: list[Any] = [] refs_container = DictRefsContainer({}, logger=self._append_reflog) BaseRepo.__init__(self, MemoryObjectStore(), refs_container) # type: ignore self._named_files: dict[str, bytes] = {} self.bare = True self._config = ConfigFile() self._description = None def _append_reflog(self, *args) -> None: self._reflog.append(args) def set_description(self, description) -> None: self._description = description def get_description(self): return self._description def _determine_file_mode(self): """Probe the file-system to determine whether permissions can be trusted. Returns: True if permissions can be trusted, False otherwise. """ return sys.platform != "win32" def _determine_symlinks(self): """Probe the file-system to determine whether permissions can be trusted. Returns: True if permissions can be trusted, False otherwise. """ return sys.platform != "win32" def _put_named_file(self, path, contents) -> None: """Write a file to the control dir with the given name and contents. Args: path: The path to the file, relative to the control dir. contents: A string to write to the file. """ self._named_files[path] = contents def _del_named_file(self, path) -> None: try: del self._named_files[path] except KeyError: pass def get_named_file(self, path, basedir=None): """Get a file from the control dir with a specific name. Although the filename should be interpreted as a filename relative to the control dir in a disk-baked Repo, the object returned need not be pointing to a file in that location. Args: path: The path to the file, relative to the control dir. Returns: An open file object, or None if the file does not exist. """ contents = self._named_files.get(path, None) if contents is None: return None return BytesIO(contents) def open_index(self) -> "Index": """Fail to open index for this repo, since it is bare. Raises: NoIndexPresent: Raised when no index is present """ raise NoIndexPresent def get_config(self): """Retrieve the config object. Returns: `ConfigFile` object. """ return self._config @classmethod def init_bare(cls, objects, refs): """Create a new bare repository in memory. Args: objects: Objects for the new repository, as iterable refs: Refs as dictionary, mapping names to object SHA1s """ ret = cls() for obj in objects: ret.object_store.add_object(obj) for refname, sha in refs.items(): ret.refs.add_if_new(refname, sha) ret._init_files(bare=True) return ret ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/server.py0000644000175100002000000012776414731042555016177 0ustar00runnerdocker# server.py -- Implementation of the server side git protocols # Copyright (C) 2008 John Carr # Copyright(C) 2011-2012 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Git smart network protocol server implementation. For more detailed implementation on the network protocol, see the Documentation/technical directory in the cgit distribution, and in particular: * Documentation/technical/protocol-capabilities.txt * Documentation/technical/pack-protocol.txt Currently supported capabilities: * include-tag * thin-pack * multi_ack_detailed * multi_ack * side-band-64k * ofs-delta * no-progress * report-status * delete-refs * shallow * symref """ import collections import os import socket import socketserver import sys import time import zlib from collections.abc import Iterable, Iterator from functools import partial from typing import Optional, cast from typing import Protocol as TypingProtocol from dulwich import log_utils from .archive import tar_stream from .errors import ( ApplyDeltaError, ChecksumMismatch, GitProtocolError, HookError, NotGitRepository, ObjectFormatException, UnexpectedCommandError, ) from .object_store import peel_sha from .objects import Commit, ObjectID, valid_hexsha from .pack import ObjectContainer, PackedObjectContainer, write_pack_from_container from .protocol import ( CAPABILITIES_REF, CAPABILITY_AGENT, CAPABILITY_DELETE_REFS, CAPABILITY_INCLUDE_TAG, CAPABILITY_MULTI_ACK, CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_NO_DONE, CAPABILITY_NO_PROGRESS, CAPABILITY_OFS_DELTA, CAPABILITY_QUIET, CAPABILITY_REPORT_STATUS, CAPABILITY_SHALLOW, CAPABILITY_SIDE_BAND_64K, CAPABILITY_THIN_PACK, COMMAND_DEEPEN, COMMAND_DONE, COMMAND_HAVE, COMMAND_SHALLOW, COMMAND_UNSHALLOW, COMMAND_WANT, MULTI_ACK, MULTI_ACK_DETAILED, NAK_LINE, SIDE_BAND_CHANNEL_DATA, SIDE_BAND_CHANNEL_FATAL, SIDE_BAND_CHANNEL_PROGRESS, SINGLE_ACK, TCP_GIT_PORT, ZERO_SHA, BufferedPktLineWriter, Protocol, ReceivableProtocol, ack_type, capability_agent, extract_capabilities, extract_want_line_capabilities, format_ack_line, format_ref_line, format_shallow_line, format_unshallow_line, symref_capabilities, ) from .refs import PEELED_TAG_SUFFIX, RefsContainer, write_info_refs from .repo import Repo logger = log_utils.getLogger(__name__) class Backend: """A backend for the Git smart server implementation.""" def open_repository(self, path) -> "BackendRepo": """Open the repository at a path. Args: path: Path to the repository Raises: NotGitRepository: no git repository was found at path Returns: Instance of BackendRepo """ raise NotImplementedError(self.open_repository) class BackendRepo(TypingProtocol): """Repository abstraction used by the Git server. The methods required here are a subset of those provided by dulwich.repo.Repo. """ object_store: PackedObjectContainer refs: RefsContainer def get_refs(self) -> dict[bytes, bytes]: """Get all the refs in the repository. Returns: dict of name -> sha """ raise NotImplementedError def get_peeled(self, name: bytes) -> Optional[bytes]: """Return the cached peeled value of a ref, if available. Args: name: Name of the ref to peel Returns: The peeled value of the ref. If the ref is known not point to a tag, this will be the SHA the ref refers to. If no cached information about a tag is available, this method may return None, but it should attempt to peel the tag if possible. """ return None def find_missing_objects( self, determine_wants, graph_walker, progress, get_tagged=None ) -> Iterator[ObjectID]: """Yield the objects required for a list of commits. Args: progress: is a callback to send progress messages to the client get_tagged: Function that returns a dict of pointed-to sha -> tag sha for including tags. """ raise NotImplementedError class DictBackend(Backend): """Trivial backend that looks up Git repositories in a dictionary.""" def __init__(self, repos) -> None: self.repos = repos def open_repository(self, path: str) -> BackendRepo: logger.debug("Opening repository at %s", path) try: return self.repos[path] except KeyError as exc: raise NotGitRepository( "No git repository was found at {path}".format(**dict(path=path)) ) from exc class FileSystemBackend(Backend): """Simple backend looking up Git repositories in the local file system.""" def __init__(self, root=os.sep) -> None: super().__init__() self.root = (os.path.abspath(root) + os.sep).replace(os.sep * 2, os.sep) def open_repository(self, path): logger.debug("opening repository at %s", path) abspath = os.path.abspath(os.path.join(self.root, path)) + os.sep normcase_abspath = os.path.normcase(abspath) normcase_root = os.path.normcase(self.root) if not normcase_abspath.startswith(normcase_root): raise NotGitRepository(f"Path {path!r} not inside root {self.root!r}") return Repo(abspath) class Handler: """Smart protocol command handler base class.""" def __init__(self, backend, proto, stateless_rpc=False) -> None: self.backend = backend self.proto = proto self.stateless_rpc = stateless_rpc def handle(self) -> None: raise NotImplementedError(self.handle) class PackHandler(Handler): """Protocol handler for packs.""" def __init__(self, backend, proto, stateless_rpc=False) -> None: super().__init__(backend, proto, stateless_rpc) self._client_capabilities: Optional[set[bytes]] = None # Flags needed for the no-done capability self._done_received = False @classmethod def capabilities(cls) -> Iterable[bytes]: raise NotImplementedError(cls.capabilities) @classmethod def innocuous_capabilities(cls) -> Iterable[bytes]: return [ CAPABILITY_INCLUDE_TAG, CAPABILITY_THIN_PACK, CAPABILITY_NO_PROGRESS, CAPABILITY_OFS_DELTA, capability_agent(), ] @classmethod def required_capabilities(cls) -> Iterable[bytes]: """Return a list of capabilities that we require the client to have.""" return [] def set_client_capabilities(self, caps: Iterable[bytes]) -> None: allowable_caps = set(self.innocuous_capabilities()) allowable_caps.update(self.capabilities()) for cap in caps: if cap.startswith(CAPABILITY_AGENT + b"="): continue if cap not in allowable_caps: raise GitProtocolError( f"Client asked for capability {cap!r} that " "was not advertised." ) for cap in self.required_capabilities(): if cap not in caps: raise GitProtocolError( "Client does not support required " f"capability {cap!r}." ) self._client_capabilities = set(caps) logger.info("Client capabilities: %s", caps) def has_capability(self, cap: bytes) -> bool: if self._client_capabilities is None: raise GitProtocolError( f"Server attempted to access capability {cap!r} " "before asking client" ) return cap in self._client_capabilities def notify_done(self) -> None: self._done_received = True class UploadPackHandler(PackHandler): """Protocol handler for uploading a pack to the client.""" def __init__( self, backend, args, proto, stateless_rpc=False, advertise_refs=False ) -> None: super().__init__(backend, proto, stateless_rpc=stateless_rpc) self.repo = backend.open_repository(args[0]) self._graph_walker = None self.advertise_refs = advertise_refs # A state variable for denoting that the have list is still # being processed, and the client is not accepting any other # data (such as side-band, see the progress method here). self._processing_have_lines = False @classmethod def capabilities(cls): return [ CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_MULTI_ACK, CAPABILITY_SIDE_BAND_64K, CAPABILITY_THIN_PACK, CAPABILITY_OFS_DELTA, CAPABILITY_NO_PROGRESS, CAPABILITY_INCLUDE_TAG, CAPABILITY_SHALLOW, CAPABILITY_NO_DONE, ] @classmethod def required_capabilities(cls): return ( CAPABILITY_SIDE_BAND_64K, CAPABILITY_THIN_PACK, CAPABILITY_OFS_DELTA, ) def progress(self, message: bytes) -> None: pass def _start_pack_send_phase(self) -> None: if self.has_capability(CAPABILITY_SIDE_BAND_64K): # The provided haves are processed, and it is safe to send side- # band data now. if not self.has_capability(CAPABILITY_NO_PROGRESS): self.progress = partial( # type: ignore self.proto.write_sideband, SIDE_BAND_CHANNEL_PROGRESS ) self.write_pack_data = partial( self.proto.write_sideband, SIDE_BAND_CHANNEL_DATA ) else: self.write_pack_data = self.proto.write def get_tagged(self, refs=None, repo=None) -> dict[ObjectID, ObjectID]: """Get a dict of peeled values of tags to their original tag shas. Args: refs: dict of refname -> sha of possible tags; defaults to all of the backend's refs. repo: optional Repo instance for getting peeled refs; defaults to the backend's repo, if available Returns: dict of peeled_sha -> tag_sha, where tag_sha is the sha of a tag whose peeled value is peeled_sha. """ if not self.has_capability(CAPABILITY_INCLUDE_TAG): return {} if refs is None: refs = self.repo.get_refs() if repo is None: repo = getattr(self.repo, "repo", None) if repo is None: # Bail if we don't have a Repo available; this is ok since # clients must be able to handle if the server doesn't include # all relevant tags. # TODO: fix behavior when missing return {} # TODO(jelmer): Integrate this with the refs logic in # Repo.find_missing_objects tagged = {} for name, sha in refs.items(): peeled_sha = repo.get_peeled(name) if peeled_sha != sha: tagged[peeled_sha] = sha return tagged def handle(self) -> None: # Note the fact that client is only processing responses related # to the have lines it sent, and any other data (including side- # band) will be be considered a fatal error. self._processing_have_lines = True graph_walker = _ProtocolGraphWalker( self, self.repo.object_store, self.repo.get_peeled, self.repo.refs.get_symrefs, ) wants = [] def wants_wrapper(refs, **kwargs): wants.extend(graph_walker.determine_wants(refs, **kwargs)) return wants missing_objects = self.repo.find_missing_objects( wants_wrapper, graph_walker, self.progress, get_tagged=self.get_tagged, ) object_ids = list(missing_objects) # Did the process short-circuit (e.g. in a stateless RPC call)? Note # that the client still expects a 0-object pack in most cases. # Also, if it also happens that the object_iter is instantiated # with a graph walker with an implementation that talks over the # wire (which is this instance of this class) this will actually # iterate through everything and write things out to the wire. if len(wants) == 0: return if not graph_walker.handle_done( not self.has_capability(CAPABILITY_NO_DONE), self._done_received ): return self._start_pack_send_phase() self.progress((f"counting objects: {len(object_ids)}, done.\n").encode("ascii")) write_pack_from_container( self.write_pack_data, self.repo.object_store, object_ids ) # we are done self.proto.write_pkt_line(None) def _split_proto_line(line, allowed): """Split a line read from the wire. Args: line: The line read from the wire. allowed: An iterable of command names that should be allowed. Command names not listed below as possible return values will be ignored. If None, any commands from the possible return values are allowed. Returns: a tuple having one of the following forms: ('want', obj_id) ('have', obj_id) ('done', None) (None, None) (for a flush-pkt) Raises: UnexpectedCommandError: if the line cannot be parsed into one of the allowed return values. """ if not line: fields = [None] else: fields = line.rstrip(b"\n").split(b" ", 1) command = fields[0] if allowed is not None and command not in allowed: raise UnexpectedCommandError(command) if len(fields) == 1 and command in (COMMAND_DONE, None): return (command, None) elif len(fields) == 2: if command in ( COMMAND_WANT, COMMAND_HAVE, COMMAND_SHALLOW, COMMAND_UNSHALLOW, ): if not valid_hexsha(fields[1]): raise GitProtocolError("Invalid sha") return tuple(fields) elif command == COMMAND_DEEPEN: return command, int(fields[1]) raise GitProtocolError(f"Received invalid line from client: {line!r}") def _find_shallow(store: ObjectContainer, heads, depth): """Find shallow commits according to a given depth. Args: store: An ObjectStore for looking up objects. heads: Iterable of head SHAs to start walking from. depth: The depth of ancestors to include. A depth of one includes only the heads themselves. Returns: A tuple of (shallow, not_shallow), sets of SHAs that should be considered shallow and unshallow according to the arguments. Note that these sets may overlap if a commit is reachable along multiple paths. """ parents: dict[bytes, list[bytes]] = {} def get_parents(sha): result = parents.get(sha, None) if not result: result = store[sha].parents parents[sha] = result return result todo = [] # stack of (sha, depth) for head_sha in heads: _unpeeled, peeled = peel_sha(store, head_sha) if isinstance(peeled, Commit): todo.append((peeled.id, 1)) not_shallow = set() shallow = set() while todo: sha, cur_depth = todo.pop() if cur_depth < depth: not_shallow.add(sha) new_depth = cur_depth + 1 todo.extend((p, new_depth) for p in get_parents(sha)) else: shallow.add(sha) return shallow, not_shallow def _want_satisfied(store: ObjectContainer, haves, want, earliest) -> bool: o = store[want] pending = collections.deque([o]) known = {want} while pending: commit = pending.popleft() if commit.id in haves: return True if not isinstance(commit, Commit): # non-commit wants are assumed to be satisfied continue for parent in commit.parents: if parent in known: continue known.add(parent) parent_obj = store[parent] assert isinstance(parent_obj, Commit) # TODO: handle parents with later commit times than children if parent_obj.commit_time >= earliest: pending.append(parent_obj) return False def _all_wants_satisfied(store: ObjectContainer, haves, wants) -> bool: """Check whether all the current wants are satisfied by a set of haves. Args: store: Object store to retrieve objects from haves: A set of commits we know the client has. wants: A set of commits the client wants Note: Wants are specified with set_wants rather than passed in since in the current interface they are determined outside this class. """ haves = set(haves) if haves: have_objs = [store[h] for h in haves] earliest = min([h.commit_time for h in have_objs if isinstance(h, Commit)]) else: earliest = 0 for want in wants: if not _want_satisfied(store, haves, want, earliest): return False return True class AckGraphWalkerImpl: def __init__(self, graph_walker): raise NotImplementedError def ack(self, have_ref: ObjectID) -> None: raise NotImplementedError class _ProtocolGraphWalker: """A graph walker that knows the git protocol. As a graph walker, this class implements ack(), next(), and reset(). It also contains some base methods for interacting with the wire and walking the commit tree. The work of determining which acks to send is passed on to the implementation instance stored in _impl. The reason for this is that we do not know at object creation time what ack level the protocol requires. A call to set_ack_type() is required to set up the implementation, before any calls to next() or ack() are made. """ def __init__( self, handler, object_store: ObjectContainer, get_peeled, get_symrefs ) -> None: self.handler = handler self.store: ObjectContainer = object_store self.get_peeled = get_peeled self.get_symrefs = get_symrefs self.proto = handler.proto self.stateless_rpc = handler.stateless_rpc self.advertise_refs = handler.advertise_refs self._wants: list[bytes] = [] self.shallow: set[bytes] = set() self.client_shallow: set[bytes] = set() self.unshallow: set[bytes] = set() self._cached = False self._cache: list[bytes] = [] self._cache_index = 0 self._impl: Optional[AckGraphWalkerImpl] = None def determine_wants(self, heads, depth=None): """Determine the wants for a set of heads. The given heads are advertised to the client, who then specifies which refs they want using 'want' lines. This portion of the protocol is the same regardless of ack type, and in fact is used to set the ack type of the ProtocolGraphWalker. If the client has the 'shallow' capability, this method also reads and responds to the 'shallow' and 'deepen' lines from the client. These are not part of the wants per se, but they set up necessary state for walking the graph. Additionally, later code depends on this method consuming everything up to the first 'have' line. Args: heads: a dict of refname->SHA1 to advertise Returns: a list of SHA1s requested by the client """ symrefs = self.get_symrefs() values = set(heads.values()) if self.advertise_refs or not self.stateless_rpc: for i, (ref, sha) in enumerate(sorted(heads.items())): try: peeled_sha = self.get_peeled(ref) except KeyError: # Skip refs that are inaccessible # TODO(jelmer): Integrate with Repo.find_missing_objects refs # logic. continue if i == 0: logger.info("Sending capabilities: %s", self.handler.capabilities()) line = format_ref_line( ref, sha, self.handler.capabilities() + symref_capabilities(symrefs.items()), ) else: line = format_ref_line(ref, sha) self.proto.write_pkt_line(line) if peeled_sha != sha: self.proto.write_pkt_line( format_ref_line(ref + PEELED_TAG_SUFFIX, peeled_sha) ) # i'm done.. self.proto.write_pkt_line(None) if self.advertise_refs: return [] # Now client will sending want want want commands want = self.proto.read_pkt_line() if not want: return [] line, caps = extract_want_line_capabilities(want) self.handler.set_client_capabilities(caps) self.set_ack_type(ack_type(caps)) allowed = (COMMAND_WANT, COMMAND_SHALLOW, COMMAND_DEEPEN, None) command, sha = _split_proto_line(line, allowed) want_revs = [] while command == COMMAND_WANT: if sha not in values: raise GitProtocolError(f"Client wants invalid object {sha}") want_revs.append(sha) command, sha = self.read_proto_line(allowed) self.set_wants(want_revs) if command in (COMMAND_SHALLOW, COMMAND_DEEPEN): self.unread_proto_line(command, sha) self._handle_shallow_request(want_revs) if self.stateless_rpc and self.proto.eof(): # The client may close the socket at this point, expecting a # flush-pkt from the server. We might be ready to send a packfile # at this point, so we need to explicitly short-circuit in this # case. return [] return want_revs def unread_proto_line(self, command, value) -> None: if isinstance(value, int): value = str(value).encode("ascii") self.proto.unread_pkt_line(command + b" " + value) def nak(self) -> None: pass def ack(self, have_ref): if len(have_ref) != 40: raise ValueError(f"invalid sha {have_ref!r}") return self._impl.ack(have_ref) def reset(self) -> None: self._cached = True self._cache_index = 0 def next(self): if not self._cached: if not self._impl and self.stateless_rpc: return None return next(self._impl) self._cache_index += 1 if self._cache_index > len(self._cache): return None return self._cache[self._cache_index] __next__ = next def read_proto_line(self, allowed): """Read a line from the wire. Args: allowed: An iterable of command names that should be allowed. Returns: A tuple of (command, value); see _split_proto_line. Raises: UnexpectedCommandError: If an error occurred reading the line. """ return _split_proto_line(self.proto.read_pkt_line(), allowed) def _handle_shallow_request(self, wants) -> None: while True: command, val = self.read_proto_line((COMMAND_DEEPEN, COMMAND_SHALLOW)) if command == COMMAND_DEEPEN: depth = val break self.client_shallow.add(val) self.read_proto_line((None,)) # consume client's flush-pkt shallow, not_shallow = _find_shallow(self.store, wants, depth) # Update self.shallow instead of reassigning it since we passed a # reference to it before this method was called. self.shallow.update(shallow - not_shallow) new_shallow = self.shallow - self.client_shallow unshallow = self.unshallow = not_shallow & self.client_shallow for sha in sorted(new_shallow): self.proto.write_pkt_line(format_shallow_line(sha)) for sha in sorted(unshallow): self.proto.write_pkt_line(format_unshallow_line(sha)) self.proto.write_pkt_line(None) def notify_done(self) -> None: # relay the message down to the handler. self.handler.notify_done() def send_ack(self, sha, ack_type=b"") -> None: self.proto.write_pkt_line(format_ack_line(sha, ack_type)) def send_nak(self) -> None: self.proto.write_pkt_line(NAK_LINE) def handle_done(self, done_required, done_received): # Delegate this to the implementation. return self._impl.handle_done(done_required, done_received) def set_wants(self, wants) -> None: self._wants = wants def all_wants_satisfied(self, haves): """Check whether all the current wants are satisfied by a set of haves. Args: haves: A set of commits we know the client has. Note: Wants are specified with set_wants rather than passed in since in the current interface they are determined outside this class. """ return _all_wants_satisfied(self.store, haves, self._wants) def set_ack_type(self, ack_type) -> None: impl_classes: dict[int, type[AckGraphWalkerImpl]] = { MULTI_ACK: MultiAckGraphWalkerImpl, MULTI_ACK_DETAILED: MultiAckDetailedGraphWalkerImpl, SINGLE_ACK: SingleAckGraphWalkerImpl, } self._impl = impl_classes[ack_type](self) _GRAPH_WALKER_COMMANDS = (COMMAND_HAVE, COMMAND_DONE, None) class SingleAckGraphWalkerImpl(AckGraphWalkerImpl): """Graph walker implementation that speaks the single-ack protocol.""" def __init__(self, walker) -> None: self.walker = walker self._common: list[bytes] = [] def ack(self, have_ref) -> None: if not self._common: self.walker.send_ack(have_ref) self._common.append(have_ref) def next(self): command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS) if command in (None, COMMAND_DONE): # defer the handling of done self.walker.notify_done() return None elif command == COMMAND_HAVE: return sha __next__ = next def handle_done(self, done_required, done_received) -> bool: if not self._common: self.walker.send_nak() if done_required and not done_received: # we are not done, especially when done is required; skip # the pack for this request and especially do not handle # the done. return False if not done_received and not self._common: # Okay we are not actually done then since the walker picked # up no haves. This is usually triggered when client attempts # to pull from a source that has no common base_commit. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\ # test_multi_ack_stateless_nodone return False return True class MultiAckGraphWalkerImpl(AckGraphWalkerImpl): """Graph walker implementation that speaks the multi-ack protocol.""" def __init__(self, walker) -> None: self.walker = walker self._found_base = False self._common: list[bytes] = [] def ack(self, have_ref) -> None: self._common.append(have_ref) if not self._found_base: self.walker.send_ack(have_ref, b"continue") if self.walker.all_wants_satisfied(self._common): self._found_base = True # else we blind ack within next def next(self): while True: command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS) if command is None: self.walker.send_nak() # in multi-ack mode, a flush-pkt indicates the client wants to # flush but more have lines are still coming continue elif command == COMMAND_DONE: self.walker.notify_done() return None elif command == COMMAND_HAVE: if self._found_base: # blind ack self.walker.send_ack(sha, b"continue") return sha __next__ = next def handle_done(self, done_required, done_received) -> bool: if done_required and not done_received: # we are not done, especially when done is required; skip # the pack for this request and especially do not handle # the done. return False if not done_received and not self._common: # Okay we are not actually done then since the walker picked # up no haves. This is usually triggered when client attempts # to pull from a source that has no common base_commit. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\ # test_multi_ack_stateless_nodone return False # don't nak unless no common commits were found, even if not # everything is satisfied if self._common: self.walker.send_ack(self._common[-1]) else: self.walker.send_nak() return True class MultiAckDetailedGraphWalkerImpl(AckGraphWalkerImpl): """Graph walker implementation speaking the multi-ack-detailed protocol.""" def __init__(self, walker) -> None: self.walker = walker self._common: list[bytes] = [] def ack(self, have_ref) -> None: # Should only be called iff have_ref is common self._common.append(have_ref) self.walker.send_ack(have_ref, b"common") def next(self): while True: command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS) if command is None: if self.walker.all_wants_satisfied(self._common): self.walker.send_ack(self._common[-1], b"ready") self.walker.send_nak() if self.walker.stateless_rpc: # The HTTP version of this request a flush-pkt always # signifies an end of request, so we also return # nothing here as if we are done (but not really, as # it depends on whether no-done capability was # specified and that's handled in handle_done which # may or may not call post_nodone_check depending on # that). return None elif command == COMMAND_DONE: # Let the walker know that we got a done. self.walker.notify_done() break elif command == COMMAND_HAVE: # return the sha and let the caller ACK it with the # above ack method. return sha # don't nak unless no common commits were found, even if not # everything is satisfied __next__ = next def handle_done(self, done_required, done_received) -> bool: if done_required and not done_received: # we are not done, especially when done is required; skip # the pack for this request and especially do not handle # the done. return False if not done_received and not self._common: # Okay we are not actually done then since the walker picked # up no haves. This is usually triggered when client attempts # to pull from a source that has no common base_commit. # See: test_server.MultiAckDetailedGraphWalkerImplTestCase.\ # test_multi_ack_stateless_nodone return False # don't nak unless no common commits were found, even if not # everything is satisfied if self._common: self.walker.send_ack(self._common[-1]) else: self.walker.send_nak() return True class ReceivePackHandler(PackHandler): """Protocol handler for downloading a pack from the client.""" def __init__( self, backend, args, proto, stateless_rpc=False, advertise_refs=False ) -> None: super().__init__(backend, proto, stateless_rpc=stateless_rpc) self.repo = backend.open_repository(args[0]) self.advertise_refs = advertise_refs @classmethod def capabilities(cls) -> Iterable[bytes]: return [ CAPABILITY_REPORT_STATUS, CAPABILITY_DELETE_REFS, CAPABILITY_QUIET, CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K, CAPABILITY_NO_DONE, ] def _apply_pack( self, refs: list[tuple[bytes, bytes, bytes]] ) -> list[tuple[bytes, bytes]]: all_exceptions = ( IOError, OSError, ChecksumMismatch, ApplyDeltaError, AssertionError, socket.error, zlib.error, ObjectFormatException, ) status = [] will_send_pack = False for command in refs: if command[1] != ZERO_SHA: will_send_pack = True if will_send_pack: # TODO: more informative error messages than just the exception # string try: recv = getattr(self.proto, "recv", None) self.repo.object_store.add_thin_pack(self.proto.read, recv) status.append((b"unpack", b"ok")) except all_exceptions as e: status.append((b"unpack", str(e).replace("\n", "").encode("utf-8"))) # The pack may still have been moved in, but it may contain # broken objects. We trust a later GC to clean it up. else: # The git protocol want to find a status entry related to unpack # process even if no pack data has been sent. status.append((b"unpack", b"ok")) for oldsha, sha, ref in refs: ref_status = b"ok" try: if sha == ZERO_SHA: if CAPABILITY_DELETE_REFS not in self.capabilities(): raise GitProtocolError( "Attempted to delete refs without delete-refs " "capability." ) try: self.repo.refs.remove_if_equals(ref, oldsha) except all_exceptions: ref_status = b"failed to delete" else: try: self.repo.refs.set_if_equals(ref, oldsha, sha) except all_exceptions: ref_status = b"failed to write" except KeyError: ref_status = b"bad ref" status.append((ref, ref_status)) return status def _report_status(self, status: list[tuple[bytes, bytes]]) -> None: if self.has_capability(CAPABILITY_SIDE_BAND_64K): writer = BufferedPktLineWriter( lambda d: self.proto.write_sideband(SIDE_BAND_CHANNEL_DATA, d) ) write = writer.write def flush() -> None: writer.flush() self.proto.write_pkt_line(None) else: write = self.proto.write_pkt_line def flush() -> None: pass for name, msg in status: if name == b"unpack": write(b"unpack " + msg + b"\n") elif msg == b"ok": write(b"ok " + name + b"\n") else: write(b"ng " + name + b" " + msg + b"\n") write(None) flush() def _on_post_receive(self, client_refs) -> None: hook = self.repo.hooks.get("post-receive", None) if not hook: return try: output = hook.execute(client_refs) if output: self.proto.write_sideband(SIDE_BAND_CHANNEL_PROGRESS, output) except HookError as err: self.proto.write_sideband(SIDE_BAND_CHANNEL_FATAL, str(err).encode("utf-8")) def handle(self) -> None: if self.advertise_refs or not self.stateless_rpc: refs = sorted(self.repo.get_refs().items()) symrefs = sorted(self.repo.refs.get_symrefs().items()) if not refs: refs = [(CAPABILITIES_REF, ZERO_SHA)] logger.info("Sending capabilities: %s", self.capabilities()) self.proto.write_pkt_line( format_ref_line( refs[0][0], refs[0][1], self.capabilities() + symref_capabilities(symrefs), ) ) for i in range(1, len(refs)): ref = refs[i] self.proto.write_pkt_line(format_ref_line(ref[0], ref[1])) self.proto.write_pkt_line(None) if self.advertise_refs: return client_refs = [] ref = self.proto.read_pkt_line() # if ref is none then client doesn't want to send us anything.. if ref is None: return ref, caps = extract_capabilities(ref) self.set_client_capabilities(caps) # client will now send us a list of (oldsha, newsha, ref) while ref: client_refs.append(ref.split()) ref = self.proto.read_pkt_line() # backend can now deal with this refs and read a pack using self.read status = self._apply_pack(client_refs) self._on_post_receive(client_refs) # when we have read all the pack from the client, send a status report # if the client asked for it if self.has_capability(CAPABILITY_REPORT_STATUS): self._report_status(status) class UploadArchiveHandler(Handler): def __init__(self, backend, args, proto, stateless_rpc=False) -> None: super().__init__(backend, proto, stateless_rpc) self.repo = backend.open_repository(args[0]) def handle(self) -> None: def write(x): return self.proto.write_sideband(SIDE_BAND_CHANNEL_DATA, x) arguments = [] for pkt in self.proto.read_pkt_seq(): (key, value) = pkt.split(b" ", 1) if key != b"argument": raise GitProtocolError(f"unknown command {key}") arguments.append(value.rstrip(b"\n")) prefix = b"" format = "tar" i = 0 store: ObjectContainer = self.repo.object_store while i < len(arguments): argument = arguments[i] if argument == b"--prefix": i += 1 prefix = arguments[i] elif argument == b"--format": i += 1 format = arguments[i].decode("ascii") else: commit_sha = self.repo.refs[argument] tree = store[cast(Commit, store[commit_sha]).tree] i += 1 self.proto.write_pkt_line(b"ACK") self.proto.write_pkt_line(None) for chunk in tar_stream( store, tree, mtime=time.time(), prefix=prefix, format=format ): write(chunk) self.proto.write_pkt_line(None) # Default handler classes for git services. DEFAULT_HANDLERS = { b"git-upload-pack": UploadPackHandler, b"git-receive-pack": ReceivePackHandler, b"git-upload-archive": UploadArchiveHandler, } class TCPGitRequestHandler(socketserver.StreamRequestHandler): def __init__(self, handlers, *args, **kwargs) -> None: self.handlers = handlers socketserver.StreamRequestHandler.__init__(self, *args, **kwargs) def handle(self) -> None: proto = ReceivableProtocol(self.connection.recv, self.wfile.write) command, args = proto.read_cmd() logger.info("Handling %s request, args=%s", command, args) cls = self.handlers.get(command, None) if not callable(cls): raise GitProtocolError(f"Invalid service {command}") h = cls(self.server.backend, args, proto) # type: ignore h.handle() class TCPGitServer(socketserver.TCPServer): allow_reuse_address = True serve = socketserver.TCPServer.serve_forever def _make_handler(self, *args, **kwargs): return TCPGitRequestHandler(self.handlers, *args, **kwargs) def __init__(self, backend, listen_addr, port=TCP_GIT_PORT, handlers=None) -> None: self.handlers = dict(DEFAULT_HANDLERS) if handlers is not None: self.handlers.update(handlers) self.backend = backend logger.info("Listening for TCP connections on %s:%d", listen_addr, port) socketserver.TCPServer.__init__(self, (listen_addr, port), self._make_handler) def verify_request(self, request, client_address) -> bool: logger.info("Handling request from %s", client_address) return True def handle_error(self, request, client_address) -> None: logger.exception( "Exception happened during processing of request " "from %s", client_address, ) def main(argv=sys.argv) -> None: """Entry point for starting a TCP git server.""" import optparse parser = optparse.OptionParser() parser.add_option( "-l", "--listen_address", dest="listen_address", default="localhost", help="Binding IP address.", ) parser.add_option( "-p", "--port", dest="port", type=int, default=TCP_GIT_PORT, help="Binding TCP port.", ) options, args = parser.parse_args(argv) log_utils.default_logging_config() if len(args) > 1: gitdir = args[1] else: gitdir = "." # TODO(jelmer): Support git-daemon-export-ok and --export-all. backend = FileSystemBackend(gitdir) server = TCPGitServer(backend, options.listen_address, options.port) server.serve_forever() def serve_command( handler_cls, argv=sys.argv, backend=None, inf=sys.stdin, outf=sys.stdout ) -> int: """Serve a single command. This is mostly useful for the implementation of commands used by e.g. git+ssh. Args: handler_cls: `Handler` class to use for the request argv: execv-style command-line arguments. Defaults to sys.argv. backend: `Backend` to use inf: File-like object to read from, defaults to standard input. outf: File-like object to write to, defaults to standard output. Returns: Exit code for use with sys.exit. 0 on success, 1 on failure. """ if backend is None: backend = FileSystemBackend() def send_fn(data) -> None: outf.write(data) outf.flush() proto = Protocol(inf.read, send_fn) handler = handler_cls(backend, argv[1:], proto) # FIXME: Catch exceptions and write a single-line summary to outf. handler.handle() return 0 def generate_info_refs(repo): """Generate an info refs file.""" refs = repo.get_refs() return write_info_refs(refs, repo.object_store) def generate_objects_info_packs(repo): """Generate an index for for packs.""" for pack in repo.object_store.packs: yield (b"P " + os.fsencode(pack.data.filename) + b"\n") def update_server_info(repo) -> None: """Generate server info for dumb file access. This generates info/refs and objects/info/packs, similar to "git update-server-info". """ repo._put_named_file( os.path.join("info", "refs"), b"".join(generate_info_refs(repo)) ) repo._put_named_file( os.path.join("objects", "info", "packs"), b"".join(generate_objects_info_packs(repo)), ) if __name__ == "__main__": main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/stash.py0000644000175100002000000000774214731042555016004 0ustar00runnerdocker# stash.py # Copyright (C) 2018 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Stash handling.""" import os from .file import GitFile from .index import commit_tree, iter_fresh_objects from .reflog import drop_reflog_entry, read_reflog DEFAULT_STASH_REF = b"refs/stash" class Stash: """A Git stash. Note that this doesn't currently update the working tree. """ def __init__(self, repo, ref=DEFAULT_STASH_REF) -> None: self._ref = ref self._repo = repo @property def _reflog_path(self): return os.path.join(self._repo.commondir(), "logs", os.fsdecode(self._ref)) def stashes(self): try: with GitFile(self._reflog_path, "rb") as f: return reversed(list(read_reflog(f))) except FileNotFoundError: return [] @classmethod def from_repo(cls, repo): """Create a new stash from a Repo object.""" return cls(repo) def drop(self, index) -> None: """Drop entry with specified index.""" with open(self._reflog_path, "rb+") as f: drop_reflog_entry(f, index, rewrite=True) if len(self) == 0: os.remove(self._reflog_path) del self._repo.refs[self._ref] return if index == 0: self._repo.refs[self._ref] = self[0].new_sha def pop(self, index): raise NotImplementedError(self.pop) def push(self, committer=None, author=None, message=None): """Create a new stash. Args: committer: Optional committer name to use author: Optional author name to use message: Optional commit message """ # First, create the index commit. commit_kwargs = {} if committer is not None: commit_kwargs["committer"] = committer if author is not None: commit_kwargs["author"] = author index = self._repo.open_index() index_tree_id = index.commit(self._repo.object_store) index_commit_id = self._repo.do_commit( ref=None, tree=index_tree_id, message=b"Index stash", merge_heads=[self._repo.head()], no_verify=True, **commit_kwargs, ) # Then, the working tree one. stash_tree_id = commit_tree( self._repo.object_store, iter_fresh_objects( index, os.fsencode(self._repo.path), object_store=self._repo.object_store, ), ) if message is None: message = b"A stash on " + self._repo.head() # TODO(jelmer): Just pass parents into do_commit()? self._repo.refs[self._ref] = self._repo.head() cid = self._repo.do_commit( ref=self._ref, tree=stash_tree_id, message=message, merge_heads=[index_commit_id], no_verify=True, **commit_kwargs, ) return cid def __getitem__(self, index): return list(self.stashes())[index] def __len__(self) -> int: return len(list(self.stashes())) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/stdint.h0000644000175100002000000000060114731042555015751 0ustar00runnerdocker/** * Replacement of gcc' stdint.h for MSVC */ #ifndef STDINT_H #define STDINT_H typedef signed char int8_t; typedef signed short int16_t; typedef signed int int32_t; typedef signed long long int64_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; typedef unsigned long long uint64_t; #endif ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/submodule.py0000644000175100002000000000306714731042555016655 0ustar00runnerdocker# config.py - Reading and writing Git config files # Copyright (C) 2011-2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Working with Git submodules.""" from collections.abc import Iterator from .object_store import iter_tree_contents from .objects import S_ISGITLINK def iter_cached_submodules(store, root_tree_id: bytes) -> Iterator[tuple[str, bytes]]: """Iterate over cached submodules. Args: store: Object store to iterate root_tree_id: SHA of root tree Returns: Iterator over over (path, sha) tuples """ for entry in iter_tree_contents(store, root_tree_id): if S_ISGITLINK(entry.mode): yield entry.path, entry.sha ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9724476 dulwich-0.22.7/dulwich/tests/0000755000175100002000000000000014731042565015441 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/tests/__init__.py0000644000175100002000000000201214731042555017544 0ustar00runnerdocker# __init__.py -- The tests for dulwich # Copyright (C) 2024 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for Dulwich.""" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/tests/test_object_store.py0000644000175100002000000003025214731042555021535 0ustar00runnerdocker# test_object_store.py -- tests for object_store.py # Copyright (C) 2008 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for the object store interface.""" from typing import TYPE_CHECKING, Any, Callable from unittest import skipUnless from dulwich.index import commit_tree from dulwich.object_store import ( PackBasedObjectStore, iter_tree_contents, peel_sha, ) from dulwich.objects import ( Blob, Tree, TreeEntry, ) from dulwich.protocol import DEPTH_INFINITE from .utils import make_object, make_tag if TYPE_CHECKING: from dulwich.object_store import BaseObjectStore try: from unittest.mock import patch except ImportError: patch = None # type: ignore testobject = make_object(Blob, data=b"yummy data") class ObjectStoreTests: store: "BaseObjectStore" assertEqual: Callable[[object, object], None] assertRaises: Callable[[type[Exception], Callable[[], Any]], None] assertNotIn: Callable[[object, object], None] assertNotEqual: Callable[[object, object], None] assertIn: Callable[[object, object], None] def test_determine_wants_all(self) -> None: self.assertEqual( [b"1" * 40], self.store.determine_wants_all({b"refs/heads/foo": b"1" * 40}), ) def test_determine_wants_all_zero(self) -> None: self.assertEqual( [], self.store.determine_wants_all({b"refs/heads/foo": b"0" * 40}) ) @skipUnless(patch, "Required mock.patch") def test_determine_wants_all_depth(self) -> None: self.store.add_object(testobject) refs = {b"refs/heads/foo": testobject.id} with patch.object(self.store, "_get_depth", return_value=1) as m: self.assertEqual([], self.store.determine_wants_all(refs, depth=0)) self.assertEqual( [testobject.id], self.store.determine_wants_all(refs, depth=DEPTH_INFINITE), ) m.assert_not_called() self.assertEqual([], self.store.determine_wants_all(refs, depth=1)) m.assert_called_with(testobject.id) self.assertEqual( [testobject.id], self.store.determine_wants_all(refs, depth=2) ) def test_get_depth(self) -> None: self.assertEqual(0, self.store._get_depth(testobject.id)) self.store.add_object(testobject) self.assertEqual( 1, self.store._get_depth(testobject.id, get_parents=lambda x: []) ) parent = make_object(Blob, data=b"parent data") self.store.add_object(parent) self.assertEqual( 2, self.store._get_depth( testobject.id, get_parents=lambda x: [parent.id] if x == testobject else [], ), ) def test_iter(self) -> None: self.assertEqual([], list(self.store)) def test_get_nonexistant(self) -> None: self.assertRaises(KeyError, lambda: self.store[b"a" * 40]) def test_contains_nonexistant(self) -> None: self.assertNotIn(b"a" * 40, self.store) def test_add_objects_empty(self) -> None: self.store.add_objects([]) def test_add_commit(self) -> None: # TODO: Argh, no way to construct Git commit objects without # access to a serialized form. self.store.add_objects([]) def test_store_resilience(self) -> None: """Test if updating an existing stored object doesn't erase the object from the store. """ test_object = make_object(Blob, data=b"data") self.store.add_object(test_object) test_object_id = test_object.id test_object.data = test_object.data + b"update" stored_test_object = self.store[test_object_id] self.assertNotEqual(test_object.id, stored_test_object.id) self.assertEqual(stored_test_object.id, test_object_id) def test_add_object(self) -> None: self.store.add_object(testobject) self.assertEqual({testobject.id}, set(self.store)) self.assertIn(testobject.id, self.store) r = self.store[testobject.id] self.assertEqual(r, testobject) def test_add_objects(self) -> None: data = [(testobject, "mypath")] self.store.add_objects(data) self.assertEqual({testobject.id}, set(self.store)) self.assertIn(testobject.id, self.store) r = self.store[testobject.id] self.assertEqual(r, testobject) def test_tree_changes(self) -> None: blob_a1 = make_object(Blob, data=b"a1") blob_a2 = make_object(Blob, data=b"a2") blob_b = make_object(Blob, data=b"b") for blob in [blob_a1, blob_a2, blob_b]: self.store.add_object(blob) blobs_1 = [(b"a", blob_a1.id, 0o100644), (b"b", blob_b.id, 0o100644)] tree1_id = commit_tree(self.store, blobs_1) blobs_2 = [(b"a", blob_a2.id, 0o100644), (b"b", blob_b.id, 0o100644)] tree2_id = commit_tree(self.store, blobs_2) change_a = ( (b"a", b"a"), (0o100644, 0o100644), (blob_a1.id, blob_a2.id), ) self.assertEqual([change_a], list(self.store.tree_changes(tree1_id, tree2_id))) self.assertEqual( [ change_a, ((b"b", b"b"), (0o100644, 0o100644), (blob_b.id, blob_b.id)), ], list(self.store.tree_changes(tree1_id, tree2_id, want_unchanged=True)), ) def test_iter_tree_contents(self) -> None: blob_a = make_object(Blob, data=b"a") blob_b = make_object(Blob, data=b"b") blob_c = make_object(Blob, data=b"c") for blob in [blob_a, blob_b, blob_c]: self.store.add_object(blob) blobs = [ (b"a", blob_a.id, 0o100644), (b"ad/b", blob_b.id, 0o100644), (b"ad/bd/c", blob_c.id, 0o100755), (b"ad/c", blob_c.id, 0o100644), (b"c", blob_c.id, 0o100644), ] tree_id = commit_tree(self.store, blobs) self.assertEqual( [TreeEntry(p, m, h) for (p, h, m) in blobs], list(iter_tree_contents(self.store, tree_id)), ) self.assertEqual([], list(iter_tree_contents(self.store, None))) def test_iter_tree_contents_include_trees(self) -> None: blob_a = make_object(Blob, data=b"a") blob_b = make_object(Blob, data=b"b") blob_c = make_object(Blob, data=b"c") for blob in [blob_a, blob_b, blob_c]: self.store.add_object(blob) blobs = [ (b"a", blob_a.id, 0o100644), (b"ad/b", blob_b.id, 0o100644), (b"ad/bd/c", blob_c.id, 0o100755), ] tree_id = commit_tree(self.store, blobs) tree = self.store[tree_id] assert isinstance(tree, Tree) tree_ad = self.store[tree[b"ad"][1]] assert isinstance(tree_ad, Tree) tree_bd = self.store[tree_ad[b"bd"][1]] expected = [ TreeEntry(b"", 0o040000, tree_id), TreeEntry(b"a", 0o100644, blob_a.id), TreeEntry(b"ad", 0o040000, tree_ad.id), TreeEntry(b"ad/b", 0o100644, blob_b.id), TreeEntry(b"ad/bd", 0o040000, tree_bd.id), TreeEntry(b"ad/bd/c", 0o100755, blob_c.id), ] actual = iter_tree_contents(self.store, tree_id, include_trees=True) self.assertEqual(expected, list(actual)) def make_tag(self, name, obj): tag = make_tag(obj, name=name) self.store.add_object(tag) return tag def test_peel_sha(self) -> None: self.store.add_object(testobject) tag1 = self.make_tag(b"1", testobject) tag2 = self.make_tag(b"2", testobject) tag3 = self.make_tag(b"3", testobject) for obj in [testobject, tag1, tag2, tag3]: self.assertEqual((obj, testobject), peel_sha(self.store, obj.id)) def test_get_raw(self) -> None: self.store.add_object(testobject) self.assertEqual( (Blob.type_num, b"yummy data"), self.store.get_raw(testobject.id) ) def test_close(self) -> None: # For now, just check that close doesn't barf. self.store.add_object(testobject) self.store.close() def test_iter_prefix(self) -> None: self.store.add_object(testobject) self.assertEqual([testobject.id], list(self.store.iter_prefix(testobject.id))) self.assertEqual( [testobject.id], list(self.store.iter_prefix(testobject.id[:10])) ) self.assertEqual( [testobject.id], list(self.store.iter_prefix(testobject.id[:4])) ) self.assertEqual([testobject.id], list(self.store.iter_prefix(b""))) def test_iter_prefix_not_found(self) -> None: self.assertEqual([], list(self.store.iter_prefix(b"1" * 40))) class PackBasedObjectStoreTests(ObjectStoreTests): store: PackBasedObjectStore def tearDown(self) -> None: for pack in self.store.packs: pack.close() def test_empty_packs(self) -> None: self.assertEqual([], list(self.store.packs)) def test_pack_loose_objects(self) -> None: b1 = make_object(Blob, data=b"yummy data") self.store.add_object(b1) b2 = make_object(Blob, data=b"more yummy data") self.store.add_object(b2) b3 = make_object(Blob, data=b"even more yummy data") b4 = make_object(Blob, data=b"and more yummy data") self.store.add_objects([(b3, None), (b4, None)]) self.assertEqual({b1.id, b2.id, b3.id, b4.id}, set(self.store)) self.assertEqual(1, len(self.store.packs)) self.assertEqual(2, self.store.pack_loose_objects()) self.assertNotEqual([], list(self.store.packs)) self.assertEqual(0, self.store.pack_loose_objects()) def test_repack(self) -> None: b1 = make_object(Blob, data=b"yummy data") self.store.add_object(b1) b2 = make_object(Blob, data=b"more yummy data") self.store.add_object(b2) b3 = make_object(Blob, data=b"even more yummy data") b4 = make_object(Blob, data=b"and more yummy data") self.store.add_objects([(b3, None), (b4, None)]) b5 = make_object(Blob, data=b"and more data") b6 = make_object(Blob, data=b"and some more data") self.store.add_objects([(b5, None), (b6, None)]) self.assertEqual({b1.id, b2.id, b3.id, b4.id, b5.id, b6.id}, set(self.store)) self.assertEqual(2, len(self.store.packs)) self.assertEqual(6, self.store.repack()) self.assertEqual(1, len(self.store.packs)) self.assertEqual(0, self.store.pack_loose_objects()) def test_repack_existing(self) -> None: b1 = make_object(Blob, data=b"yummy data") self.store.add_object(b1) b2 = make_object(Blob, data=b"more yummy data") self.store.add_object(b2) self.store.add_objects([(b1, None), (b2, None)]) self.store.add_objects([(b2, None)]) self.assertEqual({b1.id, b2.id}, set(self.store)) self.assertEqual(2, len(self.store.packs)) self.assertEqual(2, self.store.repack()) self.assertEqual(1, len(self.store.packs)) self.assertEqual(0, self.store.pack_loose_objects()) self.assertEqual({b1.id, b2.id}, set(self.store)) self.assertEqual(1, len(self.store.packs)) self.assertEqual(2, self.store.repack()) self.assertEqual(1, len(self.store.packs)) self.assertEqual(0, self.store.pack_loose_objects()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/tests/utils.py0000644000175100002000000003035314731042555017156 0ustar00runnerdocker# utils.py -- Test utilities for Dulwich. # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Utility functions common to Dulwich tests.""" import datetime import os import shutil import tempfile import time import types import warnings from unittest import SkipTest from dulwich.index import commit_tree from dulwich.objects import Commit, FixedSha, Tag, object_class from dulwich.pack import ( DELTA_TYPES, OFS_DELTA, REF_DELTA, SHA1Writer, create_delta, obj_sha, write_pack_header, write_pack_object, ) from dulwich.repo import Repo # Plain files are very frequently used in tests, so let the mode be very short. F = 0o100644 # Shorthand mode for Files. def open_repo(name, temp_dir=None): """Open a copy of a repo in a temporary directory. Use this function for accessing repos in dulwich/tests/data/repos to avoid accidentally or intentionally modifying those repos in place. Use tear_down_repo to delete any temp files created. Args: name: The name of the repository, relative to dulwich/tests/data/repos temp_dir: temporary directory to initialize to. If not provided, a temporary directory will be created. Returns: An initialized Repo object that lives in a temporary directory. """ if temp_dir is None: temp_dir = tempfile.mkdtemp() repo_dir = os.path.join( os.path.dirname(__file__), "..", "..", "testdata", "repos", name ) temp_repo_dir = os.path.join(temp_dir, name) shutil.copytree(repo_dir, temp_repo_dir, symlinks=True) return Repo(temp_repo_dir) def tear_down_repo(repo) -> None: """Tear down a test repository.""" repo.close() temp_dir = os.path.dirname(repo.path.rstrip(os.sep)) shutil.rmtree(temp_dir) def make_object(cls, **attrs): """Make an object for testing and assign some members. This method creates a new subclass to allow arbitrary attribute reassignment, which is not otherwise possible with objects having __slots__. Args: attrs: dict of attributes to set on the new object. Returns: A newly initialized object of type cls. """ class TestObject(cls): """Class that inherits from the given class, but without __slots__. Note that classes with __slots__ can't have arbitrary attributes monkey-patched in, so this is a class that is exactly the same only with a __dict__ instead of __slots__. """ TestObject.__name__ = "TestObject_" + cls.__name__ obj = TestObject() for name, value in attrs.items(): if name == "id": # id property is read-only, so we overwrite sha instead. sha = FixedSha(value) obj.sha = lambda: sha else: setattr(obj, name, value) return obj def make_commit(**attrs): """Make a Commit object with a default set of members. Args: attrs: dict of attributes to overwrite from the default values. Returns: A newly initialized Commit object. """ default_time = 1262304000 # 2010-01-01 00:00:00 all_attrs = { "author": b"Test Author ", "author_time": default_time, "author_timezone": 0, "committer": b"Test Committer ", "commit_time": default_time, "commit_timezone": 0, "message": b"Test message.", "parents": [], "tree": b"0" * 40, } all_attrs.update(attrs) return make_object(Commit, **all_attrs) def make_tag(target, **attrs): """Make a Tag object with a default set of values. Args: target: object to be tagged (Commit, Blob, Tree, etc) attrs: dict of attributes to overwrite from the default values. Returns: A newly initialized Tag object. """ target_id = target.id target_type = object_class(target.type_name) default_time = int(time.mktime(datetime.datetime(2010, 1, 1).timetuple())) all_attrs = { "tagger": b"Test Author ", "tag_time": default_time, "tag_timezone": 0, "message": b"Test message.", "object": (target_type, target_id), "name": b"Test Tag", } all_attrs.update(attrs) return make_object(Tag, **all_attrs) def functest_builder(method, func): """Generate a test method that tests the given function.""" def do_test(self) -> None: method(self, func) return do_test def ext_functest_builder(method, func): """Generate a test method that tests the given extension function. This is intended to generate test methods that test both a pure-Python version and an extension version using common test code. The extension test will raise SkipTest if the extension is not found. Sample usage: class MyTest(TestCase); def _do_some_test(self, func_impl): self.assertEqual('foo', func_impl()) test_foo = functest_builder(_do_some_test, foo_py) test_foo_extension = ext_functest_builder(_do_some_test, _foo_c) Args: method: The method to run. It must must two parameters, self and the function implementation to test. func: The function implementation to pass to method. """ def do_test(self) -> None: if not isinstance(func, types.BuiltinFunctionType): raise SkipTest(f"{func} extension not found") method(self, func) return do_test def build_pack(f, objects_spec, store=None): """Write test pack data from a concise spec. Args: f: A file-like object to write the pack to. objects_spec: A list of (type_num, obj). For non-delta types, obj is the string of that object's data. For delta types, obj is a tuple of (base, data), where: * base can be either an index in objects_spec of the base for that * delta; or for a ref delta, a SHA, in which case the resulting pack * will be thin and the base will be an external ref. * data is a string of the full, non-deltified data for that object. Note that offsets/refs and deltas are computed within this function. store: An optional ObjectStore for looking up external refs. Returns: A list of tuples in the order specified by objects_spec: (offset, type num, data, sha, CRC32) """ sf = SHA1Writer(f) num_objects = len(objects_spec) write_pack_header(sf.write, num_objects) full_objects = {} offsets = {} crc32s = {} while len(full_objects) < num_objects: for i, (type_num, data) in enumerate(objects_spec): if type_num not in DELTA_TYPES: full_objects[i] = (type_num, data, obj_sha(type_num, [data])) continue base, data = data if isinstance(base, int): if base not in full_objects: continue base_type_num, _, _ = full_objects[base] else: base_type_num, _ = store.get_raw(base) full_objects[i] = ( base_type_num, data, obj_sha(base_type_num, [data]), ) for i, (type_num, obj) in enumerate(objects_spec): offset = f.tell() if type_num == OFS_DELTA: base_index, data = obj base = offset - offsets[base_index] _, base_data, _ = full_objects[base_index] obj = (base, list(create_delta(base_data, data))) elif type_num == REF_DELTA: base_ref, data = obj if isinstance(base_ref, int): _, base_data, base = full_objects[base_ref] else: base_type_num, base_data = store.get_raw(base_ref) base = obj_sha(base_type_num, base_data) obj = (base, list(create_delta(base_data, data))) crc32 = write_pack_object(sf.write, type_num, obj) offsets[i] = offset crc32s[i] = crc32 expected = [] for i in range(num_objects): type_num, data, sha = full_objects[i] assert len(sha) == 20 expected.append((offsets[i], type_num, data, sha, crc32s[i])) sf.write_sha() f.seek(0) return expected def build_commit_graph(object_store, commit_spec, trees=None, attrs=None): """Build a commit graph from a concise specification. Sample usage: >>> c1, c2, c3 = build_commit_graph(store, [[1], [2, 1], [3, 1, 2]]) >>> store[store[c3].parents[0]] == c1 True >>> store[store[c3].parents[1]] == c2 True If not otherwise specified, commits will refer to the empty tree and have commit times increasing in the same order as the commit spec. Args: object_store: An ObjectStore to commit objects to. commit_spec: An iterable of iterables of ints defining the commit graph. Each entry defines one commit, and entries must be in topological order. The first element of each entry is a commit number, and the remaining elements are its parents. The commit numbers are only meaningful for the call to make_commits; since real commit objects are created, they will get created with real, opaque SHAs. trees: An optional dict of commit number -> tree spec for building trees for commits. The tree spec is an iterable of (path, blob, mode) or (path, blob) entries; if mode is omitted, it defaults to the normal file mode (0100644). attrs: A dict of commit number -> (dict of attribute -> value) for assigning additional values to the commits. Returns: The list of commit objects created. Raises: ValueError: If an undefined commit identifier is listed as a parent. """ if trees is None: trees = {} if attrs is None: attrs = {} commit_time = 0 nums = {} commits = [] for commit in commit_spec: commit_num = commit[0] try: parent_ids = [nums[pn] for pn in commit[1:]] except KeyError as exc: (missing_parent,) = exc.args raise ValueError(f"Unknown parent {missing_parent}") from exc blobs = [] for entry in trees.get(commit_num, []): if len(entry) == 2: path, blob = entry entry = (path, blob, F) path, blob, mode = entry blobs.append((path, blob.id, mode)) object_store.add_object(blob) tree_id = commit_tree(object_store, blobs) commit_attrs = { "message": (f"Commit {commit_num}").encode("ascii"), "parents": parent_ids, "tree": tree_id, "commit_time": commit_time, } commit_attrs.update(attrs.get(commit_num, {})) commit_obj = make_commit(**commit_attrs) # By default, increment the time by a lot. Out-of-order commits should # be closer together than this because their main cause is clock skew. commit_time = commit_attrs["commit_time"] + 100 nums[commit_num] = commit_obj.id object_store.add_object(commit_obj) commits.append(commit_obj) return commits def setup_warning_catcher(): """Wrap warnings.showwarning with code that records warnings.""" caught_warnings = [] original_showwarning = warnings.showwarning def custom_showwarning(*args, **kwargs) -> None: caught_warnings.append(args[0]) warnings.showwarning = custom_showwarning def restore_showwarning() -> None: warnings.showwarning = original_showwarning return caught_warnings, restore_showwarning ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/walk.py0000644000175100002000000004024614731042555015614 0ustar00runnerdocker# walk.py -- General implementation of walking commits and their contents. # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """General implementation of walking commits and their contents.""" import collections import heapq from itertools import chain from typing import Optional from .diff_tree import ( RENAME_CHANGE_TYPES, RenameDetector, TreeChange, tree_changes, tree_changes_for_merge, ) from .errors import MissingCommitError from .objects import Commit, ObjectID, Tag ORDER_DATE = "date" ORDER_TOPO = "topo" ALL_ORDERS = (ORDER_DATE, ORDER_TOPO) # Maximum number of commits to walk past a commit time boundary. _MAX_EXTRA_COMMITS = 5 class WalkEntry: """Object encapsulating a single result from a walk.""" def __init__(self, walker, commit) -> None: self.commit = commit self._store = walker.store self._get_parents = walker.get_parents self._changes: dict[str, list[TreeChange]] = {} self._rename_detector = walker.rename_detector def changes(self, path_prefix=None): """Get the tree changes for this entry. Args: path_prefix: Portion of the path in the repository to use to filter changes. Must be a directory name. Must be a full, valid, path reference (no partial names or wildcards). Returns: For commits with up to one parent, a list of TreeChange objects; if the commit has no parents, these will be relative to the empty tree. For merge commits, a list of lists of TreeChange objects; see dulwich.diff.tree_changes_for_merge. """ cached = self._changes.get(path_prefix) if cached is None: commit = self.commit if not self._get_parents(commit): changes_func = tree_changes parent = None elif len(self._get_parents(commit)) == 1: changes_func = tree_changes parent = self._store[self._get_parents(commit)[0]].tree if path_prefix: mode, subtree_sha = parent.lookup_path( self._store.__getitem__, path_prefix, ) parent = self._store[subtree_sha] else: changes_func = tree_changes_for_merge parent = [self._store[p].tree for p in self._get_parents(commit)] if path_prefix: parent_trees = [self._store[p] for p in parent] parent = [] for p in parent_trees: try: mode, st = p.lookup_path( self._store.__getitem__, path_prefix, ) except KeyError: pass else: parent.append(st) commit_tree_sha = commit.tree if path_prefix: commit_tree = self._store[commit_tree_sha] mode, commit_tree_sha = commit_tree.lookup_path( self._store.__getitem__, path_prefix, ) cached = list( changes_func( self._store, parent, commit_tree_sha, rename_detector=self._rename_detector, ) ) self._changes[path_prefix] = cached return self._changes[path_prefix] def __repr__(self) -> str: return f"" class _CommitTimeQueue: """Priority queue of WalkEntry objects by commit time.""" def __init__(self, walker: "Walker") -> None: self._walker = walker self._store = walker.store self._get_parents = walker.get_parents self._excluded = walker.excluded self._pq: list[tuple[int, Commit]] = [] self._pq_set: set[ObjectID] = set() self._seen: set[ObjectID] = set() self._done: set[ObjectID] = set() self._min_time = walker.since self._last = None self._extra_commits_left = _MAX_EXTRA_COMMITS self._is_finished = False for commit_id in chain(walker.include, walker.excluded): self._push(commit_id) def _push(self, object_id: bytes) -> None: try: obj = self._store[object_id] except KeyError as exc: raise MissingCommitError(object_id) from exc if isinstance(obj, Tag): self._push(obj.object[1]) return # TODO(jelmer): What to do about non-Commit and non-Tag objects? commit = obj if commit.id not in self._pq_set and commit.id not in self._done: heapq.heappush(self._pq, (-commit.commit_time, commit)) self._pq_set.add(commit.id) self._seen.add(commit.id) def _exclude_parents(self, commit) -> None: excluded = self._excluded seen = self._seen todo = [commit] while todo: commit = todo.pop() for parent in self._get_parents(commit): if parent not in excluded and parent in seen: # TODO: This is inefficient unless the object store does # some caching (which DiskObjectStore currently does not). # We could either add caching in this class or pass around # parsed queue entry objects instead of commits. todo.append(self._store[parent]) excluded.add(parent) def next(self): if self._is_finished: return None while self._pq: _, commit = heapq.heappop(self._pq) sha = commit.id self._pq_set.remove(sha) if sha in self._done: continue self._done.add(sha) for parent_id in self._get_parents(commit): self._push(parent_id) reset_extra_commits = True is_excluded = sha in self._excluded if is_excluded: self._exclude_parents(commit) if self._pq and all(c.id in self._excluded for _, c in self._pq): _, n = self._pq[0] if self._last and n.commit_time >= self._last.commit_time: # If the next commit is newer than the last one, we # need to keep walking in case its parents (which we # may not have seen yet) are excluded. This gives the # excluded set a chance to "catch up" while the commit # is still in the Walker's output queue. reset_extra_commits = True else: reset_extra_commits = False if self._min_time is not None and commit.commit_time < self._min_time: # We want to stop walking at min_time, but commits at the # boundary may be out of order with respect to their parents. # So we walk _MAX_EXTRA_COMMITS more commits once we hit this # boundary. reset_extra_commits = False if reset_extra_commits: # We're not at a boundary, so reset the counter. self._extra_commits_left = _MAX_EXTRA_COMMITS else: self._extra_commits_left -= 1 if not self._extra_commits_left: break if not is_excluded: self._last = commit return WalkEntry(self._walker, commit) self._is_finished = True return None __next__ = next class Walker: """Object for performing a walk of commits in a store. Walker objects are initialized with a store and other options and can then be treated as iterators of Commit objects. """ def __init__( self, store, include: list[bytes], exclude: Optional[list[bytes]] = None, order: str = "date", reverse: bool = False, max_entries: Optional[int] = None, paths: Optional[list[bytes]] = None, rename_detector: Optional[RenameDetector] = None, follow: bool = False, since: Optional[int] = None, until: Optional[int] = None, get_parents=lambda commit: commit.parents, queue_cls=_CommitTimeQueue, ) -> None: """Constructor. Args: store: ObjectStore instance for looking up objects. include: Iterable of SHAs of commits to include along with their ancestors. exclude: Iterable of SHAs of commits to exclude along with their ancestors, overriding includes. order: ORDER_* constant specifying the order of results. Anything other than ORDER_DATE may result in O(n) memory usage. reverse: If True, reverse the order of output, requiring O(n) memory. max_entries: The maximum number of entries to yield, or None for no limit. paths: Iterable of file or subtree paths to show entries for. rename_detector: diff.RenameDetector object for detecting renames. follow: If True, follow path across renames/copies. Forces a default rename_detector. since: Timestamp to list commits after. until: Timestamp to list commits before. get_parents: Method to retrieve the parents of a commit queue_cls: A class to use for a queue of commits, supporting the iterator protocol. The constructor takes a single argument, the Walker. """ # Note: when adding arguments to this method, please also update # dulwich.repo.BaseRepo.get_walker if order not in ALL_ORDERS: raise ValueError(f"Unknown walk order {order}") self.store = store if isinstance(include, bytes): # TODO(jelmer): Really, this should require a single type. # Print deprecation warning here? include = [include] self.include = include self.excluded = set(exclude or []) self.order = order self.reverse = reverse self.max_entries = max_entries self.paths = (paths and set(paths)) or None if follow and not rename_detector: rename_detector = RenameDetector(store) self.rename_detector = rename_detector self.get_parents = get_parents self.follow = follow self.since = since self.until = until self._num_entries = 0 self._queue = queue_cls(self) self._out_queue: collections.deque[WalkEntry] = collections.deque() def _path_matches(self, changed_path) -> bool: if changed_path is None: return False if self.paths is None: return True for followed_path in self.paths: if changed_path == followed_path: return True if ( changed_path.startswith(followed_path) and changed_path[len(followed_path)] == b"/"[0] ): return True return False def _change_matches(self, change) -> bool: assert self.paths if not change: return False old_path = change.old.path new_path = change.new.path if self._path_matches(new_path): if self.follow and change.type in RENAME_CHANGE_TYPES: self.paths.add(old_path) self.paths.remove(new_path) return True elif self._path_matches(old_path): return True return False def _should_return(self, entry) -> Optional[bool]: """Determine if a walk entry should be returned.. Args: entry: The WalkEntry to consider. Returns: True if the WalkEntry should be returned by this walk, or False otherwise (e.g. if it doesn't match any requested paths). """ commit = entry.commit if self.since is not None and commit.commit_time < self.since: return False if self.until is not None and commit.commit_time > self.until: return False if commit.id in self.excluded: return False if self.paths is None: return True if len(self.get_parents(commit)) > 1: for path_changes in entry.changes(): # For merge commits, only include changes with conflicts for # this path. Since a rename conflict may include different # old.paths, we have to check all of them. for change in path_changes: if self._change_matches(change): return True else: for change in entry.changes(): if self._change_matches(change): return True return None def _next(self): max_entries = self.max_entries while max_entries is None or self._num_entries < max_entries: entry = next(self._queue) if entry is not None: self._out_queue.append(entry) if entry is None or len(self._out_queue) > _MAX_EXTRA_COMMITS: if not self._out_queue: return None entry = self._out_queue.popleft() if self._should_return(entry): self._num_entries += 1 return entry return None def _reorder(self, results): """Possibly reorder a results iterator. Args: results: An iterator of WalkEntry objects, in the order returned from the queue_cls. Returns: An iterator or list of WalkEntry objects, in the order required by the Walker. """ if self.order == ORDER_TOPO: results = _topo_reorder(results, self.get_parents) if self.reverse: results = reversed(list(results)) return results def __iter__(self): return iter(self._reorder(iter(self._next, None))) def _topo_reorder(entries, get_parents=lambda commit: commit.parents): """Reorder an iterable of entries topologically. This works best assuming the entries are already in almost-topological order, e.g. in commit time order. Args: entries: An iterable of WalkEntry objects. get_parents: Optional function for getting the parents of a commit. Returns: iterator over WalkEntry objects from entries in FIFO order, except where a parent would be yielded before any of its children. """ todo = collections.deque() pending = {} num_children = collections.defaultdict(int) for entry in entries: todo.append(entry) for p in get_parents(entry.commit): num_children[p] += 1 while todo: entry = todo.popleft() commit = entry.commit commit_id = commit.id if num_children[commit_id]: pending[commit_id] = entry continue for parent_id in get_parents(commit): num_children[parent_id] -= 1 if not num_children[parent_id]: parent_entry = pending.pop(parent_id, None) if parent_entry: todo.appendleft(parent_entry) yield entry ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich/web.py0000644000175100002000000004477514731042555015446 0ustar00runnerdocker# web.py -- WSGI smart-http server # Copyright (C) 2010 Google, Inc. # Copyright (C) 2012 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """HTTP server for dulwich that implements the git smart HTTP protocol.""" import os import re import sys import time from collections.abc import Iterator from io import BytesIO from typing import Callable, ClassVar, Optional from urllib.parse import parse_qs from wsgiref.simple_server import ( ServerHandler, WSGIRequestHandler, WSGIServer, make_server, ) from dulwich import log_utils from .protocol import ReceivableProtocol from .repo import BaseRepo, NotGitRepository, Repo from .server import ( DEFAULT_HANDLERS, Backend, DictBackend, generate_info_refs, generate_objects_info_packs, ) logger = log_utils.getLogger(__name__) # HTTP error strings HTTP_OK = "200 OK" HTTP_NOT_FOUND = "404 Not Found" HTTP_FORBIDDEN = "403 Forbidden" HTTP_ERROR = "500 Internal Server Error" NO_CACHE_HEADERS = [ ("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"), ("Pragma", "no-cache"), ("Cache-Control", "no-cache, max-age=0, must-revalidate"), ] def cache_forever_headers(now=None): if now is None: now = time.time() return [ ("Date", date_time_string(now)), ("Expires", date_time_string(now + 31536000)), ("Cache-Control", "public, max-age=31536000"), ] def date_time_string(timestamp: Optional[float] = None) -> str: # From BaseHTTPRequestHandler.date_time_string in BaseHTTPServer.py in the # Python 2.6.5 standard library, following modifications: # - Made a global rather than an instance method. # - weekdayname and monthname are renamed and locals rather than class # variables. # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] months = [ None, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ] if timestamp is None: timestamp = time.time() year, month, day, hh, mm, ss, wd = time.gmtime(timestamp)[:7] return "%s, %02d %3s %4d %02d:%02d:%02d GMD" % ( # noqa: UP031 weekdays[wd], day, months[month], year, hh, mm, ss, ) def url_prefix(mat) -> str: """Extract the URL prefix from a regex match. Args: mat: A regex match object. Returns: The URL prefix, defined as the text before the match in the original string. Normalized to start with one leading slash and end with zero. """ return "/" + mat.string[: mat.start()].strip("/") def get_repo(backend, mat) -> BaseRepo: """Get a Repo instance for the given backend and URL regex match.""" return backend.open_repository(url_prefix(mat)) def send_file(req, f, content_type): """Send a file-like object to the request output. Args: req: The HTTPGitRequest object to send output to. f: An open file-like object to send; will be closed. content_type: The MIME type for the file. Returns: Iterator over the contents of the file, as chunks. """ if f is None: yield req.not_found("File not found") return try: req.respond(HTTP_OK, content_type) while True: data = f.read(10240) if not data: break yield data except OSError: yield req.error("Error reading file") finally: f.close() def _url_to_path(url): return url.replace("/", os.path.sep) def get_text_file(req, backend, mat): req.nocache() path = _url_to_path(mat.group()) logger.info("Sending plain text file %s", path) return send_file(req, get_repo(backend, mat).get_named_file(path), "text/plain") def get_loose_object(req, backend, mat): sha = (mat.group(1) + mat.group(2)).encode("ascii") logger.info("Sending loose object %s", sha) object_store = get_repo(backend, mat).object_store if not object_store.contains_loose(sha): yield req.not_found("Object not found") return try: data = object_store[sha].as_legacy_object() except OSError: yield req.error("Error reading object") return req.cache_forever() req.respond(HTTP_OK, "application/x-git-loose-object") yield data def get_pack_file(req, backend, mat): req.cache_forever() path = _url_to_path(mat.group()) logger.info("Sending pack file %s", path) return send_file( req, get_repo(backend, mat).get_named_file(path), "application/x-git-packed-objects", ) def get_idx_file(req, backend, mat): req.cache_forever() path = _url_to_path(mat.group()) logger.info("Sending pack file %s", path) return send_file( req, get_repo(backend, mat).get_named_file(path), "application/x-git-packed-objects-toc", ) def get_info_refs(req, backend, mat): params = parse_qs(req.environ["QUERY_STRING"]) service = params.get("service", [None])[0] try: repo = get_repo(backend, mat) except NotGitRepository as e: yield req.not_found(str(e)) return if service and not req.dumb: handler_cls = req.handlers.get(service.encode("ascii"), None) if handler_cls is None: yield req.forbidden("Unsupported service") return req.nocache() write = req.respond(HTTP_OK, f"application/x-{service}-advertisement") proto = ReceivableProtocol(BytesIO().read, write) handler = handler_cls( backend, [url_prefix(mat)], proto, stateless_rpc=True, advertise_refs=True, ) handler.proto.write_pkt_line(b"# service=" + service.encode("ascii") + b"\n") handler.proto.write_pkt_line(None) handler.handle() else: # non-smart fallback # TODO: select_getanyfile() (see http-backend.c) req.nocache() req.respond(HTTP_OK, "text/plain") logger.info("Emulating dumb info/refs") yield from generate_info_refs(repo) def get_info_packs(req, backend, mat): req.nocache() req.respond(HTTP_OK, "text/plain") logger.info("Emulating dumb info/packs") return generate_objects_info_packs(get_repo(backend, mat)) def _chunk_iter(f): while True: line = f.readline() length = int(line.rstrip(), 16) chunk = f.read(length + 2) if length == 0: break yield chunk[:-2] class ChunkReader: def __init__(self, f) -> None: self._iter = _chunk_iter(f) self._buffer: list[bytes] = [] def read(self, n): while sum(map(len, self._buffer)) < n: try: self._buffer.append(next(self._iter)) except StopIteration: break f = b"".join(self._buffer) ret = f[:n] self._buffer = [f[n:]] return ret class _LengthLimitedFile: """Wrapper class to limit the length of reads from a file-like object. This is used to ensure EOF is read from the wsgi.input object once Content-Length bytes are read. This behavior is required by the WSGI spec but not implemented in wsgiref as of 2.5. """ def __init__(self, input, max_bytes) -> None: self._input = input self._bytes_avail = max_bytes def read(self, size=-1): if self._bytes_avail <= 0: return b"" if size == -1 or size > self._bytes_avail: size = self._bytes_avail self._bytes_avail -= size return self._input.read(size) # TODO: support more methods as necessary def handle_service_request(req, backend, mat): service = mat.group().lstrip("/") logger.info("Handling service request for %s", service) handler_cls = req.handlers.get(service.encode("ascii"), None) if handler_cls is None: yield req.forbidden("Unsupported service") return try: get_repo(backend, mat) except NotGitRepository as e: yield req.not_found(str(e)) return req.nocache() write = req.respond(HTTP_OK, f"application/x-{service}-result") if req.environ.get("HTTP_TRANSFER_ENCODING") == "chunked": read = ChunkReader(req.environ["wsgi.input"]).read else: read = req.environ["wsgi.input"].read proto = ReceivableProtocol(read, write) # TODO(jelmer): Find a way to pass in repo, rather than having handler_cls # reopen. handler = handler_cls(backend, [url_prefix(mat)], proto, stateless_rpc=True) handler.handle() class HTTPGitRequest: """Class encapsulating the state of a single git HTTP request. Attributes: environ: the WSGI environment for the request. """ def __init__( self, environ, start_response, dumb: bool = False, handlers=None ) -> None: self.environ = environ self.dumb = dumb self.handlers = handlers self._start_response = start_response self._cache_headers: list[tuple[str, str]] = [] self._headers: list[tuple[str, str]] = [] def add_header(self, name, value) -> None: """Add a header to the response.""" self._headers.append((name, value)) def respond( self, status: str = HTTP_OK, content_type: Optional[str] = None, headers: Optional[list[tuple[str, str]]] = None, ): """Begin a response with the given status and other headers.""" if headers: self._headers.extend(headers) if content_type: self._headers.append(("Content-Type", content_type)) self._headers.extend(self._cache_headers) return self._start_response(status, self._headers) def not_found(self, message: str) -> bytes: """Begin a HTTP 404 response and return the text of a message.""" self._cache_headers = [] logger.info("Not found: %s", message) self.respond(HTTP_NOT_FOUND, "text/plain") return message.encode("ascii") def forbidden(self, message: str) -> bytes: """Begin a HTTP 403 response and return the text of a message.""" self._cache_headers = [] logger.info("Forbidden: %s", message) self.respond(HTTP_FORBIDDEN, "text/plain") return message.encode("ascii") def error(self, message: str) -> bytes: """Begin a HTTP 500 response and return the text of a message.""" self._cache_headers = [] logger.error("Error: %s", message) self.respond(HTTP_ERROR, "text/plain") return message.encode("ascii") def nocache(self) -> None: """Set the response to never be cached by the client.""" self._cache_headers = NO_CACHE_HEADERS def cache_forever(self) -> None: """Set the response to be cached forever by the client.""" self._cache_headers = cache_forever_headers() class HTTPGitApplication: """Class encapsulating the state of a git WSGI application. Attributes: backend: the Backend object backing this application """ services: ClassVar[ dict[ tuple[str, re.Pattern], Callable[[HTTPGitRequest, Backend, re.Match], Iterator[bytes]], ] ] = { ("GET", re.compile("/HEAD$")): get_text_file, ("GET", re.compile("/info/refs$")): get_info_refs, ("GET", re.compile("/objects/info/alternates$")): get_text_file, ("GET", re.compile("/objects/info/http-alternates$")): get_text_file, ("GET", re.compile("/objects/info/packs$")): get_info_packs, ( "GET", re.compile("/objects/([0-9a-f]{2})/([0-9a-f]{38})$"), ): get_loose_object, ( "GET", re.compile("/objects/pack/pack-([0-9a-f]{40})\\.pack$"), ): get_pack_file, ( "GET", re.compile("/objects/pack/pack-([0-9a-f]{40})\\.idx$"), ): get_idx_file, ("POST", re.compile("/git-upload-pack$")): handle_service_request, ("POST", re.compile("/git-receive-pack$")): handle_service_request, } def __init__( self, backend, dumb: bool = False, handlers=None, fallback_app=None ) -> None: self.backend = backend self.dumb = dumb self.handlers = dict(DEFAULT_HANDLERS) self.fallback_app = fallback_app if handlers is not None: self.handlers.update(handlers) def __call__(self, environ, start_response): path = environ["PATH_INFO"] method = environ["REQUEST_METHOD"] req = HTTPGitRequest( environ, start_response, dumb=self.dumb, handlers=self.handlers ) # environ['QUERY_STRING'] has qs args handler = None for smethod, spath in self.services.keys(): if smethod != method: continue mat = spath.search(path) if mat: handler = self.services[smethod, spath] break if handler is None: if self.fallback_app is not None: return self.fallback_app(environ, start_response) else: return [req.not_found("Sorry, that method is not supported")] return handler(req, self.backend, mat) class GunzipFilter: """WSGI middleware that unzips gzip-encoded requests before passing on to the underlying application. """ def __init__(self, application) -> None: self.app = application def __call__(self, environ, start_response): import gzip if environ.get("HTTP_CONTENT_ENCODING", "") == "gzip": environ["wsgi.input"] = gzip.GzipFile( filename=None, fileobj=environ["wsgi.input"], mode="rb" ) del environ["HTTP_CONTENT_ENCODING"] if "CONTENT_LENGTH" in environ: del environ["CONTENT_LENGTH"] return self.app(environ, start_response) class LimitedInputFilter: """WSGI middleware that limits the input length of a request to that specified in Content-Length. """ def __init__(self, application) -> None: self.app = application def __call__(self, environ, start_response): # This is not necessary if this app is run from a conforming WSGI # server. Unfortunately, there's no way to tell that at this point. # TODO: git may used HTTP/1.1 chunked encoding instead of specifying # content-length content_length = environ.get("CONTENT_LENGTH", "") if content_length: environ["wsgi.input"] = _LengthLimitedFile( environ["wsgi.input"], int(content_length) ) return self.app(environ, start_response) def make_wsgi_chain(*args, **kwargs): """Factory function to create an instance of HTTPGitApplication, correctly wrapped with needed middleware. """ app = HTTPGitApplication(*args, **kwargs) wrapped_app = LimitedInputFilter(GunzipFilter(app)) return wrapped_app class ServerHandlerLogger(ServerHandler): """ServerHandler that uses dulwich's logger for logging exceptions.""" def log_exception(self, exc_info) -> None: logger.exception( "Exception happened during processing of request", exc_info=exc_info, ) def log_message(self, format, *args) -> None: logger.info(format, *args) def log_error(self, *args) -> None: logger.error(*args) class WSGIRequestHandlerLogger(WSGIRequestHandler): """WSGIRequestHandler that uses dulwich's logger for logging exceptions.""" def log_exception(self, exc_info) -> None: logger.exception( "Exception happened during processing of request", exc_info=exc_info, ) def log_message(self, format, *args) -> None: logger.info(format, *args) def log_error(self, *args) -> None: logger.error(*args) def handle(self) -> None: """Handle a single HTTP request.""" self.raw_requestline = self.rfile.readline() if not self.parse_request(): # An error code has been sent, just exit return handler = ServerHandlerLogger( self.rfile, self.wfile, # type: ignore self.get_stderr(), self.get_environ(), ) handler.request_handler = self # type: ignore # backpointer for logging handler.run(self.server.get_app()) # type: ignore class WSGIServerLogger(WSGIServer): def handle_error(self, request, client_address) -> None: """Handle an error.""" logger.exception( f"Exception happened during processing of request from {client_address!s}" ) def main(argv=sys.argv) -> None: """Entry point for starting an HTTP git server.""" import optparse parser = optparse.OptionParser() parser.add_option( "-l", "--listen_address", dest="listen_address", default="localhost", help="Binding IP address.", ) parser.add_option( "-p", "--port", dest="port", type=int, default=8000, help="Port to listen on.", ) options, args = parser.parse_args(argv) if len(args) > 1: gitdir = args[1] else: gitdir = os.getcwd() log_utils.default_logging_config() backend = DictBackend({"/": Repo(gitdir)}) app = make_wsgi_chain(backend) server = make_server( options.listen_address, options.port, app, handler_class=WSGIRequestHandlerLogger, server_class=WSGIServerLogger, ) logger.info( "Listening for HTTP connections on %s:%d", options.listen_address, options.port, ) server.serve_forever() if __name__ == "__main__": main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/dulwich.cfg0000644000175100002000000000017314731042555014760 0ustar00runnerdockerpackages: dulwich docformat: restructuredtext projectname: Dulwich projecturl: https://www.dulwich.io/ htmloutput: apidocs ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9924474 dulwich-0.22.7/dulwich.egg-info/0000755000175100002000000000000014731042565015771 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624628.0 dulwich-0.22.7/dulwich.egg-info/PKG-INFO0000644000175100002000000001045014731042564017065 0ustar00runnerdockerMetadata-Version: 2.1 Name: dulwich Version: 0.22.7 Summary: Python Git Library Author-email: Jelmer Vernooij License: Apachev2 or later or GPLv2 Project-URL: Homepage, https://www.dulwich.io/ Project-URL: Repository, https://www.dulwich.io/code/ Project-URL: GitHub, https://github.com/dulwich/dulwich Project-URL: Bug Tracker, https://github.com/dulwich/dulwich/issues Keywords: vcs,git Classifier: Development Status :: 4 - Beta Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Operating System :: POSIX Classifier: Operating System :: Microsoft :: Windows Classifier: Topic :: Software Development :: Version Control Requires-Python: >=3.9 Description-Content-Type: text/x-rst License-File: COPYING Requires-Dist: urllib3>=1.25 Provides-Extra: fastimport Requires-Dist: fastimport; extra == "fastimport" Provides-Extra: https Requires-Dist: urllib3>=1.24.1; extra == "https" Provides-Extra: pgp Requires-Dist: gpg; extra == "pgp" Provides-Extra: paramiko Requires-Dist: paramiko; extra == "paramiko" Provides-Extra: dev Requires-Dist: ruff==0.8.3; extra == "dev" Requires-Dist: mypy==1.13.0; extra == "dev" Dulwich ======= This is the Dulwich project. It aims to provide an interface to git repos (both local and remote) that doesn't call out to git directly but instead uses pure Python. **Main website**: **License**: Apache License, version 2 or GNU General Public License, version 2 or later. SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later The project is named after the part of London that Mr. and Mrs. Git live in the particular Monty Python sketch. Installation ------------ By default, Dulwich' setup.py will attempt to build and install the optional Rust extensions. The reason for this is that they significantly improve the performance since some low-level operations that are executed often are much slower in CPython. If you don't want to install the Rust bindings, specify the --pure argument to setup.py:: $ python setup.py --pure install or if you are installing from pip:: $ pip install --no-binary dulwich dulwich --config-settings "--build-option=--pure" Note that you can also specify --build-option in a `requirements.txt `_ file, e.g. like this:: dulwich --config-settings "--build-option=--pure" Getting started --------------- Dulwich comes with both a lower-level API and higher-level plumbing ("porcelain"). For example, to use the lower level API to access the commit message of the last commit:: >>> from dulwich.repo import Repo >>> r = Repo('.') >>> r.head() '57fbe010446356833a6ad1600059d80b1e731e15' >>> c = r[r.head()] >>> c >>> c.message 'Add note about encoding.\n' And to print it using porcelain:: >>> from dulwich import porcelain >>> porcelain.log('.', max_entries=1) -------------------------------------------------- commit: 57fbe010446356833a6ad1600059d80b1e731e15 Author: Jelmer Vernooij Date: Sat Apr 29 2017 23:57:34 +0000 Add note about encoding. Further documentation --------------------- The dulwich documentation can be found in docs/ and built by running ``make doc``. It can also be found `on the web `_. Help ---- There is a *#dulwich* IRC channel on the `OFTC `_, and a `dulwich-discuss `_ mailing list. Contributing ------------ For a full list of contributors, see the git logs or `AUTHORS `_. If you'd like to contribute to Dulwich, see the `CONTRIBUTING `_ file and `list of open issues `_. Supported versions of Python ---------------------------- At the moment, Dulwich supports (and is tested on) CPython 3.9 and later and Pypy. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624628.0 dulwich-0.22.7/dulwich.egg-info/SOURCES.txt0000644000175100002000000002013714731042564017657 0ustar00runnerdocker.testr.conf AUTHORS CONTRIBUTING.rst COPYING Cargo.lock Cargo.toml MANIFEST.in Makefile NEWS README.rst TODO dulwich.cfg pyproject.toml setup.py tox.ini bin/dul-receive-pack bin/dul-upload-pack crates/diff-tree/Cargo.toml crates/diff-tree/src/lib.rs crates/objects/Cargo.toml crates/objects/src/lib.rs crates/pack/Cargo.toml crates/pack/src/lib.rs docs/Makefile docs/conf.py docs/index.txt docs/make.bat docs/protocol.txt docs/requirements.txt docs/api/index.txt docs/tutorial/Makefile docs/tutorial/conclusion.txt docs/tutorial/encoding.txt docs/tutorial/file-format.txt docs/tutorial/index.txt docs/tutorial/introduction.txt docs/tutorial/object-store.txt docs/tutorial/porcelain.txt docs/tutorial/remote.txt docs/tutorial/repo.txt docs/tutorial/tag.txt dulwich/__init__.py dulwich/__main__.py dulwich/archive.py dulwich/bundle.py dulwich/cli.py dulwich/client.py dulwich/config.py dulwich/credentials.py dulwich/diff_tree.py dulwich/errors.py dulwich/fastexport.py dulwich/file.py dulwich/graph.py dulwich/greenthreads.py dulwich/hooks.py dulwich/ignore.py dulwich/index.py dulwich/lfs.py dulwich/line_ending.py dulwich/log_utils.py dulwich/lru_cache.py dulwich/mailmap.py dulwich/object_store.py dulwich/objects.py dulwich/objectspec.py dulwich/pack.py dulwich/patch.py dulwich/porcelain.py dulwich/protocol.py dulwich/py.typed dulwich/reflog.py dulwich/refs.py dulwich/repo.py dulwich/server.py dulwich/stash.py dulwich/stdint.h dulwich/submodule.py dulwich/walk.py dulwich/web.py dulwich.egg-info/PKG-INFO dulwich.egg-info/SOURCES.txt dulwich.egg-info/dependency_links.txt dulwich.egg-info/entry_points.txt dulwich.egg-info/not-zip-safe dulwich.egg-info/requires.txt dulwich.egg-info/top_level.txt dulwich/cloud/__init__.py dulwich/cloud/gcs.py dulwich/contrib/__init__.py dulwich/contrib/diffstat.py dulwich/contrib/paramiko_vendor.py dulwich/contrib/release_robot.py dulwich/contrib/requests_vendor.py dulwich/contrib/swift.py dulwich/tests/__init__.py dulwich/tests/test_object_store.py dulwich/tests/utils.py examples/clone.py examples/config.py examples/diff.py examples/gcs.py examples/latest_change.py examples/memoryrepo.py examples/rename-branch.py testdata/blobs/11/11111111111111111111111111111111111111 testdata/blobs/6f/670c0fb53f9463760b7295fbb814e965fb20c8 testdata/blobs/95/4a536f7819d40e6f637f849ee187dd10066349 testdata/blobs/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391 testdata/commits/0d/89f20333fbb1d2f3a94da77f4981373d8f4310 testdata/commits/5d/ac377bdded4c9aeb8dff595f0faeebcc8498cc testdata/commits/60/dacdc733de308bb77bb76ce0fb0f9b44c9769e testdata/indexes/index testdata/packs/pack-bc63ddad95e7321ee734ea11a7a62d314e0d7481.idx testdata/packs/pack-bc63ddad95e7321ee734ea11a7a62d314e0d7481.pack testdata/repos/.gitattributes testdata/repos/issue88_expect_ack_nak_client.export testdata/repos/issue88_expect_ack_nak_other.export testdata/repos/issue88_expect_ack_nak_server.export testdata/repos/server_new.export testdata/repos/server_old.export testdata/repos/a.git/HEAD testdata/repos/a.git/packed-refs testdata/repos/a.git/objects/28/237f4dc30d0d462658d6b937b08a0f0b6ef55a testdata/repos/a.git/objects/2a/72d929692c41d8554c07f6301757ba18a65d91 testdata/repos/a.git/objects/4e/f30bbfe26431a69c3820d3a683df54d688f2ec testdata/repos/a.git/objects/4f/2e6529203aa6d44b5af6e3292c837ceda003f9 testdata/repos/a.git/objects/7d/9a07d797595ef11344549b8d08198e48c15364 testdata/repos/a.git/objects/a2/96d0bb611188cabb256919f36bc30117cca005 testdata/repos/a.git/objects/a9/0fa2d900a17e99b433217e988c4eb4a2e9a097 testdata/repos/a.git/objects/b0/931cadc54336e78a1d980420e3268903b57a50 testdata/repos/a.git/objects/ff/d47d45845a8f6576491e1edb97e3fe6a850e7f testdata/repos/a.git/refs/heads/master testdata/repos/a.git/refs/tags/mytag testdata/repos/empty.git/HEAD testdata/repos/empty.git/config testdata/repos/empty.git/objects/info/.gitignore testdata/repos/empty.git/objects/pack/.gitignore testdata/repos/empty.git/refs/heads/.gitignore testdata/repos/empty.git/refs/tags/.gitignore testdata/repos/ooo_merge.git/HEAD testdata/repos/ooo_merge.git/objects/29/69be3e8ee1c0222396a5611407e4769f14e54b testdata/repos/ooo_merge.git/objects/38/74e9c60a6d149c44c928140f250d81e6381520 testdata/repos/ooo_merge.git/objects/6f/670c0fb53f9463760b7295fbb814e965fb20c8 testdata/repos/ooo_merge.git/objects/70/c190eb48fa8bbb50ddc692a17b44cb781af7f6 testdata/repos/ooo_merge.git/objects/76/01d7f6231db6a57f7bbb79ee52e4d462fd44d1 testdata/repos/ooo_merge.git/objects/90/182552c4a85a45ec2a835cadc3451bebdfe870 testdata/repos/ooo_merge.git/objects/95/4a536f7819d40e6f637f849ee187dd10066349 testdata/repos/ooo_merge.git/objects/b2/a2766a2879c209ab1176e7e778b81ae422eeaa testdata/repos/ooo_merge.git/objects/f5/07291b64138b875c28e03469025b1ea20bc614 testdata/repos/ooo_merge.git/objects/f9/e39b120c68182a4ba35349f832d0e4e61f485c testdata/repos/ooo_merge.git/objects/fb/5b0425c7ce46959bec94d54b9a157645e114f5 testdata/repos/ooo_merge.git/refs/heads/master testdata/repos/refs.git/HEAD testdata/repos/refs.git/packed-refs testdata/repos/refs.git/objects/3b/9e5457140e738c2dcd39bf6d7acf88379b90d1 testdata/repos/refs.git/objects/3e/c9c43c84ff242e3ef4a9fc5bc111fd780a76a8 testdata/repos/refs.git/objects/42/d06bd4b77fed026b154d16493e5deab78f02ec testdata/repos/refs.git/objects/a1/8114c31713746a33a2e70d9914d1ef3e781425 testdata/repos/refs.git/objects/cd/a609072918d7b70057b6bef9f4c2537843fcfe testdata/repos/refs.git/objects/df/6800012397fb85c56e7418dd4eb9405dee075c testdata/repos/refs.git/refs/heads/40-char-ref-aaaaaaaaaaaaaaaaaa testdata/repos/refs.git/refs/heads/loop testdata/repos/refs.git/refs/heads/master testdata/repos/refs.git/refs/tags/refs-0.2 testdata/repos/simple_merge.git/HEAD testdata/repos/simple_merge.git/objects/0d/89f20333fbb1d2f3a94da77f4981373d8f4310 testdata/repos/simple_merge.git/objects/1b/6318f651a534b38f9c7aedeebbd56c1e896853 testdata/repos/simple_merge.git/objects/29/69be3e8ee1c0222396a5611407e4769f14e54b testdata/repos/simple_merge.git/objects/4c/ffe90e0a41ad3f5190079d7c8f036bde29cbe6 testdata/repos/simple_merge.git/objects/5d/ac377bdded4c9aeb8dff595f0faeebcc8498cc testdata/repos/simple_merge.git/objects/60/dacdc733de308bb77bb76ce0fb0f9b44c9769e testdata/repos/simple_merge.git/objects/6f/670c0fb53f9463760b7295fbb814e965fb20c8 testdata/repos/simple_merge.git/objects/70/c190eb48fa8bbb50ddc692a17b44cb781af7f6 testdata/repos/simple_merge.git/objects/90/182552c4a85a45ec2a835cadc3451bebdfe870 testdata/repos/simple_merge.git/objects/95/4a536f7819d40e6f637f849ee187dd10066349 testdata/repos/simple_merge.git/objects/ab/64bbdcc51b170d21588e5c5d391ee5c0c96dfd testdata/repos/simple_merge.git/objects/d4/bdad6549dfedf25d3b89d21f506aff575b28a7 testdata/repos/simple_merge.git/objects/d8/0c186a03f423a81b39df39dc87fd269736ca86 testdata/repos/simple_merge.git/objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391 testdata/repos/simple_merge.git/refs/heads/master testdata/repos/submodule/dotgit testdata/tags/71/033db03a03c6a36721efcf1968dd8f8e0cf023 testdata/trees/70/c190eb48fa8bbb50ddc692a17b44cb781af7f6 tests/__init__.py tests/test_archive.py tests/test_blackbox.py tests/test_bundle.py tests/test_client.py tests/test_config.py tests/test_credentials.py tests/test_diff_tree.py tests/test_fastexport.py tests/test_file.py tests/test_grafts.py tests/test_graph.py tests/test_greenthreads.py tests/test_hooks.py tests/test_ignore.py tests/test_index.py tests/test_lfs.py tests/test_line_ending.py tests/test_lru_cache.py tests/test_mailmap.py tests/test_missing_obj_finder.py tests/test_object_store.py tests/test_objects.py tests/test_objectspec.py tests/test_pack.py tests/test_patch.py tests/test_porcelain.py tests/test_protocol.py tests/test_reflog.py tests/test_refs.py tests/test_repository.py tests/test_server.py tests/test_stash.py tests/test_utils.py tests/test_walk.py tests/test_web.py tests/compat/__init__.py tests/compat/server_utils.py tests/compat/test_client.py tests/compat/test_pack.py tests/compat/test_patch.py tests/compat/test_porcelain.py tests/compat/test_repository.py tests/compat/test_server.py tests/compat/test_utils.py tests/compat/test_web.py tests/compat/utils.py tests/contrib/__init__.py tests/contrib/test_paramiko_vendor.py tests/contrib/test_release_robot.py tests/contrib/test_swift.py tests/contrib/test_swift_smoke.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624628.0 dulwich-0.22.7/dulwich.egg-info/dependency_links.txt0000644000175100002000000000000114731042564022036 0ustar00runnerdocker ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624628.0 dulwich-0.22.7/dulwich.egg-info/entry_points.txt0000644000175100002000000000005514731042564021266 0ustar00runnerdocker[console_scripts] dulwich = dulwich.cli:main ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624628.0 dulwich-0.22.7/dulwich.egg-info/not-zip-safe0000644000175100002000000000000114731042564020216 0ustar00runnerdocker ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624628.0 dulwich-0.22.7/dulwich.egg-info/requires.txt0000644000175100002000000000020014731042564020360 0ustar00runnerdockerurllib3>=1.25 [dev] ruff==0.8.3 mypy==1.13.0 [fastimport] fastimport [https] urllib3>=1.24.1 [paramiko] paramiko [pgp] gpg ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624628.0 dulwich-0.22.7/dulwich.egg-info/top_level.txt0000644000175100002000000000001014731042564020511 0ustar00runnerdockerdulwich ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9724476 dulwich-0.22.7/examples/0000755000175100002000000000000014731042565014456 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/examples/clone.py0000644000175100002000000000144014731042555016126 0ustar00runnerdocker# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later """Clone. This trivial script demonstrates how to clone or lock a remote repository. Example usage: 1. python examples/clone.py git://github.com/jelmer/dulwich 2. python examples/clone.py git://github.com/jelmer/dulwich.git 3. python examples/clone.py git://github.com/jelmer/dulwich.git dulwich """ import sys from getopt import getopt from os.path import basename from dulwich import porcelain _, args = getopt(sys.argv, "", []) if len(args) < 2: print(f"usage: {args[0]} host:path path") sys.exit(1) elif len(args) < 3: target_path = basename(args[1].split(":")[-1]) if target_path[-4:] == ".git": target_path = target_path[:-4] else: target_path = args[2] porcelain.clone(args[1], target_path) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/examples/config.py0000644000175100002000000000051414731042555016274 0ustar00runnerdocker#!/usr/bin/python # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Read the config file for a git repository. # # Example usage: # python examples/config.py from dulwich.repo import Repo repo = Repo(".") config = repo.get_config() print(config.get("core", "filemode")) print(config.get(("remote", "origin"), "url")) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/examples/diff.py0000644000175100002000000000113414731042555015736 0ustar00runnerdocker#!/usr/bin/python # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # This trivial script demonstrates how to extract the unified diff for a single # commit in a local repository. # # Example usage: # python examples/diff.py import sys from dulwich.patch import write_tree_diff from dulwich.repo import Repo repo_path = "." commit_id = b"a6602654997420bcfd0bee2a0563d9416afe34b4" r = Repo(repo_path) commit = r[commit_id] parent_commit = r[commit.parents[0]] outstream = getattr(sys.stdout, "buffer", sys.stdout) write_tree_diff(outstream, r.object_store, parent_commit.tree, commit.tree) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/examples/gcs.py0000644000175100002000000000060714731042555015606 0ustar00runnerdocker#!/usr/bin/python3 # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later import tempfile from google.cloud import storage from dulwich.cloud.gcs import GcsObjectStore from dulwich.repo import Repo client = storage.Client() bucket = client.get_bucket("mybucket") gcs_object_store = GcsObjectStore(bucket, "path") r = Repo.init_bare(tempfile.mkdtemp(), object_store=gcs_object_store) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/examples/latest_change.py0000644000175100002000000000113714731042555017632 0ustar00runnerdocker#!/usr/bin/python # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Example printing the last author of a specified file import sys import time from dulwich.repo import Repo if len(sys.argv) < 2: print(f"usage: {sys.argv[0]} filename") sys.exit(1) r = Repo(".") path = sys.argv[1].encode("utf-8") w = r.get_walker(paths=[path], max_entries=1) try: c = next(iter(w)).commit except StopIteration: print(f"No file {sys.argv[1]} anywhere in history.") else: print( f"{sys.argv[1]} was last changed by {c.author} at {time.ctime(c.author_time)} (commit {c.id})" ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/examples/memoryrepo.py0000755000175100002000000000206114731042555017227 0ustar00runnerdocker#!/usr/bin/python # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # This script creates a clone of a remote repository in local memory, # then adds a single file and pushes the result back. # # Example usage: # python examples/memoryrepo.py git+ssh://github.com/jelmer/testrepo import stat import sys from dulwich import porcelain from dulwich.objects import Blob from dulwich.repo import MemoryRepo local_repo = MemoryRepo() local_repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master") fetch_result = porcelain.fetch(local_repo, sys.argv[1]) local_repo.refs[b"refs/heads/master"] = fetch_result.refs[b"refs/heads/master"] print(local_repo.refs.as_dict()) last_tree = local_repo[local_repo[b"HEAD"].tree] new_blob = Blob.from_string(b"Some contents") local_repo.object_store.add_object(new_blob) last_tree.add(b"test", stat.S_IFREG, new_blob.id) local_repo.object_store.add_object(last_tree) local_repo.do_commit( message=b"Add a file called 'test'", ref=b"refs/heads/master", tree=last_tree.id ) porcelain.push(local_repo, sys.argv[1], "master") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/examples/rename-branch.py0000644000175100002000000000146614731042555017540 0ustar00runnerdocker#!/usr/bin/python3 # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later import argparse from dulwich.client import get_transport_and_path_from_url from dulwich.objects import ZERO_SHA from dulwich.pack import pack_objects_to_data parser = argparse.ArgumentParser() parser.add_argument("url", type=str) parser.add_argument("old_ref", type=str) parser.add_argument("new_ref", type=str) args = parser.parse_args() client, path = get_transport_and_path_from_url(args.url) def generate_pack_data(*args, **kwargs): return pack_objects_to_data([]) def update_refs(refs): sha = refs[args.old_ref.encode("utf-8")] return {args.old_ref.encode("utf-8"): ZERO_SHA, args.new_ref.encode("utf-8"): sha} client.send_pack(path, update_refs, generate_pack_data) print(f"Renamed {args.old_ref} to {args.new_ref}") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/pyproject.toml0000644000175100002000000000560514731042555015561 0ustar00runnerdocker[build-system] requires = ["setuptools>=61.2"] build-backend = "setuptools.build_meta" [project] name = "dulwich" description = "Python Git Library" readme = "README.rst" authors = [{name = "Jelmer Vernooij", email = "jelmer@jelmer.uk"}] license = {text = "Apachev2 or later or GPLv2"} keywords = ["vcs", "git"] classifiers = [ "Development Status :: 4 - Beta", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Operating System :: POSIX", "Operating System :: Microsoft :: Windows", "Topic :: Software Development :: Version Control", ] requires-python = ">=3.9" dependencies = [ "urllib3>=1.25", ] dynamic = ["version"] [project.urls] Homepage = "https://www.dulwich.io/" Repository = "https://www.dulwich.io/code/" GitHub = "https://github.com/dulwich/dulwich" "Bug Tracker" = "https://github.com/dulwich/dulwich/issues" [project.optional-dependencies] fastimport = ["fastimport"] https = ["urllib3>=1.24.1"] pgp = ["gpg"] paramiko = ["paramiko"] dev = [ "ruff==0.8.3", "mypy==1.13.0" ] [project.scripts] dulwich = "dulwich.cli:main" [tool.mypy] ignore_missing_imports = true [tool.setuptools] packages = [ "dulwich", "dulwich.cloud", "dulwich.contrib", "dulwich.tests", ] include-package-data = true zip-safe = false script-files = [ "bin/dul-receive-pack", "bin/dul-upload-pack", ] license-files = ["COPYING"] [tool.setuptools.dynamic] version = {attr = "dulwich.__version__"} [tool.ruff.lint] select = [ "ANN", "D", "E", "F", "I", "PIE", "UP", "RSE", "RUF", ] ignore = [ "ANN001", "ANN002", "ANN003", "ANN201", "ANN202", "ANN204", "ANN205", "ANN206", "D100", "D101", "D102", "D103", "D104", "D105", "D107", "D204", "D205", "D417", "E501", # line too long ] [tool.ruff.lint.pydocstyle] convention = "google" [tool.cibuildwheel] environment = {PATH="$HOME/.cargo/bin:$PATH"} before-build = "pip install -U setuptools-rust && curl https://sh.rustup.rs -sSf | sh -s -- --profile=minimal -y && rustup show" [tool.cibuildwheel.linux] skip = "*-musllinux_*" archs = ["auto", "aarch64"] [tool.cibuildwheel.macos] archs = ["auto", "universal2", "x86_64", "arm64"] before-all = "rustup target add x86_64-apple-darwin aarch64-apple-darwin" skip = """\ cp39-macosx_x86_64 cp39-macosx_universal2 \ cp310-macosx_x86_64 cp310-macosx_universal2 \ cp311-macosx_x86_64 cp311-macosx_universal2 \ cp312-macosx_x86_64 cp312-macosx_universal2 \ cp313-macosx_x86_64 cp313-macosx_universal2 \ """ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9964476 dulwich-0.22.7/setup.cfg0000644000175100002000000000004614731042565014461 0ustar00runnerdocker[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/setup.py0000755000175100002000000000447314731042555014364 0ustar00runnerdocker#!/usr/bin/python3 # Setup file for dulwich # Copyright (C) 2008-2022 Jelmer Vernooij # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later import os import sys from setuptools import setup if sys.platform == "darwin" and os.path.exists("/usr/bin/xcodebuild"): # XCode 4.0 dropped support for ppc architecture, which is hardcoded in # distutils.sysconfig import subprocess p = subprocess.Popen( ["/usr/bin/xcodebuild", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={}, ) out, err = p.communicate() for line in out.splitlines(): line = line.decode("utf8") # Also parse only first digit, because 3.2.1 can't be parsed nicely if line.startswith("Xcode") and int(line.split()[1].split(".")[0]) >= 4: os.environ["ARCHFLAGS"] = "" tests_require = ["fastimport"] if "__pypy__" not in sys.modules and sys.platform != "win32": tests_require.extend(["gevent", "geventhttpclient", "setuptools>=17.1"]) optional = os.environ.get("CIBUILDWHEEL", "0") != "1" # Ideally, setuptools would just provide a way to do this if "PURE" in os.environ or "--pure" in sys.argv: if "--pure" in sys.argv: sys.argv.remove("--pure") setup_requires = [] rust_extensions = [] else: setup_requires = ["setuptools_rust"] # We check for egg_info since that indicates we are running prepare_metadata_for_build_* if "egg_info" in sys.argv: rust_extensions = [] else: from setuptools_rust import Binding, RustExtension rust_extensions = [ RustExtension( "dulwich._objects", "crates/objects/Cargo.toml", binding=Binding.PyO3, optional=optional, ), RustExtension( "dulwich._pack", "crates/pack/Cargo.toml", binding=Binding.PyO3, optional=optional, ), RustExtension( "dulwich._diff_tree", "crates/diff-tree/Cargo.toml", binding=Binding.PyO3, optional=optional, ), ] setup( package_data={"": ["py.typed"]}, rust_extensions=rust_extensions, setup_requires=setup_requires, tests_require=tests_require, ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9564476 dulwich-0.22.7/testdata/0000755000175100002000000000000014731042565014451 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9484477 dulwich-0.22.7/testdata/blobs/0000755000175100002000000000000014731042565015552 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9724476 dulwich-0.22.7/testdata/blobs/11/0000755000175100002000000000000014731042565015773 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/blobs/11/111111111111111111111111111111111111110000644000175100002000000000007614731042555021505 0ustar00runnerdockerxKOR0`,V(HT/VHIKMUHO-V/QM,IP,)V(JM)././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9724476 dulwich-0.22.7/testdata/blobs/6f/0000755000175100002000000000000014731042565016065 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/blobs/6f/670c0fb53f9463760b7295fbb814e965fb20c80000644000175100002000000000002014731042555023065 0ustar00runnerdocker7x+I-.Q0 l././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9724476 dulwich-0.22.7/testdata/blobs/95/0000755000175100002000000000000014731042565016007 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/blobs/95/4a536f7819d40e6f637f849ee187dd100663490000644000175100002000000000002614731042555022673 0ustar00runnerdockerxKOR0g(I-.Q0!././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9724476 dulwich-0.22.7/testdata/blobs/e6/0000755000175100002000000000000014731042565016064 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/blobs/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c53910000644000175100002000000000001714731042555023310 0ustar00runnerdockerxKOR0` ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9484477 dulwich-0.22.7/testdata/commits/0000755000175100002000000000000014731042565016124 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9724476 dulwich-0.22.7/testdata/commits/0d/0000755000175100002000000000000014731042565016427 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/commits/0d/89f20333fbb1d2f3a94da77f4981373d8f43100000755000175100002000000000020414731042555023427 0ustar00runnerdockerxK @])z53׮==-&e=i:"Z=H)r芔>4wYԯMx|q=s)&6Dh6{Ym/LXg?././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9764476 dulwich-0.22.7/testdata/commits/5d/0000755000175100002000000000000014731042565016434 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/commits/5d/ac377bdded4c9aeb8dff595f0faeebcc8498cc0000644000175100002000000000030214731042555024545 0ustar00runnerdockerxJ1D]+hMy ׮+:#= ,((EAeYNÇZf浂`"Ǧ}5Vb}f91Ȍ4\2klh{iYn (!i36ҴH3&ll7'ZϿvj#TJ,v9? jۻizdZ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9764476 dulwich-0.22.7/testdata/commits/60/0000755000175100002000000000000014731042565016351 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/commits/60/dacdc733de308bb77bb76ce0fb0f9b44c9769e0000644000175100002000000000024314731042555024074 0ustar00runnerdockerx 0E]+f/N"] g *5"O.υɗia UBERr[P\ʋ Tz靖-zN0Q )ZOEv,pIop['lǺ <|fֶk)PGX{&K0 ?yMQ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9764476 dulwich-0.22.7/testdata/indexes/0000755000175100002000000000000014731042565016110 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/indexes/index0000644000175100002000000000015014731042555017135 0ustar00runnerdockerDIRCIZIZ9c|⛲CK)wZSbla->=Đδ|wo././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9764476 dulwich-0.22.7/testdata/packs/0000755000175100002000000000000014731042565015552 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/packs/pack-bc63ddad95e7321ee734ea11a7a62d314e0d7481.idx0000644000175100002000000000216014731042555024676 0ustar00runnerdockerog ?cv re vj(y vx" Sph%Hrf_gADE*o2.;ڥ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/packs/pack-bc63ddad95e7321ee734ea11a7a62d314e0d7481.pack0000644000175100002000000000032614731042555025032 0ustar00runnerdockerPACK xA 0F}N1$C$ ҵk` i)ުGp|TXYbTN{YK!I%E :}c^+ݰZyiܚ;ʠS7~͇ vis{Q{ϵfpOrox_l`fU[ `T#Rի9S)H9PKByB'(~43؋.}݊7_z7j;X ٭`i6I`I././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9764476 dulwich-0.22.7/testdata/repos/a.git/objects/b0/0000755000175100002000000000000014731042565020535 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/a.git/objects/b0/931cadc54336e78a1d980420e3268903b57a500000644000175100002000000000022114731042555025357 0ustar00runnerdockerx-[ 0**I75T[oRWo w*`e/i7sjpیhjkL[c7L ><2ݏ 1Jr tqصh̰ɾ֥2v././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9764476 dulwich-0.22.7/testdata/repos/a.git/objects/ff/0000755000175100002000000000000014731042565020627 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/a.git/objects/ff/d47d45845a8f6576491e1edb97e3fe6a850e7f0000644000175100002000000000014014731042555026017 0ustar00runnerdockerx+)JMU0g040031QHd̽Q9 5 T2_/USjo5uk.` LfX4DSU3%?gf?[%././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/a.git/packed-refs0000644000175100002000000000020414731042555020705 0ustar00runnerdocker# pack-refs with: peeled b0931cadc54336e78a1d980420e3268903b57a50 refs/tags/mytag-packed ^2a72d929692c41d8554c07f6301757ba18a65d91 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9484477 dulwich-0.22.7/testdata/repos/a.git/refs/0000755000175100002000000000000014731042565017542 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9764476 dulwich-0.22.7/testdata/repos/a.git/refs/heads/0000755000175100002000000000000014731042565020626 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/a.git/refs/heads/master0000644000175100002000000000005114731042555022037 0ustar00runnerdockera90fa2d900a17e99b433217e988c4eb4a2e9a097 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9764476 dulwich-0.22.7/testdata/repos/a.git/refs/tags/0000755000175100002000000000000014731042565020500 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/a.git/refs/tags/mytag0000644000175100002000000000005114731042555021537 0ustar00runnerdocker28237f4dc30d0d462658d6b937b08a0f0b6ef55a ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9764476 dulwich-0.22.7/testdata/repos/empty.git/0000755000175100002000000000000014731042565017521 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/empty.git/HEAD0000644000175100002000000000002714731042555020143 0ustar00runnerdockerref: refs/heads/master ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/empty.git/config0000644000175100002000000000020314731042555020703 0ustar00runnerdocker[core] repositoryformatversion = 0 filemode = false bare = true symlinks = false ignorecase = true hideDotFiles = dotGitOnly ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9524477 dulwich-0.22.7/testdata/repos/empty.git/objects/0000755000175100002000000000000014731042565021152 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9764476 dulwich-0.22.7/testdata/repos/empty.git/objects/info/0000755000175100002000000000000014731042565022105 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/empty.git/objects/info/.gitignore0000644000175100002000000000001514731042555024070 0ustar00runnerdocker* !.gitignore././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/empty.git/objects/pack/0000755000175100002000000000000014731042565022070 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/empty.git/objects/pack/.gitignore0000644000175100002000000000001514731042555024053 0ustar00runnerdocker* !.gitignore././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9524477 dulwich-0.22.7/testdata/repos/empty.git/refs/0000755000175100002000000000000014731042565020460 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/empty.git/refs/heads/0000755000175100002000000000000014731042565021544 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/empty.git/refs/heads/.gitignore0000644000175100002000000000001514731042555023527 0ustar00runnerdocker* !.gitignore././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/empty.git/refs/tags/0000755000175100002000000000000014731042565021416 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/empty.git/refs/tags/.gitignore0000644000175100002000000000001514731042555023401 0ustar00runnerdocker* !.gitignore././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/issue88_expect_ack_nak_client.export0000644000175100002000000001123714731042555024734 0ustar00runnerdockerreset refs/heads/master commit refs/heads/master mark :1 author User 1427183369 +1300 committer User 1427183369 +1300 data 6 empty blob mark :2 data 35 We will reproduce a problem here. commit refs/heads/master mark :3 author User 1427183376 +1300 committer User 1427183376 +1300 data 11 demo file. from :1 M 100644 :2 demo.txt blob mark :4 data 62 We will reproduce a problem here. This will take some time. commit refs/heads/master mark :5 author User 1427185135 +1300 committer User 1427185135 +1300 data 13 added a line from :3 M 100644 :4 demo.txt blob mark :6 data 57 We will reproduce a problem here. We will change these. commit refs/heads/master mark :7 author User 1427185245 +1300 committer User 1427185245 +1300 data 14 replace a line from :5 M 100644 :6 demo.txt blob mark :8 data 52 We will change these. Then issues will be proven. commit refs/heads/master mark :9 author User 1427185343 +1300 committer User 1427185343 +1300 data 13 Yes we will. from :7 M 100644 :8 demo.txt blob mark :10 data 69 We will change these. Then issues will be proven once and for all. commit refs/heads/master mark :11 author User 1427185440 +1300 committer User 1427185440 +1300 data 6 sure. from :9 M 100644 :10 demo.txt blob mark :12 data 0 commit refs/heads/master mark :13 author User 1427185512 +1300 committer User 1427185516 +1300 data 26 not an actual readme, yet from :11 M 100644 :12 readme.txt blob mark :14 data 61 This will for sure we will prove a problem exist somewhere. blob mark :15 data 49 okay fine add something here this is only a test commit refs/heads/master mark :16 author User 1427185569 +1300 committer User 1427185569 +1300 data 12 more things from :13 M 100644 :14 demo.txt M 100644 :15 readme.txt blob mark :17 data 100 This will for sure we will prove a problem exist somewhere. Just that we need a few more commits. commit refs/heads/master mark :18 author User 1427185659 +1300 committer User 1427185659 +1300 data 13 one more try from :16 M 100644 :17 demo.txt blob mark :19 data 54 It might have something to do with number of commits? commit refs/heads/master mark :20 author User 1427185905 +1300 committer User 1427185905 +1300 data 18 is this number 9? from :18 M 100644 :19 commitcount blob mark :21 data 123 This will for sure we will prove a problem exist somewhere. Just that we need a few more commits. Hey look we need more commit refs/heads/master mark :22 author User 1427185922 +1300 committer User 1427185922 +1300 data 5 cool from :20 M 100644 :21 demo.txt blob mark :23 data 50 Okay fine add something here this is only a test. commit refs/heads/master mark :24 author User 1427185936 +1300 committer User 1427185936 +1300 data 7 readme from :22 M 100644 :23 readme.txt blob mark :25 data 74 Okay come on this is getting boring. Yes I went and edit all the things. commit refs/heads/master mark :26 author User 1427185954 +1300 committer User 1427185954 +1300 data 14 remove a line from :24 M 100644 :25 demo.txt blob mark :27 data 186 Okay come on this is getting boring. Yes I went and edit all the things. Of course, making test data can be somewhat tedious, especially a minimum set that can be easily reproduced. commit refs/heads/master mark :28 author User 1427185996 +1300 committer User 1427185996 +1300 data 25 Getting serious mode on. from :26 M 100644 :27 demo.txt blob mark :29 data 48 This is taking a bit longer than I remembered. commit refs/heads/master mark :30 author User 1427186065 +1300 committer User 1427186065 +1300 data 40 At least we will have things minimized. from :28 M 100644 :29 demo.txt blob mark :31 data 11 there yet? commit refs/heads/master mark :32 author User 1427186080 +1300 committer User 1427186080 +1300 data 7 are we from :30 M 100644 :31 demo.txt blob mark :33 data 237 This should be the head commit for the client repo for testing out the failure case reported in issue 88. Just do a git pull from the repo that includes the following commit that is hosted with dulwich. The issue should be reproduced. commit refs/heads/master mark :34 author User 1427186109 +1300 committer User 1427186109 +1300 data 6 okay? from :32 M 100644 :33 readme.txt ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/issue88_expect_ack_nak_other.export0000644000175100002000000001256014731042555024577 0ustar00runnerdockerblob mark :1 data 33 We will sneak in a blob like so. reset refs/heads/master commit refs/heads/master mark :2 author User 1427183369 +1300 committer User 1427183369 +1300 data 7 sneaky M 100644 :1 problem.questionmark blob mark :3 data 35 We will introduce a problem here. commit refs/heads/master mark :4 author User 1427183376 +1300 committer User 1427183376 +1300 data 11 demo file. from :2 M 100644 :3 demo.rst blob mark :5 data 62 We will introduce a problem here. This will take some time. commit refs/heads/master mark :6 author User 1427185135 +1300 committer User 1427185135 +1300 data 13 added a line from :4 M 100644 :5 demo.rst blob mark :7 data 57 We will introduce a problem here. We will change these. commit refs/heads/master mark :8 author User 1427185245 +1300 committer User 1427185245 +1300 data 14 replace a linefrom :6 M 100644 :7 demo.rst blob mark :9 data 52 We will change these. Then issues will be proven. commit refs/heads/master mark :10 author User 1427185343 +1300 committer User 1427185343 +1300 data 13 Yes we will. from :8 M 100644 :9 demo.rst blob mark :11 data 72 We will change these. Then issues will be construed once and for all. commit refs/heads/master mark :12 author User 1427185440 +1300 committer User 1427185440 +1300 data 6 sure. from :10 M 100644 :11 demo.rst blob mark :13 data 0 commit refs/heads/master mark :14 author User 1427185512 +1300 committer User 1427185516 +1300 data 26 not an actual readme, yet from :12 M 100644 :13 emdaer.txt blob mark :15 data 58 This will for sure we will prove issues exist somewhere. blob mark :16 data 49 okay fine add something here this is only a test commit refs/heads/master mark :17 author User 1427185569 +1300 committer User 1427185569 +1300 data 12 more things from :14 M 100644 :15 demo.rst M 100644 :16 emdaer.txt blob mark :18 data 97 This will for sure prove issue exist somewhere. Just that we need a few more commits as usual. commit refs/heads/master mark :19 author User 1427185659 +1300 committer User 1427185659 +1300 data 13 one more try from :17 M 100644 :18 demo.rst blob mark :20 data 54 It might have something to do with number of commits? commit refs/heads/master mark :21 author User 1427185905 +1300 committer User 1427185905 +1300 data 18 is this number 9? from :19 M 100644 :20 count blob mark :22 data 119 This will for sure we will prove issues exist somewhere. Just that we need a few more commits. Hey look we need more commit refs/heads/master mark :23 author User 1427185922 +1300 committer User 1427185922 +1300 data 5 cool from :21 M 100644 :22 demo.rst blob mark :24 data 50 Okay fine add something here this is only a test. commit refs/heads/master mark :25 author User 1427185936 +1300 committer User 1427185936 +1300 data 7 readme from :23 M 100644 :24 emdaer.txt blob mark :26 data 74 Okay come on this is getting boring. Yes I went and edit all the things. commit refs/heads/master mark :27 author User 1427185954 +1300 committer User 1427185954 +1300 data 14 remove a line from :25 M 100644 :26 demo.rst blob mark :28 data 186 Okay come on this is getting boring. Yes I went and edit all the things. Of course, making test data can be somewhat tedious, especially a minimum set that can be easily reproduced. commit refs/heads/master mark :29 author User 1427185996 +1300 committer User 1427185996 +1300 data 25 Getting serious mode on. from :27 M 100644 :28 demo.rst blob mark :30 data 48 This is taking a bit longer than I remembered. commit refs/heads/master mark :31 author User 1427186065 +1300 committer User 1427186065 +1300 data 40 At least we will have things minimized. from :29 M 100644 :30 demo.rst blob mark :32 data 11 there yet? commit refs/heads/master mark :33 author User 1427186080 +1300 committer User 1427186080 +1300 data 7 are we from :31 M 100644 :32 demo.rst blob mark :34 data 237 This should be the head commit for the client repo for testing out the failure case reported in issue 88. Just do a git pull from the repo that includes the following commit that is hosted with dulwich. The issue should be reproduced. commit refs/heads/master mark :35 author User 1427186109 +1300 committer User 1427186109 +1300 data 6 okay? from :33 M 100644 :34 emdaer.txt blob mark :36 data 394 This should be the commit that will trigger the bug noted in issue 88 (https://github.com/jelmer/dulwich/issues/88). To reproduce, run git fast-import using this fast-export and host this using dulwich, and then make a copy of this, strip out this blob and the following commit block, import to another git repo and then git clone from the previous. Naturally, this is part of the test case. commit refs/heads/master mark :37 author User 1427244891 +1300 committer User 1427248186 +1300 data 49 Added instructions on how to use this to readme. from :35 M 100644 :36 emdaer.txt ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/issue88_expect_ack_nak_server.export0000644000175100002000000001243614731042555024766 0ustar00runnerdockerreset refs/heads/master commit refs/heads/master mark :1 author User 1427183369 +1300 committer User 1427183369 +1300 data 6 empty blob mark :2 data 35 We will reproduce a problem here. commit refs/heads/master mark :3 author User 1427183376 +1300 committer User 1427183376 +1300 data 11 demo file. from :1 M 100644 :2 demo.txt blob mark :4 data 62 We will reproduce a problem here. This will take some time. commit refs/heads/master mark :5 author User 1427185135 +1300 committer User 1427185135 +1300 data 13 added a line from :3 M 100644 :4 demo.txt blob mark :6 data 57 We will reproduce a problem here. We will change these. commit refs/heads/master mark :7 author User 1427185245 +1300 committer User 1427185245 +1300 data 14 replace a line from :5 M 100644 :6 demo.txt blob mark :8 data 52 We will change these. Then issues will be proven. commit refs/heads/master mark :9 author User 1427185343 +1300 committer User 1427185343 +1300 data 13 Yes we will. from :7 M 100644 :8 demo.txt blob mark :10 data 69 We will change these. Then issues will be proven once and for all. commit refs/heads/master mark :11 author User 1427185440 +1300 committer User 1427185440 +1300 data 6 sure. from :9 M 100644 :10 demo.txt blob mark :12 data 0 commit refs/heads/master mark :13 author User 1427185512 +1300 committer User 1427185516 +1300 data 26 not an actual readme, yet from :11 M 100644 :12 readme.txt blob mark :14 data 61 This will for sure we will prove a problem exist somewhere. blob mark :15 data 49 okay fine add something here this is only a test commit refs/heads/master mark :16 author User 1427185569 +1300 committer User 1427185569 +1300 data 12 more things from :13 M 100644 :14 demo.txt M 100644 :15 readme.txt blob mark :17 data 100 This will for sure we will prove a problem exist somewhere. Just that we need a few more commits. commit refs/heads/master mark :18 author User 1427185659 +1300 committer User 1427185659 +1300 data 13 one more try from :16 M 100644 :17 demo.txt blob mark :19 data 54 It might have something to do with number of commits? commit refs/heads/master mark :20 author User 1427185905 +1300 committer User 1427185905 +1300 data 18 is this number 9? from :18 M 100644 :19 commitcount blob mark :21 data 123 This will for sure we will prove a problem exist somewhere. Just that we need a few more commits. Hey look we need more commit refs/heads/master mark :22 author User 1427185922 +1300 committer User 1427185922 +1300 data 5 cool from :20 M 100644 :21 demo.txt blob mark :23 data 50 Okay fine add something here this is only a test. commit refs/heads/master mark :24 author User 1427185936 +1300 committer User 1427185936 +1300 data 7 readme from :22 M 100644 :23 readme.txt blob mark :25 data 74 Okay come on this is getting boring. Yes I went and edit all the things. commit refs/heads/master mark :26 author User 1427185954 +1300 committer User 1427185954 +1300 data 14 remove a line from :24 M 100644 :25 demo.txt blob mark :27 data 186 Okay come on this is getting boring. Yes I went and edit all the things. Of course, making test data can be somewhat tedious, especially a minimum set that can be easily reproduced. commit refs/heads/master mark :28 author User 1427185996 +1300 committer User 1427185996 +1300 data 25 Getting serious mode on. from :26 M 100644 :27 demo.txt blob mark :29 data 48 This is taking a bit longer than I remembered. commit refs/heads/master mark :30 author User 1427186065 +1300 committer User 1427186065 +1300 data 40 At least we will have things minimized. from :28 M 100644 :29 demo.txt blob mark :31 data 11 there yet? commit refs/heads/master mark :32 author User 1427186080 +1300 committer User 1427186080 +1300 data 7 are we from :30 M 100644 :31 demo.txt blob mark :33 data 237 This should be the head commit for the client repo for testing out the failure case reported in issue 88. Just do a git pull from the repo that includes the following commit that is hosted with dulwich. The issue should be reproduced. commit refs/heads/master mark :34 author User 1427186109 +1300 committer User 1427186109 +1300 data 6 okay? from :32 M 100644 :33 readme.txt blob mark :35 data 394 This should be the commit that will trigger the bug noted in issue 88 (https://github.com/jelmer/dulwich/issues/88). To reproduce, run git fast-import using this fast-export and host this using dulwich, and then make a copy of this, strip out this blob and the following commit block, import to another git repo and then git clone from the previous. Naturally, this is part of the test case. commit refs/heads/master mark :36 author User 1427244891 +1300 committer User 1427248186 +1300 data 49 Added instructions on how to use this to readme. from :34 M 100644 :35 readme.txt ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/ooo_merge.git/0000755000175100002000000000000014731042565020336 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/ooo_merge.git/HEAD0000644000175100002000000000002714731042555020760 0ustar00runnerdockerref: refs/heads/master ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9524477 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/0000755000175100002000000000000014731042565021767 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/29/0000755000175100002000000000000014731042565022221 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/29/69be3e8ee1c0222396a5611407e4769f14e54b0000644000175100002000000000002614731042555027137 0ustar00runnerdockerxKOR0g(I-.Q0!././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/38/0000755000175100002000000000000014731042565022221 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/38/74e9c60a6d149c44c928140f250d81e63815200000644000175100002000000000010614731042555026770 0ustar00runnerdockerx+)JMU0`040031QHdOj?%h"/S+J&3L ί—\2a]dOn././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/6f/0000755000175100002000000000000014731042565022302 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/6f/670c0fb53f9463760b7295fbb814e965fb20c80000644000175100002000000000002614731042555027310 0ustar00runnerdockerxKOR0g(I-.Q0!././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/70/0000755000175100002000000000000014731042565022215 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/70/c190eb48fa8bbb50ddc692a17b44cb781af7f60000644000175100002000000000010714731042555027644 0ustar00runnerdockerx+)JMU0`040031QHdOj?%h"/S+J&1hf{x@IyD'eEzױ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/76/0000755000175100002000000000000014731042565022223 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/76/01d7f6231db6a57f7bbb79ee52e4d462fd44d10000644000175100002000000000030314731042555027513 0ustar00runnerdockerxAj1 E)L%[PJօ46Cf txӲzL `MH* [dL:^ l8++Pb+46nhb&ei?:檵SH@mD r_-ᗮxMY_~{a U*Z{2 CW%>rT&I@$P5iX莥7y w:^o_|Q[IZS sVIEy?././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/fb/0000755000175100002000000000000014731042565022356 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/ooo_merge.git/objects/fb/5b0425c7ce46959bec94d54b9a157645e114f50000644000175100002000000000024514731042555027367 0ustar00runnerdockerxA 0={d76 t mFߋsf<y3X()*IU;g/hL$5dA'J^X%tsMhl=UN]qhyvݛ`{}ӋL?x3YQ1`5+f8ᷫL N_././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9524477 dulwich-0.22.7/testdata/repos/ooo_merge.git/refs/0000755000175100002000000000000014731042565021275 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/ooo_merge.git/refs/heads/0000755000175100002000000000000014731042565022361 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/ooo_merge.git/refs/heads/master0000644000175100002000000000005114731042555023572 0ustar00runnerdocker7601d7f6231db6a57f7bbb79ee52e4d462fd44d1 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/refs.git/0000755000175100002000000000000014731042565017322 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/HEAD0000644000175100002000000000002714731042555017744 0ustar00runnerdockerref: refs/heads/master ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9524477 dulwich-0.22.7/testdata/repos/refs.git/objects/0000755000175100002000000000000014731042565020753 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/refs.git/objects/3b/0000755000175100002000000000000014731042565021257 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/objects/3b/9e5457140e738c2dcd39bf6d7acf88379b90d10000644000175100002000000000006014731042555026435 0ustar00runnerdockerx+)JMU06d040031QHgX(rX\$xsޙ"U ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/refs.git/objects/3e/0000755000175100002000000000000014731042565021262 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/objects/3e/c9c43c84ff242e3ef4a9fc5bc111fd780a76a80000644000175100002000000000022614731042555026643 0ustar00runnerdockerx-Q 0D)-mV^i66.~{#Cm]rw yu=u5^[o<H<*y?ƴ,()a߈2<)$8xR.4YktPaԵ q?W)'ǧ6././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/refs.git/objects/42/0000755000175100002000000000000014731042565021200 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/objects/42/d06bd4b77fed026b154d16493e5deab78f02ec0000644000175100002000000000020114731042555026541 0ustar00runnerdockerx 1NۀI{V00Lntfp9|0X*b3T* 1GMFK[z1\{8RyY|(N`[kVݮՅf];'././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/refs.git/objects/a1/0000755000175100002000000000000014731042565021254 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/objects/a1/8114c31713746a33a2e70d9914d1ef3e7814250000644000175100002000000000003514731042555026020 0ustar00runnerdockerxKOR04fHWH+I+)J././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/refs.git/objects/cd/0000755000175100002000000000000014731042565021341 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/objects/cd/a609072918d7b70057b6bef9f4c2537843fcfe0000644000175100002000000000023314731042555026432 0ustar00runnerdockerx-Q 0D)m7iV^i6bIEOo ~c`Av.; Zyku<*^Zox\T4 < 4 .Lam Fj#e /s=SRYBcQk eZ-\r?)Y9././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/refs.git/objects/df/0000755000175100002000000000000014731042565021344 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/objects/df/6800012397fb85c56e7418dd4eb9405dee075c0000644000175100002000000000020614731042555026345 0ustar00runnerdockerx-[ 0)-gS^ MX"qQVocC]WJ Fet18M2*5Y:3kB|AEINں.,x{t*GJIpj>?kkF@*U# q U|y,././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/packed-refs0000644000175100002000000000027314731042555021432 0ustar00runnerdocker# pack-refs with: peeled df6800012397fb85c56e7418dd4eb9405dee075c refs/tags/refs-0.1 ^42d06bd4b77fed026b154d16493e5deab78f02ec 42d06bd4b77fed026b154d16493e5deab78f02ec refs/heads/packed ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9524477 dulwich-0.22.7/testdata/repos/refs.git/refs/0000755000175100002000000000000014731042565020261 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9804475 dulwich-0.22.7/testdata/repos/refs.git/refs/heads/0000755000175100002000000000000014731042565021345 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/refs/heads/40-char-ref-aaaaaaaaaaaaaaaaaa0000644000175100002000000000005114731042555026572 0ustar00runnerdocker42d06bd4b77fed026b154d16493e5deab78f02ec ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/refs/heads/loop0000644000175100002000000000002514731042555022235 0ustar00runnerdockerref: refs/heads/loop ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/refs/heads/master0000644000175100002000000000005114731042555022556 0ustar00runnerdocker42d06bd4b77fed026b154d16493e5deab78f02ec ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/refs.git/refs/tags/0000755000175100002000000000000014731042565021217 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/refs.git/refs/tags/refs-0.20000644000175100002000000000005114731042555022371 0ustar00runnerdocker3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/server_new.export0000644000175100002000000000321114731042555021217 0ustar00runnerdockerblob mark :1 data 13 foo contents reset refs/heads/master commit refs/heads/master mark :2 author Dave Borowitz 1265755064 -0800 committer Dave Borowitz 1265755064 -0800 data 16 initial checkin M 100644 :1 foo blob mark :3 data 13 baz contents blob mark :4 data 21 updated foo contents commit refs/heads/master mark :5 author Dave Borowitz 1265755140 -0800 committer Dave Borowitz 1265755140 -0800 data 15 master checkin from :2 M 100644 :3 baz M 100644 :4 foo blob mark :6 data 24 updated foo contents v2 commit refs/heads/master mark :7 author Dave Borowitz 1265755287 -0800 committer Dave Borowitz 1265755287 -0800 data 17 master checkin 2 from :5 M 100644 :6 foo blob mark :8 data 24 updated foo contents v3 commit refs/heads/master mark :9 author Dave Borowitz 1265755295 -0800 committer Dave Borowitz 1265755295 -0800 data 17 master checkin 3 from :7 M 100644 :8 foo blob mark :10 data 22 branched bar contents blob mark :11 data 22 branched foo contents commit refs/heads/branch mark :12 author Dave Borowitz 1265755111 -0800 committer Dave Borowitz 1265755111 -0800 data 15 branch checkin from :2 M 100644 :10 bar M 100644 :11 foo blob mark :13 data 25 branched bar contents v2 commit refs/heads/branch mark :14 author Dave Borowitz 1265755319 -0800 committer Dave Borowitz 1265755319 -0800 data 17 branch checkin 2 from :12 M 100644 :13 bar reset refs/heads/master from :9 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/server_old.export0000644000175100002000000000160514731042555021211 0ustar00runnerdockerblob mark :1 data 13 foo contents reset refs/heads/master commit refs/heads/master mark :2 author Dave Borowitz 1265755064 -0800 committer Dave Borowitz 1265755064 -0800 data 16 initial checkin M 100644 :1 foo blob mark :3 data 22 branched bar contents blob mark :4 data 22 branched foo contents commit refs/heads/branch mark :5 author Dave Borowitz 1265755111 -0800 committer Dave Borowitz 1265755111 -0800 data 15 branch checkin from :2 M 100644 :3 bar M 100644 :4 foo blob mark :6 data 13 baz contents blob mark :7 data 21 updated foo contents commit refs/heads/master mark :8 author Dave Borowitz 1265755140 -0800 committer Dave Borowitz 1265755140 -0800 data 15 master checkin from :2 M 100644 :6 baz M 100644 :7 foo reset refs/heads/master from :8 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/0000755000175100002000000000000014731042565021033 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/HEAD0000644000175100002000000000002714731042555021455 0ustar00runnerdockerref: refs/heads/master ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9564476 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/0000755000175100002000000000000014731042565022464 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/0d/0000755000175100002000000000000014731042565022767 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/0d/89f20333fbb1d2f3a94da77f4981373d8f43100000644000175100002000000000020414731042555027764 0ustar00runnerdockerxK @])z53׮==-&e=i:"Z=H)r芔>4wYԯMx|q=s)&6Dh6{Ym/LXg?././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/1b/0000755000175100002000000000000014731042565022766 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/1b/6318f651a534b38f9c7aedeebbd56c1e8968530000644000175100002000000000014014731042555030220 0ustar00runnerdockerx+)JMU0g040031QHdOj?%h"/S+J&1hf{x@IyD'eEzC%S}4{kݚʣnz<>%././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/29/0000755000175100002000000000000014731042565022716 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/29/69be3e8ee1c0222396a5611407e4769f14e54b0000644000175100002000000000002014731042555027626 0ustar00runnerdocker7x+I-.Q0 n././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/4c/0000755000175100002000000000000014731042565022772 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/4c/ffe90e0a41ad3f5190079d7c8f036bde29cbe60000644000175100002000000000024714731042555030353 0ustar00runnerdockerxK 1D]L~=pݝŒ2Fo-U:.UUA I!KU.!kj FN *R{QofwSQ[!)G;]g8Шw863Mˇ/_m1 tSK0]i*'pCO././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/5d/0000755000175100002000000000000014731042565022774 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/5d/ac377bdded4c9aeb8dff595f0faeebcc8498cc0000644000175100002000000000030214731042555031105 0ustar00runnerdockerxJ1D]+hMy ׮+:#= ,((EAeYNÇZf浂`"Ǧ}5Vb}f91Ȍ4\2klh{iYn (!i36ҴH3&ll7'ZϿvj#TJ,v9? jۻizdZ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/60/0000755000175100002000000000000014731042565022711 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/60/dacdc733de308bb77bb76ce0fb0f9b44c9769e0000644000175100002000000000024314731042555030434 0ustar00runnerdockerx 0E]+f/N"] g *5"O.υɗia UBERr[P\ʋ Tz靖-zN0Q )ZOEv,pIop['lǺ <|fֶk)PGX{&K0 ?yMQ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/6f/0000755000175100002000000000000014731042565022777 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/6f/670c0fb53f9463760b7295fbb814e965fb20c80000644000175100002000000000002014731042555027777 0ustar00runnerdocker7x+I-.Q0 l././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/70/0000755000175100002000000000000014731042565022712 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/70/c190eb48fa8bbb50ddc692a17b44cb781af7f60000644000175100002000000000010714731042555030341 0ustar00runnerdockerx+)JMU0`040031QHdOj?%h"/S+J&1hf{x@IyD'eEzױ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/90/0000755000175100002000000000000014731042565022714 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/90/182552c4a85a45ec2a835cadc3451bebdfe8700000644000175100002000000000013714731042555030176 0ustar00runnerdockerx+)JMU0g040031QHdOj?%h"/S+J&1hf{x@IyD'eEzC%zWH^Oo['<"3././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/95/0000755000175100002000000000000014731042565022721 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/95/4a536f7819d40e6f637f849ee187dd100663490000644000175100002000000000002614731042555027605 0ustar00runnerdockerxKOR0g(I-.Q0!././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/ab/0000755000175100002000000000000014731042565023046 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/ab/64bbdcc51b170d21588e5c5d391ee5c0c96dfd0000644000175100002000000000024714731042555030423 0ustar00runnerdockerxM 0]$cL";/:3b mo|6=~SgU@c̍bUA)ƙ{ulR+ld&z7ږm{IiKt.pmQx?|ݨ!־c仴?s9r4/mO+././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/d4/0000755000175100002000000000000014731042565022773 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/d4/bdad6549dfedf25d3b89d21f506aff575b28a70000644000175100002000000000014014731042555030436 0ustar00runnerdockerx+)JMU0g040031QHdOj?%h"/S+J&1hf{x@IyD'eEzC%S}4{kݚʣnz<>%././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/d8/0000755000175100002000000000000014731042565022777 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/d8/0c186a03f423a81b39df39dc87fd269736ca860000644000175100002000000000014614731042555030067 0ustar00runnerdockerx+)JMU044c040031QHdOj?%h"/S+J&1hf{x@IyD'eEzC%S}4{kݚʣnz<*UH3././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/e6/0000755000175100002000000000000014731042565022776 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c53910000644000175100002000000000001714731042555030222 0ustar00runnerdockerxKOR0` ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9564476 dulwich-0.22.7/testdata/repos/simple_merge.git/refs/0000755000175100002000000000000014731042565021772 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/simple_merge.git/refs/heads/0000755000175100002000000000000014731042565023056 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/simple_merge.git/refs/heads/master0000644000175100002000000000005114731042555024267 0ustar00runnerdocker5dac377bdded4c9aeb8dff595f0faeebcc8498cc ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/repos/submodule/0000755000175100002000000000000014731042565017600 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/repos/submodule/dotgit0000644000175100002000000000002014731042555021004 0ustar00runnerdockergitdir: ./a.git ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9564476 dulwich-0.22.7/testdata/tags/0000755000175100002000000000000014731042565015407 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9844475 dulwich-0.22.7/testdata/tags/71/0000755000175100002000000000000014731042565015636 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/testdata/tags/71/033db03a03c6a36721efcf1968dd8f8e0cf0230000644000175100002000000000044114731042555023033 0ustar00runnerdockerxmMO@=x#݅QnIMEQ mʿG'sL2OSz,$1vqnaJb+0u3mMr a dɢs,=RB bY(֝cQ Yjn!p 7# ݜ5!X[GپM} n}]8m9pzd% !#f|X`fBKD%'sKCӝ5\ # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for Dulwich.""" __all__ = [ "BlackboxTestCase", "SkipTest", "TestCase", "expectedFailure", "skipIf", ] import doctest import os import shutil import subprocess import sys import tempfile # If Python itself provides an exception, use that import unittest from typing import ClassVar from unittest import SkipTest, expectedFailure, skipIf from unittest import TestCase as _TestCase class TestCase(_TestCase): def setUp(self) -> None: super().setUp() self.overrideEnv("HOME", "/nonexistent") self.overrideEnv("GIT_CONFIG_NOSYSTEM", "1") def overrideEnv(self, name, value) -> None: def restore() -> None: if oldval is not None: os.environ[name] = oldval else: del os.environ[name] oldval = os.environ.get(name) if value is not None: os.environ[name] = value else: del os.environ[name] self.addCleanup(restore) class BlackboxTestCase(TestCase): """Blackbox testing.""" # TODO(jelmer): Include more possible binary paths. bin_directories: ClassVar[list[str]] = [ os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "bin")), "/usr/bin", "/usr/local/bin", ] def bin_path(self, name): """Determine the full path of a binary. Args: name: Name of the script Returns: Full path """ for d in self.bin_directories: p = os.path.join(d, name) if os.path.isfile(p): return p else: raise SkipTest(f"Unable to find binary {name}") def run_command(self, name, args): """Run a Dulwich command. Args: name: Name of the command, as it exists in bin/ args: Arguments to the command """ env = dict(os.environ) env["PYTHONPATH"] = os.pathsep.join(sys.path) # Since they don't have any extensions, Windows can't recognize # executablility of the Python files in /bin. Even then, we'd have to # expect the user to set up file associations for .py files. # # Save us from all that headache and call python with the bin script. argv = [sys.executable, self.bin_path(name), *args] return subprocess.Popen( argv, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, env=env, ) def self_test_suite(): names = [ "archive", "blackbox", "bundle", "client", "config", "credentials", "diff_tree", "fastexport", "file", "grafts", "graph", "greenthreads", "hooks", "ignore", "index", "lfs", "line_ending", "lru_cache", "mailmap", "objects", "objectspec", "object_store", "missing_obj_finder", "pack", "patch", "porcelain", "protocol", "reflog", "refs", "repository", "server", "stash", "utils", "walk", "web", ] module_names = ["tests.test_" + name for name in names] loader = unittest.TestLoader() return loader.loadTestsFromNames(module_names) def tutorial_test_suite(): tutorial = [ "introduction", "file-format", "repo", "object-store", "remote", "conclusion", ] tutorial_files = [f"../docs/tutorial/{name}.txt" for name in tutorial] to_restore = [] def overrideEnv(name, value) -> None: oldval = os.environ.get(name) if value is not None: os.environ[name] = value else: del os.environ[name] to_restore.append((name, oldval)) def setup(test) -> None: test.__old_cwd = os.getcwd() test.tempdir = tempfile.mkdtemp() test.globs.update({"tempdir": test.tempdir}) os.chdir(test.tempdir) overrideEnv("HOME", "/nonexistent") overrideEnv("GIT_CONFIG_NOSYSTEM", "1") def teardown(test) -> None: os.chdir(test.__old_cwd) shutil.rmtree(test.tempdir) for name, oldval in to_restore: if oldval is not None: os.environ[name] = oldval else: del os.environ[name] to_restore.clear() return doctest.DocFileSuite( module_relative=True, package="tests", setUp=setup, tearDown=teardown, *tutorial_files, ) def nocompat_test_suite(): result = unittest.TestSuite() result.addTests(self_test_suite()) result.addTests(tutorial_test_suite()) from dulwich.contrib import test_suite as contrib_test_suite result.addTests(contrib_test_suite()) return result def compat_test_suite(): result = unittest.TestSuite() from .compat import test_suite as compat_test_suite result.addTests(compat_test_suite()) return result def test_suite(): result = unittest.TestSuite() result.addTests(self_test_suite()) if sys.platform != "win32": result.addTests(tutorial_test_suite()) from .compat import test_suite as compat_test_suite result.addTests(compat_test_suite()) from .contrib import test_suite as contrib_test_suite result.addTests(contrib_test_suite()) return result ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9924474 dulwich-0.22.7/tests/compat/0000755000175100002000000000000014731042565015265 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/compat/__init__.py0000644000175100002000000000272414731042555017402 0ustar00runnerdocker# __init__.py -- Compatibility tests for dulwich # Copyright (C) 2010 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Compatibility tests for Dulwich.""" import unittest def test_suite(): names = [ "client", "pack", "patch", "porcelain", "repository", "server", "utils", "web", ] module_names = ["tests.compat.test_" + name for name in names] result = unittest.TestSuite() loader = unittest.TestLoader() suite = loader.loadTestsFromNames(module_names) result.addTests(suite) return result ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/compat/server_utils.py0000644000175100002000000003177114731042555020375 0ustar00runnerdocker# server_utils.py -- Git server compatibility utilities # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Utilities for testing git server compatibility.""" import errno import os import shutil import socket import tempfile from dulwich.objects import hex_to_sha from dulwich.protocol import CAPABILITY_SIDE_BAND_64K from dulwich.repo import Repo from dulwich.server import ReceivePackHandler from dulwich.tests.utils import tear_down_repo from .utils import require_git_version, run_git_or_fail class _StubRepo: """A stub repo that just contains a path to tear down.""" def __init__(self, name) -> None: temp_dir = tempfile.mkdtemp() self.path = os.path.join(temp_dir, name) os.mkdir(self.path) def close(self) -> None: pass def _get_shallow(repo): shallow_file = repo.get_named_file("shallow") if not shallow_file: return [] shallows = [] with shallow_file: for line in shallow_file: sha = line.strip() if not sha: continue hex_to_sha(sha) shallows.append(sha) return shallows class ServerTests: """Base tests for testing servers. Does not inherit from TestCase so tests are not automatically run. """ min_single_branch_version = ( 1, 7, 10, ) def import_repos(self) -> None: self._old_repo = self.import_repo("server_old.export") self._new_repo = self.import_repo("server_new.export") def url(self, port) -> str: return f"{self.protocol}://localhost:{port}/" def branch_args(self, branches=None): if branches is None: branches = ["master", "branch"] return [f"{b}:{b}" for b in branches] def test_push_to_dulwich(self) -> None: self.import_repos() self.assertReposNotEqual(self._old_repo, self._new_repo) port = self._start_server(self._old_repo) run_git_or_fail( ["push", self.url(port), *self.branch_args()], cwd=self._new_repo.path, ) self.assertReposEqual(self._old_repo, self._new_repo) def test_push_to_dulwich_no_op(self) -> None: self._old_repo = self.import_repo("server_old.export") self._new_repo = self.import_repo("server_old.export") self.assertReposEqual(self._old_repo, self._new_repo) port = self._start_server(self._old_repo) run_git_or_fail( ["push", self.url(port), *self.branch_args()], cwd=self._new_repo.path, ) self.assertReposEqual(self._old_repo, self._new_repo) def test_push_to_dulwich_remove_branch(self) -> None: self._old_repo = self.import_repo("server_old.export") self._new_repo = self.import_repo("server_old.export") self.assertReposEqual(self._old_repo, self._new_repo) port = self._start_server(self._old_repo) run_git_or_fail(["push", self.url(port), ":master"], cwd=self._new_repo.path) self.assertEqual(list(self._old_repo.get_refs().keys()), [b"refs/heads/branch"]) def test_fetch_from_dulwich(self) -> None: self.import_repos() self.assertReposNotEqual(self._old_repo, self._new_repo) port = self._start_server(self._new_repo) run_git_or_fail( ["fetch", self.url(port), *self.branch_args()], cwd=self._old_repo.path, ) # flush the pack cache so any new packs are picked up self._old_repo.object_store._pack_cache_time = 0 self.assertReposEqual(self._old_repo, self._new_repo) def test_fetch_from_dulwich_no_op(self) -> None: self._old_repo = self.import_repo("server_old.export") self._new_repo = self.import_repo("server_old.export") self.assertReposEqual(self._old_repo, self._new_repo) port = self._start_server(self._new_repo) run_git_or_fail( ["fetch", self.url(port), *self.branch_args()], cwd=self._old_repo.path, ) # flush the pack cache so any new packs are picked up self._old_repo.object_store._pack_cache_time = 0 self.assertReposEqual(self._old_repo, self._new_repo) def test_clone_from_dulwich_empty(self) -> None: old_repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, old_repo_dir) self._old_repo = Repo.init_bare(old_repo_dir) port = self._start_server(self._old_repo) new_repo_base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, new_repo_base_dir) new_repo_dir = os.path.join(new_repo_base_dir, "empty_new") run_git_or_fail(["clone", self.url(port), new_repo_dir], cwd=new_repo_base_dir) new_repo = Repo(new_repo_dir) self.assertReposEqual(self._old_repo, new_repo) def test_lsremote_from_dulwich(self) -> None: self._repo = self.import_repo("server_old.export") port = self._start_server(self._repo) o = run_git_or_fail(["ls-remote", self.url(port)]) self.assertEqual(len(o.split(b"\n")), 4) def test_new_shallow_clone_from_dulwich(self) -> None: require_git_version(self.min_single_branch_version) self._source_repo = self.import_repo("server_new.export") self._stub_repo = _StubRepo("shallow") self.addCleanup(tear_down_repo, self._stub_repo) port = self._start_server(self._source_repo) # Fetch at depth 1 run_git_or_fail( [ "clone", "--mirror", "--depth=1", "--no-single-branch", self.url(port), self._stub_repo.path, ] ) clone = self._stub_repo = Repo(self._stub_repo.path) expected_shallow = [ b"35e0b59e187dd72a0af294aedffc213eaa4d03ff", b"514dc6d3fbfe77361bcaef320c4d21b72bc10be9", ] self.assertEqual(expected_shallow, _get_shallow(clone)) self.assertReposNotEqual(clone, self._source_repo) def test_shallow_clone_from_git_is_identical(self) -> None: require_git_version(self.min_single_branch_version) self._source_repo = self.import_repo("server_new.export") self._stub_repo_git = _StubRepo("shallow-git") self.addCleanup(tear_down_repo, self._stub_repo_git) self._stub_repo_dw = _StubRepo("shallow-dw") self.addCleanup(tear_down_repo, self._stub_repo_dw) # shallow clone using stock git, then using dulwich run_git_or_fail( [ "clone", "--mirror", "--depth=1", "--no-single-branch", "file://" + self._source_repo.path, self._stub_repo_git.path, ] ) port = self._start_server(self._source_repo) run_git_or_fail( [ "clone", "--mirror", "--depth=1", "--no-single-branch", self.url(port), self._stub_repo_dw.path, ] ) # compare the two clones; they should be equal self.assertReposEqual( Repo(self._stub_repo_git.path), Repo(self._stub_repo_dw.path) ) def test_fetch_same_depth_into_shallow_clone_from_dulwich(self) -> None: require_git_version(self.min_single_branch_version) self._source_repo = self.import_repo("server_new.export") self._stub_repo = _StubRepo("shallow") self.addCleanup(tear_down_repo, self._stub_repo) port = self._start_server(self._source_repo) # Fetch at depth 2 run_git_or_fail( [ "clone", "--mirror", "--depth=2", "--no-single-branch", self.url(port), self._stub_repo.path, ] ) clone = self._stub_repo = Repo(self._stub_repo.path) # Fetching at the same depth is a no-op. run_git_or_fail( ["fetch", "--depth=2", self.url(port), *self.branch_args()], cwd=self._stub_repo.path, ) expected_shallow = [ b"94de09a530df27ac3bb613aaecdd539e0a0655e1", b"da5cd81e1883c62a25bb37c4d1f8ad965b29bf8d", ] self.assertEqual(expected_shallow, _get_shallow(clone)) self.assertReposNotEqual(clone, self._source_repo) def test_fetch_full_depth_into_shallow_clone_from_dulwich(self) -> None: require_git_version(self.min_single_branch_version) self._source_repo = self.import_repo("server_new.export") self._stub_repo = _StubRepo("shallow") self.addCleanup(tear_down_repo, self._stub_repo) port = self._start_server(self._source_repo) # Fetch at depth 2 run_git_or_fail( [ "clone", "--mirror", "--depth=2", "--no-single-branch", self.url(port), self._stub_repo.path, ] ) clone = self._stub_repo = Repo(self._stub_repo.path) # Fetching at the same depth is a no-op. run_git_or_fail( ["fetch", "--depth=2", self.url(port), *self.branch_args()], cwd=self._stub_repo.path, ) # The whole repo only has depth 4, so it should equal server_new. run_git_or_fail( ["fetch", "--depth=4", self.url(port), *self.branch_args()], cwd=self._stub_repo.path, ) self.assertEqual([], _get_shallow(clone)) self.assertReposEqual(clone, self._source_repo) def test_fetch_from_dulwich_issue_88_standard(self) -> None: # Basically an integration test to see that the ACK/NAK # generation works on repos with common head. self._source_repo = self.import_repo("issue88_expect_ack_nak_server.export") self._client_repo = self.import_repo("issue88_expect_ack_nak_client.export") port = self._start_server(self._source_repo) run_git_or_fail(["fetch", self.url(port), "master"], cwd=self._client_repo.path) self.assertObjectStoreEqual( self._source_repo.object_store, self._client_repo.object_store ) def test_fetch_from_dulwich_issue_88_alternative(self) -> None: # likewise, but the case where the two repos have no common parent self._source_repo = self.import_repo("issue88_expect_ack_nak_other.export") self._client_repo = self.import_repo("issue88_expect_ack_nak_client.export") port = self._start_server(self._source_repo) self.assertRaises( KeyError, self._client_repo.get_object, b"02a14da1fc1fc13389bbf32f0af7d8899f2b2323", ) run_git_or_fail(["fetch", self.url(port), "master"], cwd=self._client_repo.path) self.assertEqual( b"commit", self._client_repo.get_object( b"02a14da1fc1fc13389bbf32f0af7d8899f2b2323" ).type_name, ) def test_push_to_dulwich_issue_88_standard(self) -> None: # Same thing, but we reverse the role of the server/client # and do a push instead. self._source_repo = self.import_repo("issue88_expect_ack_nak_client.export") self._client_repo = self.import_repo("issue88_expect_ack_nak_server.export") port = self._start_server(self._source_repo) run_git_or_fail(["push", self.url(port), "master"], cwd=self._client_repo.path) self.assertReposEqual(self._source_repo, self._client_repo) # TODO(dborowitz): Come up with a better way of testing various permutations of # capabilities. The only reason it is the way it is now is that side-band-64k # was only recently introduced into git-receive-pack. class NoSideBand64kReceivePackHandler(ReceivePackHandler): """ReceivePackHandler that does not support side-band-64k.""" @classmethod def capabilities(cls): return [ c for c in ReceivePackHandler.capabilities() if c != CAPABILITY_SIDE_BAND_64K ] def ignore_error(error): """Check whether this error is safe to ignore.""" (e_type, e_value, e_tb) = error return issubclass(e_type, socket.error) and e_value[0] in ( errno.ECONNRESET, errno.EPIPE, ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/compat/test_client.py0000644000175100002000000006553214731042555020166 0ustar00runnerdocker# test_client.py -- Compatibility tests for git client. # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Compatibility tests between the Dulwich client and the cgit server.""" import copy import http.server import os import select import signal import stat import subprocess import sys import tarfile import tempfile import threading from contextlib import suppress from io import BytesIO from typing import NoReturn from unittest.mock import patch from urllib.parse import unquote from dulwich import client, file, index, objects, protocol, repo from dulwich.porcelain import tag_create from .. import SkipTest, expectedFailure from .utils import ( _DEFAULT_GIT, CompatTestCase, check_for_daemon, import_repo_to_dir, rmtree_ro, run_git_or_fail, ) if sys.platform == "win32": import ctypes class DulwichClientTestBase: """Tests for client/server compatibility.""" def setUp(self) -> None: self.gitroot = os.path.dirname( import_repo_to_dir("server_new.export").rstrip(os.sep) ) self.dest = os.path.join(self.gitroot, "dest") file.ensure_dir_exists(self.dest) run_git_or_fail(["init", "--quiet", "--bare"], cwd=self.dest) def tearDown(self) -> None: rmtree_ro(self.gitroot) def assertDestEqualsSrc(self) -> None: repo_dir = os.path.join(self.gitroot, "server_new.export") dest_repo_dir = os.path.join(self.gitroot, "dest") with repo.Repo(repo_dir) as src: with repo.Repo(dest_repo_dir) as dest: self.assertReposEqual(src, dest) def _client(self) -> NoReturn: raise NotImplementedError def _build_path(self) -> NoReturn: raise NotImplementedError def _do_send_pack(self) -> None: c = self._client() srcpath = os.path.join(self.gitroot, "server_new.export") with repo.Repo(srcpath) as src: sendrefs = dict(src.get_refs()) del sendrefs[b"HEAD"] c.send_pack( self._build_path("/dest"), lambda _: sendrefs, src.generate_pack_data, ) def test_send_pack(self) -> None: self._do_send_pack() self.assertDestEqualsSrc() def test_send_pack_nothing_to_send(self) -> None: self._do_send_pack() self.assertDestEqualsSrc() # nothing to send, but shouldn't raise either. self._do_send_pack() @staticmethod def _add_file(repo, tree_id, filename, contents): tree = repo[tree_id] blob = objects.Blob() blob.data = contents.encode("utf-8") repo.object_store.add_object(blob) tree.add(filename.encode("utf-8"), stat.S_IFREG | 0o644, blob.id) repo.object_store.add_object(tree) return tree.id def test_send_pack_from_shallow_clone(self) -> None: c = self._client() server_new_path = os.path.join(self.gitroot, "server_new.export") run_git_or_fail(["config", "http.uploadpack", "true"], cwd=server_new_path) run_git_or_fail(["config", "http.receivepack", "true"], cwd=server_new_path) remote_path = self._build_path("/server_new.export") with repo.Repo(self.dest) as local: result = c.fetch(remote_path, local, depth=1) for r in result.refs.items(): local.refs.set_if_equals(r[0], None, r[1]) tree_id = local[local.head()].tree for filename, contents in [ ("bar", "bar contents"), ("zop", "zop contents"), ]: tree_id = self._add_file(local, tree_id, filename, contents) commit_id = local.do_commit( message=b"add " + filename.encode("utf-8"), committer=b"Joe Example ", tree=tree_id, ) sendrefs = dict(local.get_refs()) del sendrefs[b"HEAD"] c.send_pack(remote_path, lambda _: sendrefs, local.generate_pack_data) with repo.Repo(server_new_path) as remote: self.assertEqual(remote.head(), commit_id) def test_send_without_report_status(self) -> None: c = self._client() c._send_capabilities.remove(b"report-status") srcpath = os.path.join(self.gitroot, "server_new.export") with repo.Repo(srcpath) as src: sendrefs = dict(src.get_refs()) del sendrefs[b"HEAD"] c.send_pack( self._build_path("/dest"), lambda _: sendrefs, src.generate_pack_data, ) self.assertDestEqualsSrc() def make_dummy_commit(self, dest): b = objects.Blob.from_string(b"hi") dest.object_store.add_object(b) t = index.commit_tree(dest.object_store, [(b"hi", b.id, 0o100644)]) c = objects.Commit() c.author = c.committer = b"Foo Bar " c.author_time = c.commit_time = 0 c.author_timezone = c.commit_timezone = 0 c.message = b"hi" c.tree = t dest.object_store.add_object(c) return c.id def disable_ff_and_make_dummy_commit(self): # disable non-fast-forward pushes to the server dest = repo.Repo(os.path.join(self.gitroot, "dest")) run_git_or_fail( ["config", "receive.denyNonFastForwards", "true"], cwd=dest.path ) commit_id = self.make_dummy_commit(dest) return dest, commit_id def compute_send(self, src): sendrefs = dict(src.get_refs()) del sendrefs[b"HEAD"] return sendrefs, src.generate_pack_data def test_send_pack_one_error(self) -> None: dest, dummy_commit = self.disable_ff_and_make_dummy_commit() dest.refs[b"refs/heads/master"] = dummy_commit repo_dir = os.path.join(self.gitroot, "server_new.export") with repo.Repo(repo_dir) as src: sendrefs, gen_pack = self.compute_send(src) c = self._client() result = c.send_pack( self._build_path("/dest"), lambda _: sendrefs, gen_pack ) self.assertEqual( { b"refs/heads/branch": None, b"refs/heads/master": "non-fast-forward", }, result.ref_status, ) def test_send_pack_multiple_errors(self) -> None: dest, dummy = self.disable_ff_and_make_dummy_commit() # set up for two non-ff errors branch, master = b"refs/heads/branch", b"refs/heads/master" dest.refs[branch] = dest.refs[master] = dummy repo_dir = os.path.join(self.gitroot, "server_new.export") with repo.Repo(repo_dir) as src: sendrefs, gen_pack = self.compute_send(src) c = self._client() result = c.send_pack( self._build_path("/dest"), lambda _: sendrefs, gen_pack ) self.assertEqual( {branch: "non-fast-forward", master: "non-fast-forward"}, result.ref_status, ) def test_archive(self) -> None: c = self._client() f = BytesIO() c.archive(self._build_path("/server_new.export"), b"HEAD", f.write) f.seek(0) tf = tarfile.open(fileobj=f) self.assertEqual(["baz", "foo"], tf.getnames()) def test_fetch_pack(self) -> None: c = self._client() with repo.Repo(os.path.join(self.gitroot, "dest")) as dest: result = c.fetch(self._build_path("/server_new.export"), dest) self.assertEqual( {b"HEAD": b"refs/heads/master"}, result.symrefs, ) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() def test_fetch_pack_with_nondefault_symref(self) -> None: c = self._client() src = repo.Repo(os.path.join(self.gitroot, "server_new.export")) src.refs.add_if_new(b"refs/heads/main", src.refs[b"refs/heads/master"]) src.refs.set_symbolic_ref(b"HEAD", b"refs/heads/main") with repo.Repo(os.path.join(self.gitroot, "dest")) as dest: result = c.fetch(self._build_path("/server_new.export"), dest) self.assertEqual( {b"HEAD": b"refs/heads/main"}, result.symrefs, ) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() def test_get_refs_with_peeled_tag(self) -> None: tag_create( os.path.join(self.gitroot, "server_new.export"), b"v1.0", message=b"tagging", annotated=True, ) c = self._client() refs = c.get_refs(self._build_path("/server_new.export")) self.assertEqual( [ b"HEAD", b"refs/heads/branch", b"refs/heads/master", b"refs/tags/v1.0", b"refs/tags/v1.0^{}", ], sorted(refs.keys()), ) def test_get_refs_with_ref_prefix(self) -> None: c = self._client() refs = c.get_refs( self._build_path("/server_new.export"), ref_prefix=[b"refs/heads"] ) self.assertEqual( [ b"refs/heads/branch", b"refs/heads/master", ], sorted(refs.keys()), ) def test_fetch_pack_depth(self) -> None: c = self._client() with repo.Repo(os.path.join(self.gitroot, "dest")) as dest: result = c.fetch(self._build_path("/server_new.export"), dest, depth=1) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertEqual( dest.get_shallow(), { b"35e0b59e187dd72a0af294aedffc213eaa4d03ff", b"514dc6d3fbfe77361bcaef320c4d21b72bc10be9", }, ) def test_repeat(self) -> None: c = self._client() with repo.Repo(os.path.join(self.gitroot, "dest")) as dest: result = c.fetch(self._build_path("/server_new.export"), dest) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() result = c.fetch(self._build_path("/server_new.export"), dest) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() def test_fetch_empty_pack(self) -> None: c = self._client() with repo.Repo(os.path.join(self.gitroot, "dest")) as dest: result = c.fetch(self._build_path("/server_new.export"), dest) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() def dw(refs, **kwargs): return list(refs.values()) result = c.fetch( self._build_path("/server_new.export"), dest, determine_wants=dw, ) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() def test_incremental_fetch_pack(self) -> None: self.test_fetch_pack() dest, dummy = self.disable_ff_and_make_dummy_commit() dest.refs[b"refs/heads/master"] = dummy c = self._client() repo_dir = os.path.join(self.gitroot, "server_new.export") with repo.Repo(repo_dir) as dest: result = c.fetch(self._build_path("/dest"), dest) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() def test_fetch_pack_no_side_band_64k(self) -> None: if protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH >= 2: raise SkipTest("side-band-64k cannot be disabled with git protocol v2") c = self._client() c._fetch_capabilities.remove(b"side-band-64k") with repo.Repo(os.path.join(self.gitroot, "dest")) as dest: result = c.fetch(self._build_path("/server_new.export"), dest) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) self.assertDestEqualsSrc() def test_fetch_pack_zero_sha(self) -> None: # zero sha1s are already present on the client, and should # be ignored c = self._client() with repo.Repo(os.path.join(self.gitroot, "dest")) as dest: result = c.fetch( self._build_path("/server_new.export"), dest, lambda refs, **kwargs: [protocol.ZERO_SHA], ) for r in result.refs.items(): dest.refs.set_if_equals(r[0], None, r[1]) def test_send_remove_branch(self) -> None: with repo.Repo(os.path.join(self.gitroot, "dest")) as dest: dummy_commit = self.make_dummy_commit(dest) dest.refs[b"refs/heads/master"] = dummy_commit dest.refs[b"refs/heads/abranch"] = dummy_commit sendrefs = dict(dest.refs) sendrefs[b"refs/heads/abranch"] = b"00" * 20 del sendrefs[b"HEAD"] def gen_pack(have, want, ofs_delta=False, progress=None): return 0, [] c = self._client() self.assertEqual(dest.refs[b"refs/heads/abranch"], dummy_commit) c.send_pack(self._build_path("/dest"), lambda _: sendrefs, gen_pack) self.assertNotIn(b"refs/heads/abranch", dest.refs) def test_send_new_branch_empty_pack(self) -> None: with repo.Repo(os.path.join(self.gitroot, "dest")) as dest: dummy_commit = self.make_dummy_commit(dest) dest.refs[b"refs/heads/master"] = dummy_commit dest.refs[b"refs/heads/abranch"] = dummy_commit sendrefs = {b"refs/heads/bbranch": dummy_commit} def gen_pack(have, want, ofs_delta=False, progress=None): return 0, [] c = self._client() self.assertEqual(dest.refs[b"refs/heads/abranch"], dummy_commit) c.send_pack(self._build_path("/dest"), lambda _: sendrefs, gen_pack) self.assertEqual(dummy_commit, dest.refs[b"refs/heads/abranch"]) def test_get_refs(self) -> None: c = self._client() refs = c.get_refs(self._build_path("/server_new.export")) repo_dir = os.path.join(self.gitroot, "server_new.export") with repo.Repo(repo_dir) as dest: self.assertDictEqual(dest.refs.as_dict(), refs) class DulwichTCPClientTest(CompatTestCase, DulwichClientTestBase): def setUp(self) -> None: CompatTestCase.setUp(self) DulwichClientTestBase.setUp(self) if check_for_daemon(limit=1): raise SkipTest( f"git-daemon was already running on port {protocol.TCP_GIT_PORT}" ) fd, self.pidfile = tempfile.mkstemp( prefix="dulwich-test-git-client", suffix=".pid" ) os.fdopen(fd).close() args = [ _DEFAULT_GIT, "daemon", "--verbose", "--export-all", f"--pid-file={self.pidfile}", f"--base-path={self.gitroot}", "--enable=receive-pack", "--enable=upload-archive", "--listen=localhost", "--reuseaddr", self.gitroot, ] self.process = subprocess.Popen( args, cwd=self.gitroot, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) if not check_for_daemon(): raise SkipTest("git-daemon failed to start") def tearDown(self) -> None: with open(self.pidfile) as f: pid = int(f.read().strip()) if sys.platform == "win32": PROCESS_TERMINATE = 1 handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, pid) ctypes.windll.kernel32.TerminateProcess(handle, -1) ctypes.windll.kernel32.CloseHandle(handle) else: with suppress(OSError): os.kill(pid, signal.SIGKILL) os.unlink(self.pidfile) self.process.wait() self.process.stdout.close() self.process.stderr.close() DulwichClientTestBase.tearDown(self) CompatTestCase.tearDown(self) def _client(self): return client.TCPGitClient("localhost") def _build_path(self, path): return path if sys.platform == "win32" and protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH < 2: @expectedFailure def test_fetch_pack_no_side_band_64k(self) -> None: DulwichClientTestBase.test_fetch_pack_no_side_band_64k(self) def test_send_remove_branch(self) -> None: # This test fails intermittently on my machine, probably due to some sort # of race condition. Probably also related to #1015 self.skipTest("skip flaky test; see #1015") @patch("dulwich.protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH", new=0) class DulwichTCPClientTestGitProtov0(DulwichTCPClientTest): pass class TestSSHVendor: @staticmethod def run_command( host, command, username=None, port=None, password=None, key_filename=None, protocol_version=None, ): cmd, path = command.split(" ") cmd = cmd.split("-", 1) path = path.replace("'", "") env = dict(os.environ) if protocol_version is None: protocol_version = protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH if protocol_version > 0: env["GIT_PROTOCOL"] = f"version={protocol_version}" p = subprocess.Popen( [*cmd, path], bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, ) return client.SubprocessWrapper(p) class DulwichMockSSHClientTest(CompatTestCase, DulwichClientTestBase): def setUp(self) -> None: CompatTestCase.setUp(self) DulwichClientTestBase.setUp(self) self.real_vendor = client.get_ssh_vendor client.get_ssh_vendor = TestSSHVendor def tearDown(self) -> None: DulwichClientTestBase.tearDown(self) CompatTestCase.tearDown(self) client.get_ssh_vendor = self.real_vendor def _client(self): return client.SSHGitClient("localhost") def _build_path(self, path): return self.gitroot + path @patch("dulwich.protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH", new=0) class DulwichMockSSHClientTestGitProtov0(DulwichMockSSHClientTest): pass class DulwichSubprocessClientTest(CompatTestCase, DulwichClientTestBase): def setUp(self) -> None: CompatTestCase.setUp(self) DulwichClientTestBase.setUp(self) def tearDown(self) -> None: DulwichClientTestBase.tearDown(self) CompatTestCase.tearDown(self) def _client(self): return client.SubprocessGitClient() def _build_path(self, path): return self.gitroot + path @patch("dulwich.protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH", new=0) class DulwichSubprocessClientTestGitProtov0(DulwichSubprocessClientTest): pass class GitHTTPRequestHandler(http.server.SimpleHTTPRequestHandler): """HTTP Request handler that calls out to 'git http-backend'.""" # Make rfile unbuffered -- we need to read one line and then pass # the rest to a subprocess, so we can't use buffered input. rbufsize = 0 def do_POST(self) -> None: self.run_backend() def do_GET(self) -> None: self.run_backend() def send_head(self): return self.run_backend() def log_request(self, code="-", size="-") -> None: # Let's be quiet, the test suite is noisy enough already pass def run_backend(self) -> None: """Call out to git http-backend.""" # Based on CGIHTTPServer.CGIHTTPRequestHandler.run_cgi: # Copyright (c) 2001-2010 Python Software Foundation; # All Rights Reserved # Licensed under the Python Software Foundation License. rest = self.path # find an explicit query string, if present. i = rest.rfind("?") if i >= 0: rest, query = rest[:i], rest[i + 1 :] else: query = "" env = copy.deepcopy(os.environ) env["SERVER_SOFTWARE"] = self.version_string() env["SERVER_NAME"] = self.server.server_name env["GATEWAY_INTERFACE"] = "CGI/1.1" env["SERVER_PROTOCOL"] = self.protocol_version env["SERVER_PORT"] = str(self.server.server_port) env["GIT_PROJECT_ROOT"] = self.server.root_path env["GIT_HTTP_EXPORT_ALL"] = "1" env["REQUEST_METHOD"] = self.command uqrest = unquote(rest) env["PATH_INFO"] = uqrest env["SCRIPT_NAME"] = "/" if query: env["QUERY_STRING"] = query host = self.address_string() if host != self.client_address[0]: env["REMOTE_HOST"] = host env["REMOTE_ADDR"] = self.client_address[0] authorization = self.headers.get("authorization") if authorization: authorization = authorization.split() if len(authorization) == 2: import base64 import binascii env["AUTH_TYPE"] = authorization[0] if authorization[0].lower() == "basic": try: authorization = base64.decodestring(authorization[1]) except binascii.Error: pass else: authorization = authorization.split(":") if len(authorization) == 2: env["REMOTE_USER"] = authorization[0] # XXX REMOTE_IDENT content_type = self.headers.get("content-type") if content_type: env["CONTENT_TYPE"] = content_type length = self.headers.get("content-length") if length: env["CONTENT_LENGTH"] = length referer = self.headers.get("referer") if referer: env["HTTP_REFERER"] = referer accept = [] for line in self.headers.getallmatchingheaders("accept"): if line[:1] in "\t\n\r ": accept.append(line.strip()) else: accept = accept + line[7:].split(",") env["HTTP_ACCEPT"] = ",".join(accept) ua = self.headers.get("user-agent") if ua: env["HTTP_USER_AGENT"] = ua co = self.headers.get("cookie") if co: env["HTTP_COOKIE"] = co proto = self.headers.get("Git-Protocol") if proto: env["GIT_PROTOCOL"] = proto # XXX Other HTTP_* headers # Since we're setting the env in the parent, provide empty # values to override previously set values for k in ( "QUERY_STRING", "REMOTE_HOST", "CONTENT_LENGTH", "HTTP_USER_AGENT", "HTTP_COOKIE", "HTTP_REFERER", ): env.setdefault(k, "") self.wfile.write(b"HTTP/1.1 200 Script output follows\r\n") self.wfile.write((f"Server: {self.server.server_name}\r\n").encode("ascii")) self.wfile.write((f"Date: {self.date_time_string()}\r\n").encode("ascii")) decoded_query = query.replace("+", " ") try: nbytes = int(length) except (TypeError, ValueError): nbytes = -1 if self.command.lower() == "post": if nbytes > 0: data = self.rfile.read(nbytes) elif self.headers.get("transfer-encoding") == "chunked": chunks = [] while True: line = self.rfile.readline() length = int(line.rstrip(), 16) chunk = self.rfile.read(length + 2) chunks.append(chunk[:-2]) if length == 0: break data = b"".join(chunks) env["CONTENT_LENGTH"] = str(len(data)) else: raise AssertionError else: data = None env["CONTENT_LENGTH"] = "0" # throw away additional data [see bug #427345] while select.select([self.rfile._sock], [], [], 0)[0]: if not self.rfile._sock.recv(1): break args = ["http-backend"] if "=" not in decoded_query: args.append(decoded_query) stdout = run_git_or_fail(args, input=data, env=env, stderr=subprocess.PIPE) self.wfile.write(stdout) class HTTPGitServer(http.server.HTTPServer): allow_reuse_address = True def __init__(self, server_address, root_path) -> None: http.server.HTTPServer.__init__(self, server_address, GitHTTPRequestHandler) self.root_path = root_path self.server_name = "localhost" def get_url(self) -> str: return f"http://{self.server_name}:{self.server_port}/" class DulwichHttpClientTest(CompatTestCase, DulwichClientTestBase): min_git_version = (1, 7, 0, 2) def setUp(self) -> None: CompatTestCase.setUp(self) DulwichClientTestBase.setUp(self) self._httpd = HTTPGitServer(("localhost", 0), self.gitroot) self.addCleanup(self._httpd.shutdown) threading.Thread(target=self._httpd.serve_forever).start() run_git_or_fail(["config", "http.uploadpack", "true"], cwd=self.dest) run_git_or_fail(["config", "http.receivepack", "true"], cwd=self.dest) def tearDown(self) -> None: DulwichClientTestBase.tearDown(self) CompatTestCase.tearDown(self) self._httpd.shutdown() self._httpd.socket.close() def _client(self): return client.HttpGitClient(self._httpd.get_url()) def _build_path(self, path): return path def test_archive(self) -> NoReturn: raise SkipTest("exporting archives not supported over http") @patch("dulwich.protocol.DEFAULT_GIT_PROTOCOL_VERSION_FETCH", new=0) class DulwichHttpClientTestGitProtov0(DulwichHttpClientTest): pass ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/compat/test_pack.py0000644000175100002000000001477414731042555017630 0ustar00runnerdocker# test_pack.py -- Compatibility tests for git packs. # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Compatibility tests for git packs.""" import binascii import os import re import shutil import tempfile from typing import NoReturn from dulwich.objects import Blob from dulwich.pack import write_pack from .. import SkipTest from ..test_pack import PackTests, a_sha, pack1_sha from .utils import require_git_version, run_git_or_fail _NON_DELTA_RE = re.compile(b"non delta: (?P\\d+) objects") def _git_verify_pack_object_list(output): pack_shas = set() for line in output.splitlines(): sha = line[:40] try: binascii.unhexlify(sha) except (TypeError, binascii.Error): continue # non-sha line pack_shas.add(sha) return pack_shas class TestPack(PackTests): """Compatibility tests for reading and writing pack files.""" def setUp(self) -> None: require_git_version((1, 5, 0)) super().setUp() self._tempdir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self._tempdir) def test_copy(self) -> None: with self.get_pack(pack1_sha) as origpack: self.assertSucceeds(origpack.index.check) pack_path = os.path.join(self._tempdir, "Elch") write_pack(pack_path, origpack.pack_tuples()) output = run_git_or_fail(["verify-pack", "-v", pack_path]) orig_shas = {o.id for o in origpack.iterobjects()} self.assertEqual(orig_shas, _git_verify_pack_object_list(output)) def test_deltas_work(self) -> None: with self.get_pack(pack1_sha) as orig_pack: orig_blob = orig_pack[a_sha] new_blob = Blob() new_blob.data = orig_blob.data + b"x" all_to_pack = [(o, None) for o in orig_pack.iterobjects()] + [ (new_blob, None) ] pack_path = os.path.join(self._tempdir, "pack_with_deltas") write_pack(pack_path, all_to_pack, deltify=True) output = run_git_or_fail(["verify-pack", "-v", pack_path]) self.assertEqual( {x[0].id for x in all_to_pack}, _git_verify_pack_object_list(output), ) # We specifically made a new blob that should be a delta # against the blob a_sha, so make sure we really got only 3 # non-delta objects: got_non_delta = int(_NON_DELTA_RE.search(output).group("non_delta")) self.assertEqual( 3, got_non_delta, f"Expected 3 non-delta objects, got {got_non_delta}", ) def test_delta_medium_object(self) -> None: # This tests an object set that will have a copy operation # 2**20 in size. with self.get_pack(pack1_sha) as orig_pack: orig_blob = orig_pack[a_sha] new_blob = Blob() new_blob.data = orig_blob.data + (b"x" * 2**20) new_blob_2 = Blob() new_blob_2.data = new_blob.data + b"y" all_to_pack = [ *list(orig_pack.pack_tuples()), (new_blob, None), (new_blob_2, None), ] pack_path = os.path.join(self._tempdir, "pack_with_deltas") write_pack(pack_path, all_to_pack, deltify=True) output = run_git_or_fail(["verify-pack", "-v", pack_path]) self.assertEqual( {x[0].id for x in all_to_pack}, _git_verify_pack_object_list(output), ) # We specifically made a new blob that should be a delta # against the blob a_sha, so make sure we really got only 3 # non-delta objects: got_non_delta = int(_NON_DELTA_RE.search(output).group("non_delta")) self.assertEqual( 3, got_non_delta, f"Expected 3 non-delta objects, got {got_non_delta}", ) # We expect one object to have a delta chain length of two # (new_blob_2), so let's verify that actually happens: self.assertIn(b"chain length = 2", output) # This test is SUPER slow: over 80 seconds on a 2012-era # laptop. This is because SequenceMatcher is worst-case quadratic # on the input size. It's impractical to produce deltas for # objects this large, but it's still worth doing the right thing # when it happens. def test_delta_large_object(self) -> NoReturn: # This tests an object set that will have a copy operation # 2**25 in size. This is a copy large enough that it requires # two copy operations in git's binary delta format. raise SkipTest("skipping slow, large test") with self.get_pack(pack1_sha) as orig_pack: new_blob = Blob() new_blob.data = "big blob" + ("x" * 2**25) new_blob_2 = Blob() new_blob_2.data = new_blob.data + "y" all_to_pack = [ *list(orig_pack.pack_tuples()), (new_blob, None), (new_blob_2, None), ] pack_path = os.path.join(self._tempdir, "pack_with_deltas") write_pack(pack_path, all_to_pack, deltify=True) output = run_git_or_fail(["verify-pack", "-v", pack_path]) self.assertEqual( {x[0].id for x in all_to_pack}, _git_verify_pack_object_list(output), ) # We specifically made a new blob that should be a delta # against the blob a_sha, so make sure we really got only 4 # non-delta objects: got_non_delta = int(_NON_DELTA_RE.search(output).group("non_delta")) self.assertEqual( 4, got_non_delta, f"Expected 4 non-delta objects, got {got_non_delta}", ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/compat/test_patch.py0000644000175100002000000001010414731042555017770 0ustar00runnerdocker# test_patch.py -- test patch compatibility with CGit # Copyright (C) 2019 Boris Feld # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests related to patch compatibility with CGit.""" import os import shutil import tempfile from io import BytesIO from dulwich import porcelain from dulwich.repo import Repo from .utils import CompatTestCase, run_git_or_fail class CompatPatchTestCase(CompatTestCase): def setUp(self) -> None: super().setUp() self.test_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.test_dir) self.repo_path = os.path.join(self.test_dir, "repo") self.repo = Repo.init(self.repo_path, mkdir=True) self.addCleanup(self.repo.close) def test_patch_apply(self) -> None: # Prepare the repository # Create some files and commit them file_list = ["to_exists", "to_modify", "to_delete"] for file in file_list: file_path = os.path.join(self.repo_path, file) # Touch the files with open(file_path, "w"): pass self.repo.stage(file_list) first_commit = self.repo.do_commit(b"The first commit") # Make a copy of the repository so we can apply the diff later copy_path = os.path.join(self.test_dir, "copy") shutil.copytree(self.repo_path, copy_path) # Do some changes with open(os.path.join(self.repo_path, "to_modify"), "w") as f: f.write("Modified!") os.remove(os.path.join(self.repo_path, "to_delete")) with open(os.path.join(self.repo_path, "to_add"), "w"): pass self.repo.stage(["to_modify", "to_delete", "to_add"]) second_commit = self.repo.do_commit(b"The second commit") # Get the patch first_tree = self.repo[first_commit].tree second_tree = self.repo[second_commit].tree outstream = BytesIO() porcelain.diff_tree( self.repo.path, first_tree, second_tree, outstream=outstream ) # Save it on disk patch_path = os.path.join(self.test_dir, "patch.patch") with open(patch_path, "wb") as patch: patch.write(outstream.getvalue()) # And try to apply it to the copy directory git_command = ["-C", copy_path, "apply", patch_path] run_git_or_fail(git_command) # And now check that the files contents are exactly the same between # the two repositories original_files = set(os.listdir(self.repo_path)) new_files = set(os.listdir(copy_path)) # Check that we have the exact same files in both repositories self.assertEqual(original_files, new_files) for file in original_files: if file == ".git": continue original_file_path = os.path.join(self.repo_path, file) copy_file_path = os.path.join(copy_path, file) self.assertTrue(os.path.isfile(copy_file_path)) with open(original_file_path, "rb") as original_file: original_content = original_file.read() with open(copy_file_path, "rb") as copy_file: copy_content = copy_file.read() self.assertEqual(original_content, copy_content) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/compat/test_porcelain.py0000644000175100002000000001243114731042555020652 0ustar00runnerdocker# test_porcelain .py -- Tests for dulwich.porcelain/CGit compatibility # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Compatibility tests for dulwich.porcelain.""" import os from unittest import skipIf from dulwich import porcelain from dulwich.tests.utils import build_commit_graph from ..test_porcelain import PorcelainGpgTestCase from .utils import CompatTestCase, run_git_or_fail try: import gpgme except ImportError: gpgme = None @skipIf( gpgme is None, "gpgme not available, skipping tests that require GPG signing", ) class TagCreateSignTestCase(PorcelainGpgTestCase, CompatTestCase): def test_sign(self) -> None: # Test that dulwich signatures can be verified by CGit c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id cfg = self.repo.get_config() cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID) self.import_default_key() porcelain.tag_create( self.repo.path, b"tryme", b"foo ", b"bar", annotated=True, sign=True, ) run_git_or_fail( [f"--git-dir={self.repo.controldir()}", "tag", "-v", "tryme"], env={"GNUPGHOME": os.environ["GNUPGHOME"]}, ) def test_verify(self) -> None: # Test that CGit signatures can be verified by dulwich c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id self.import_default_key() run_git_or_fail( [ f"--git-dir={self.repo.controldir()}", "tag", "-u", PorcelainGpgTestCase.DEFAULT_KEY_ID, "-m", "foo", "verifyme", ], env={ "GNUPGHOME": os.environ["GNUPGHOME"], "GIT_COMMITTER_NAME": "Joe Example", "GIT_COMMITTER_EMAIL": "joe@example.com", }, ) tag = self.repo[b"refs/tags/verifyme"] self.assertNotEqual(tag.signature, None) tag.verify() @skipIf( gpgme is None, "gpgme not available, skipping tests that require GPG signing", ) class CommitCreateSignTestCase(PorcelainGpgTestCase, CompatTestCase): def test_sign(self): # Test that dulwich signatures can be verified by CGit cfg = self.repo.get_config() cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID) self.import_default_key() porcelain.commit( self.repo.path, b"messy message messiah", b"foo ", signoff=True, ) run_git_or_fail( [f"--git-dir={self.repo.controldir()}", "verify-commit", "-v", "HEAD"], env={"GNUPGHOME": os.environ["GNUPGHOME"]}, ) def test_verify(self): # Test that CGit signatures can be verified by dulwich self.import_default_key() run_git_or_fail( [ f"--git-dir={self.repo.controldir()}", "commit", "--allow-empty", "-S" + PorcelainGpgTestCase.DEFAULT_KEY_ID, "-m", "foo", ], env={ "GNUPGHOME": os.environ["GNUPGHOME"], "GIT_COMMITTER_NAME": "Joe Example", "GIT_COMMITTER_EMAIL": "joe@example.com", }, ) commit = self.repo[b"HEAD"] self.assertNotEqual(commit.gpgsig, None) commit.verify() def test_verify_with_empty_message(self): # Test that CGit signatures can be verified by dulwich self.import_default_key() run_git_or_fail( [ f"--git-dir={self.repo.controldir()}", "commit", "--allow-empty", "-S" + PorcelainGpgTestCase.DEFAULT_KEY_ID, "--allow-empty-message", "-m", "", ], env={ "GNUPGHOME": os.environ["GNUPGHOME"], "GIT_COMMITTER_NAME": "Joe Example", "GIT_COMMITTER_EMAIL": "joe@example.com", }, ) commit = self.repo[b"HEAD"] self.assertNotEqual(commit.gpgsig, None) commit.verify() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/compat/test_repository.py0000644000175100002000000002223314731042555021116 0ustar00runnerdocker# test_repo.py -- Git repo compatibility tests # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Compatibility tests for dulwich repositories.""" import os import tempfile from io import BytesIO from itertools import chain from dulwich.objects import hex_to_sha from dulwich.repo import Repo, check_ref_format from .utils import CompatTestCase, require_git_version, rmtree_ro, run_git_or_fail class ObjectStoreTestCase(CompatTestCase): """Tests for git repository compatibility.""" def setUp(self) -> None: super().setUp() self._repo = self.import_repo("server_new.export") def _run_git(self, args): return run_git_or_fail(args, cwd=self._repo.path) def _parse_refs(self, output): refs = {} for line in BytesIO(output): fields = line.rstrip(b"\n").split(b" ") self.assertEqual(3, len(fields)) refname, type_name, sha = fields check_ref_format(refname[5:]) hex_to_sha(sha) refs[refname] = (type_name, sha) return refs def _parse_objects(self, output): return {s.rstrip(b"\n").split(b" ")[0] for s in BytesIO(output)} def test_bare(self) -> None: self.assertTrue(self._repo.bare) self.assertFalse(os.path.exists(os.path.join(self._repo.path, ".git"))) def test_head(self) -> None: output = self._run_git(["rev-parse", "HEAD"]) head_sha = output.rstrip(b"\n") hex_to_sha(head_sha) self.assertEqual(head_sha, self._repo.refs[b"HEAD"]) def test_refs(self) -> None: output = self._run_git( ["for-each-ref", "--format=%(refname) %(objecttype) %(objectname)"] ) expected_refs = self._parse_refs(output) actual_refs = {} for refname, sha in self._repo.refs.as_dict().items(): if refname == b"HEAD": continue # handled in test_head obj = self._repo[sha] self.assertEqual(sha, obj.id) actual_refs[refname] = (obj.type_name, obj.id) self.assertEqual(expected_refs, actual_refs) # TODO(dborowitz): peeled ref tests def _get_loose_shas(self): output = self._run_git(["rev-list", "--all", "--objects", "--unpacked"]) return self._parse_objects(output) def _get_all_shas(self): output = self._run_git(["rev-list", "--all", "--objects"]) return self._parse_objects(output) def assertShasMatch(self, expected_shas, actual_shas_iter) -> None: actual_shas = set() for sha in actual_shas_iter: obj = self._repo[sha] self.assertEqual(sha, obj.id) actual_shas.add(sha) self.assertEqual(expected_shas, actual_shas) def test_loose_objects(self) -> None: # TODO(dborowitz): This is currently not very useful since # fast-imported repos only contained packed objects. expected_shas = self._get_loose_shas() self.assertShasMatch( expected_shas, self._repo.object_store._iter_loose_objects() ) def test_packed_objects(self) -> None: expected_shas = self._get_all_shas() - self._get_loose_shas() self.assertShasMatch( expected_shas, chain.from_iterable(self._repo.object_store.packs) ) def test_all_objects(self) -> None: expected_shas = self._get_all_shas() self.assertShasMatch(expected_shas, iter(self._repo.object_store)) class WorkingTreeTestCase(ObjectStoreTestCase): """Test for compatibility with git-worktree.""" min_git_version = (2, 5, 0) def create_new_worktree(self, repo_dir, branch): """Create a new worktree using git-worktree. Args: repo_dir: The directory of the main working tree. branch: The branch or commit to checkout in the new worktree. Returns: The path to the new working tree. """ temp_dir = tempfile.mkdtemp() run_git_or_fail(["worktree", "add", temp_dir, branch], cwd=repo_dir) self.addCleanup(rmtree_ro, temp_dir) return temp_dir def setUp(self) -> None: super().setUp() self._worktree_path = self.create_new_worktree(self._repo.path, "branch") self._worktree_repo = Repo(self._worktree_path) self.addCleanup(self._worktree_repo.close) self._mainworktree_repo = self._repo self._number_of_working_tree = 2 self._repo = self._worktree_repo def test_refs(self) -> None: super().test_refs() self.assertEqual( self._mainworktree_repo.refs.allkeys(), self._repo.refs.allkeys() ) def test_head_equality(self) -> None: self.assertNotEqual( self._repo.refs[b"HEAD"], self._mainworktree_repo.refs[b"HEAD"] ) def test_bare(self) -> None: self.assertFalse(self._repo.bare) self.assertTrue(os.path.isfile(os.path.join(self._repo.path, ".git"))) def _parse_worktree_list(self, output): worktrees = [] for line in BytesIO(output): fields = line.rstrip(b"\n").split() worktrees.append(tuple(f.decode() for f in fields)) return worktrees def test_git_worktree_list(self) -> None: # 'git worktree list' was introduced in 2.7.0 require_git_version((2, 7, 0)) output = run_git_or_fail(["worktree", "list"], cwd=self._repo.path) worktrees = self._parse_worktree_list(output) self.assertEqual(len(worktrees), self._number_of_working_tree) self.assertEqual(worktrees[0][1], "(bare)") self.assertTrue(os.path.samefile(worktrees[0][0], self._mainworktree_repo.path)) output = run_git_or_fail(["worktree", "list"], cwd=self._mainworktree_repo.path) worktrees = self._parse_worktree_list(output) self.assertEqual(len(worktrees), self._number_of_working_tree) self.assertEqual(worktrees[0][1], "(bare)") self.assertTrue(os.path.samefile(worktrees[0][0], self._mainworktree_repo.path)) def test_git_worktree_config(self) -> None: """Test that git worktree config parsing matches the git CLI's behavior.""" # Set some config value in the main repo using the git CLI require_git_version((2, 7, 0)) test_name = "Jelmer" test_email = "jelmer@apache.org" run_git_or_fail(["config", "user.name", test_name], cwd=self._repo.path) run_git_or_fail(["config", "user.email", test_email], cwd=self._repo.path) worktree_cfg = self._worktree_repo.get_config() main_cfg = self._repo.get_config() # Assert that both the worktree repo and main repo have the same view of the config, # and that the config matches what we set with the git cli self.assertEqual(worktree_cfg, main_cfg) for c in [worktree_cfg, main_cfg]: self.assertEqual(test_name.encode(), c.get((b"user",), b"name")) self.assertEqual(test_email.encode(), c.get((b"user",), b"email")) # Read the config values in the worktree with the git cli and assert they match # the dulwich-parsed configs output_name = ( run_git_or_fail(["config", "user.name"], cwd=self._mainworktree_repo.path) .decode() .rstrip("\n") ) output_email = ( run_git_or_fail(["config", "user.email"], cwd=self._mainworktree_repo.path) .decode() .rstrip("\n") ) self.assertEqual(test_name, output_name) self.assertEqual(test_email, output_email) class InitNewWorkingDirectoryTestCase(WorkingTreeTestCase): """Test compatibility of Repo.init_new_working_directory.""" min_git_version = (2, 5, 0) def setUp(self) -> None: super().setUp() self._other_worktree = self._repo worktree_repo_path = tempfile.mkdtemp() self.addCleanup(rmtree_ro, worktree_repo_path) self._repo = Repo._init_new_working_directory( worktree_repo_path, self._mainworktree_repo ) self.addCleanup(self._repo.close) self._number_of_working_tree = 3 def test_head_equality(self) -> None: self.assertEqual( self._repo.refs[b"HEAD"], self._mainworktree_repo.refs[b"HEAD"] ) def test_bare(self) -> None: self.assertFalse(self._repo.bare) self.assertTrue(os.path.isfile(os.path.join(self._repo.path, ".git"))) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/compat/test_server.py0000644000175100002000000000671614731042555020215 0ustar00runnerdocker# test_server.py -- Compatibility tests for git server. # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Compatibility tests between Dulwich and the cgit server. Warning: these tests should be fairly stable, but when writing/debugging new tests, deadlocks may freeze the test process such that it cannot be Ctrl-C'ed. On POSIX systems, you can kill the tests with Ctrl-Z, "kill %". """ import os import sys import threading from dulwich.server import DictBackend, TCPGitServer from .. import skipIf from .server_utils import NoSideBand64kReceivePackHandler, ServerTests from .utils import CompatTestCase, require_git_version @skipIf(sys.platform == "win32", "Broken on windows, with very long fail time.") class GitServerTestCase(ServerTests, CompatTestCase): """Tests for client/server compatibility. This server test case does not use side-band-64k in git-receive-pack. """ protocol = "git" def _handlers(self): return {b"git-receive-pack": NoSideBand64kReceivePackHandler} def _check_server(self, dul_server) -> None: receive_pack_handler_cls = dul_server.handlers[b"git-receive-pack"] caps = receive_pack_handler_cls.capabilities() self.assertNotIn(b"side-band-64k", caps) def _start_server(self, repo): backend = DictBackend({b"/": repo}) dul_server = TCPGitServer(backend, b"localhost", 0, handlers=self._handlers()) self._check_server(dul_server) self.addCleanup(dul_server.shutdown) self.addCleanup(dul_server.server_close) threading.Thread(target=dul_server.serve).start() self._server = dul_server _, port = self._server.socket.getsockname() return port @skipIf(sys.platform == "win32", "Broken on windows, with very long fail time.") class GitServerSideBand64kTestCase(GitServerTestCase): """Tests for client/server compatibility with side-band-64k support.""" # side-band-64k in git-receive-pack was introduced in git 1.7.0.2 min_git_version = (1, 7, 0, 2) def setUp(self) -> None: super().setUp() # side-band-64k is broken in the windows client. # https://github.com/msysgit/git/issues/101 # Fix has landed for the 1.9.3 release. if os.name == "nt": require_git_version((1, 9, 3)) def _handlers(self) -> None: return None # default handlers include side-band-64k def _check_server(self, server) -> None: receive_pack_handler_cls = server.handlers[b"git-receive-pack"] caps = receive_pack_handler_cls.capabilities() self.assertIn(b"side-band-64k", caps) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/compat/test_utils.py0000644000175100002000000000674114731042555020045 0ustar00runnerdocker# test_utils.py -- Tests for git compatibility utilities # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for git compatibility utilities.""" from .. import SkipTest, TestCase from . import utils class GitVersionTests(TestCase): def setUp(self) -> None: super().setUp() self._orig_run_git = utils.run_git self._version_str = None # tests can override to set stub version def run_git(args, **unused_kwargs): self.assertEqual(["--version"], args) return 0, self._version_str, "" utils.run_git = run_git def tearDown(self) -> None: super().tearDown() utils.run_git = self._orig_run_git def test_git_version_none(self) -> None: self._version_str = b"not a git version" self.assertEqual(None, utils.git_version()) def test_git_version_3(self) -> None: self._version_str = b"git version 1.6.6" self.assertEqual((1, 6, 6, 0), utils.git_version()) def test_git_version_4(self) -> None: self._version_str = b"git version 1.7.0.2" self.assertEqual((1, 7, 0, 2), utils.git_version()) def test_git_version_extra(self) -> None: self._version_str = b"git version 1.7.0.3.295.gd8fa2" self.assertEqual((1, 7, 0, 3), utils.git_version()) def assertRequireSucceeds(self, required_version) -> None: try: utils.require_git_version(required_version) except SkipTest: self.fail() def assertRequireFails(self, required_version) -> None: self.assertRaises(SkipTest, utils.require_git_version, required_version) def test_require_git_version(self) -> None: try: self._version_str = b"git version 1.6.6" self.assertRequireSucceeds((1, 6, 6)) self.assertRequireSucceeds((1, 6, 6, 0)) self.assertRequireSucceeds((1, 6, 5)) self.assertRequireSucceeds((1, 6, 5, 99)) self.assertRequireFails((1, 7, 0)) self.assertRequireFails((1, 7, 0, 2)) self.assertRaises(ValueError, utils.require_git_version, (1, 6, 6, 0, 0)) self._version_str = b"git version 1.7.0.2" self.assertRequireSucceeds((1, 6, 6)) self.assertRequireSucceeds((1, 6, 6, 0)) self.assertRequireSucceeds((1, 7, 0)) self.assertRequireSucceeds((1, 7, 0, 2)) self.assertRequireFails((1, 7, 0, 3)) self.assertRequireFails((1, 7, 1)) except SkipTest as e: # This test is designed to catch all SkipTest exceptions. self.fail(f"Test unexpectedly skipped: {e}") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/compat/test_web.py0000644000175100002000000001633714731042555017464 0ustar00runnerdocker# test_web.py -- Compatibility tests for the git web server. # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Compatibility tests between Dulwich and the cgit HTTP server. warning: these tests should be fairly stable, but when writing/debugging new tests, deadlocks may freeze the test process such that it cannot be Ctrl-C'ed. On POSIX systems, you can kill the tests with Ctrl-Z, "kill %". """ import sys import threading from typing import NoReturn from wsgiref import simple_server from dulwich.server import DictBackend, ReceivePackHandler, UploadPackHandler from dulwich.web import ( HTTPGitApplication, WSGIRequestHandlerLogger, WSGIServerLogger, make_wsgi_chain, ) from .. import SkipTest, skipIf from .server_utils import NoSideBand64kReceivePackHandler, ServerTests from .utils import CompatTestCase @skipIf(sys.platform == "win32", "Broken on windows, with very long fail time.") class WebTests(ServerTests): """Base tests for web server tests. Contains utility and setUp/tearDown methods, but does non inherit from TestCase so tests are not automatically run. """ protocol = "http" def _start_server(self, repo): backend = DictBackend({"/": repo}) app = self._make_app(backend) dul_server = simple_server.make_server( "localhost", 0, app, server_class=WSGIServerLogger, handler_class=WSGIRequestHandlerLogger, ) self.addCleanup(dul_server.shutdown) self.addCleanup(dul_server.server_close) threading.Thread(target=dul_server.serve_forever).start() self._server = dul_server _, port = dul_server.socket.getsockname() return port @skipIf(sys.platform == "win32", "Broken on windows, with very long fail time.") class SmartWebTestCase(WebTests, CompatTestCase): """Test cases for smart HTTP server. This server test case does not use side-band-64k in git-receive-pack. """ min_git_version: tuple[int, ...] = (1, 6, 6) def _handlers(self): return {b"git-receive-pack": NoSideBand64kReceivePackHandler} def _check_app(self, app) -> None: receive_pack_handler_cls = app.handlers[b"git-receive-pack"] caps = receive_pack_handler_cls.capabilities() self.assertNotIn(b"side-band-64k", caps) def _make_app(self, backend): app = make_wsgi_chain(backend, handlers=self._handlers()) to_check = app # peel back layers until we're at the base application while not issubclass(to_check.__class__, HTTPGitApplication): to_check = to_check.app self._check_app(to_check) return app def patch_capabilities(handler, caps_removed): # Patch a handler's capabilities by specifying a list of them to be # removed, and return the original classmethod for restoration. original_capabilities = handler.capabilities filtered_capabilities = [ i for i in original_capabilities() if i not in caps_removed ] def capabilities(cls): return filtered_capabilities handler.capabilities = classmethod(capabilities) return original_capabilities @skipIf(sys.platform == "win32", "Broken on windows, with very long fail time.") class SmartWebSideBand64kTestCase(SmartWebTestCase): """Test cases for smart HTTP server with side-band-64k support.""" # side-band-64k in git-receive-pack was introduced in git 1.7.0.2 min_git_version = (1, 7, 0, 2) def setUp(self) -> None: self.o_uph_cap = patch_capabilities(UploadPackHandler, (b"no-done",)) self.o_rph_cap = patch_capabilities(ReceivePackHandler, (b"no-done",)) super().setUp() def tearDown(self) -> None: super().tearDown() UploadPackHandler.capabilities = self.o_uph_cap ReceivePackHandler.capabilities = self.o_rph_cap def _handlers(self) -> None: return None # default handlers include side-band-64k def _check_app(self, app) -> None: receive_pack_handler_cls = app.handlers[b"git-receive-pack"] caps = receive_pack_handler_cls.capabilities() self.assertIn(b"side-band-64k", caps) self.assertNotIn(b"no-done", caps) class SmartWebSideBand64kNoDoneTestCase(SmartWebTestCase): """Test cases for smart HTTP server with side-band-64k and no-done support. """ # no-done was introduced in git 1.7.4 min_git_version = (1, 7, 4) def _handlers(self) -> None: return None # default handlers include side-band-64k def _check_app(self, app) -> None: receive_pack_handler_cls = app.handlers[b"git-receive-pack"] caps = receive_pack_handler_cls.capabilities() self.assertIn(b"side-band-64k", caps) self.assertIn(b"no-done", caps) @skipIf(sys.platform == "win32", "Broken on windows, with very long fail time.") class DumbWebTestCase(WebTests, CompatTestCase): """Test cases for dumb HTTP server.""" def _make_app(self, backend): return make_wsgi_chain(backend, dumb=True) def test_push_to_dulwich(self) -> NoReturn: # Note: remove this if dulwich implements dumb web pushing. raise SkipTest("Dumb web pushing not supported.") def test_push_to_dulwich_remove_branch(self) -> NoReturn: # Note: remove this if dumb pushing is supported raise SkipTest("Dumb web pushing not supported.") def test_new_shallow_clone_from_dulwich(self) -> NoReturn: # Note: remove this if C git and dulwich implement dumb web shallow # clones. raise SkipTest("Dumb web shallow cloning not supported.") def test_shallow_clone_from_git_is_identical(self) -> NoReturn: # Note: remove this if C git and dulwich implement dumb web shallow # clones. raise SkipTest("Dumb web shallow cloning not supported.") def test_fetch_same_depth_into_shallow_clone_from_dulwich(self) -> NoReturn: # Note: remove this if C git and dulwich implement dumb web shallow # clones. raise SkipTest("Dumb web shallow cloning not supported.") def test_fetch_full_depth_into_shallow_clone_from_dulwich(self) -> NoReturn: # Note: remove this if C git and dulwich implement dumb web shallow # clones. raise SkipTest("Dumb web shallow cloning not supported.") def test_push_to_dulwich_issue_88_standard(self) -> NoReturn: raise SkipTest("Dumb web pushing not supported.") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/compat/utils.py0000644000175100002000000002216614731042555017005 0ustar00runnerdocker# utils.py -- Git compatibility utilities # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Utilities for interacting with cgit.""" import errno import functools import os import shutil import socket import stat import subprocess import sys import tempfile import time from dulwich.protocol import TCP_GIT_PORT from dulwich.repo import Repo from .. import SkipTest, TestCase _DEFAULT_GIT = "git" _VERSION_LEN = 4 _REPOS_DATA_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, "testdata", "repos") ) def git_version(git_path=_DEFAULT_GIT): """Attempt to determine the version of git currently installed. Args: git_path: Path to the git executable; defaults to the version in the system path. Returns: A tuple of ints of the form (major, minor, point, sub-point), or None if no git installation was found. """ try: output = run_git_or_fail(["--version"], git_path=git_path) except OSError: return None version_prefix = b"git version " if not output.startswith(version_prefix): return None parts = output[len(version_prefix) :].split(b".") nums = [] for part in parts: try: nums.append(int(part)) except ValueError: break while len(nums) < _VERSION_LEN: nums.append(0) return tuple(nums[:_VERSION_LEN]) def require_git_version(required_version, git_path=_DEFAULT_GIT) -> None: """Require git version >= version, or skip the calling test. Args: required_version: A tuple of ints of the form (major, minor, point, sub-point); omitted components default to 0. git_path: Path to the git executable; defaults to the version in the system path. Raises: ValueError: if the required version tuple has too many parts. SkipTest: if no suitable git version was found at the given path. """ found_version = git_version(git_path=git_path) if found_version is None: raise SkipTest(f"Test requires git >= {required_version}, but c git not found") if len(required_version) > _VERSION_LEN: raise ValueError( f"Invalid version tuple {required_version}, expected {_VERSION_LEN} parts" ) required_version = list(required_version) while len(found_version) < len(required_version): required_version.append(0) required_version = tuple(required_version) if found_version < required_version: required_version = ".".join(map(str, required_version)) found_version = ".".join(map(str, found_version)) raise SkipTest( f"Test requires git >= {required_version}, found {found_version}" ) def run_git( args, git_path=_DEFAULT_GIT, input=None, capture_stdout=False, capture_stderr=False, **popen_kwargs, ): """Run a git command. Input is piped from the input parameter and output is sent to the standard streams, unless capture_stdout is set. Args: args: A list of args to the git command. git_path: Path to to the git executable. input: Input data to be sent to stdin. capture_stdout: Whether to capture and return stdout. popen_kwargs: Additional kwargs for subprocess.Popen; stdin/stdout args are ignored. Returns: A tuple of (returncode, stdout contents, stderr contents). If capture_stdout is False, None will be returned as stdout contents. If capture_stderr is False, None will be returned as stderr contents. Raises: OSError: if the git executable was not found. """ env = popen_kwargs.pop("env", {}) env["LC_ALL"] = env["LANG"] = "C" env["PATH"] = os.getenv("PATH") args = [git_path, *args] popen_kwargs["stdin"] = subprocess.PIPE if capture_stdout: popen_kwargs["stdout"] = subprocess.PIPE else: popen_kwargs.pop("stdout", None) if capture_stderr: popen_kwargs["stderr"] = subprocess.PIPE else: popen_kwargs.pop("stderr", None) p = subprocess.Popen(args, env=env, **popen_kwargs) stdout, stderr = p.communicate(input=input) return (p.returncode, stdout, stderr) def run_git_or_fail(args, git_path=_DEFAULT_GIT, input=None, **popen_kwargs): """Run a git command, capture stdout/stderr, and fail if git fails.""" if "stderr" not in popen_kwargs: popen_kwargs["stderr"] = subprocess.STDOUT returncode, stdout, stderr = run_git( args, git_path=git_path, input=input, capture_stdout=True, capture_stderr=True, **popen_kwargs, ) if returncode != 0: raise AssertionError( f"git with args {args!r} failed with {returncode}: stdout={stdout!r} stderr={stderr!r}" ) return stdout def import_repo_to_dir(name): """Import a repo from a fast-export file in a temporary directory. These are used rather than binary repos for compat tests because they are more compact and human-editable, and we already depend on git. Args: name: The name of the repository export file, relative to dulwich/tests/data/repos. Returns: The path to the imported repository. """ temp_dir = tempfile.mkdtemp() export_path = os.path.join(_REPOS_DATA_DIR, name) temp_repo_dir = os.path.join(temp_dir, name) export_file = open(export_path, "rb") run_git_or_fail(["init", "--quiet", "--bare", temp_repo_dir]) run_git_or_fail(["fast-import"], input=export_file.read(), cwd=temp_repo_dir) export_file.close() return temp_repo_dir def check_for_daemon(limit=10, delay=0.1, timeout=0.1, port=TCP_GIT_PORT) -> bool: """Check for a running TCP daemon. Defaults to checking 10 times with a delay of 0.1 sec between tries. Args: limit: Number of attempts before deciding no daemon is running. delay: Delay between connection attempts. timeout: Socket timeout for connection attempts. port: Port on which we expect the daemon to appear. Returns: A boolean, true if a daemon is running on the specified port, false if not. """ for _ in range(limit): time.sleep(delay) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(delay) try: s.connect(("localhost", port)) return True except socket.timeout: pass except OSError as e: if getattr(e, "errno", False) and e.errno != errno.ECONNREFUSED: raise elif e.args[0] != errno.ECONNREFUSED: raise finally: s.close() return False class CompatTestCase(TestCase): """Test case that requires git for compatibility checks. Subclasses can change the git version required by overriding min_git_version. """ min_git_version: tuple[int, ...] = (1, 5, 0) def setUp(self) -> None: super().setUp() require_git_version(self.min_git_version) def assertObjectStoreEqual(self, store1, store2) -> None: self.assertEqual(sorted(set(store1)), sorted(set(store2))) def assertReposEqual(self, repo1, repo2) -> None: self.assertEqual(repo1.get_refs(), repo2.get_refs()) self.assertObjectStoreEqual(repo1.object_store, repo2.object_store) def assertReposNotEqual(self, repo1, repo2) -> None: refs1 = repo1.get_refs() objs1 = set(repo1.object_store) refs2 = repo2.get_refs() objs2 = set(repo2.object_store) self.assertFalse(refs1 == refs2 and objs1 == objs2) def import_repo(self, name): """Import a repo from a fast-export file in a temporary directory. Args: name: The name of the repository export file, relative to dulwich/tests/data/repos. Returns: An initialized Repo object that lives in a temporary directory. """ path = import_repo_to_dir(name) repo = Repo(path) def cleanup() -> None: repo.close() rmtree_ro(os.path.dirname(path.rstrip(os.sep))) self.addCleanup(cleanup) return repo if sys.platform == "win32": def remove_ro(action, name, exc) -> None: os.chmod(name, stat.S_IWRITE) os.remove(name) rmtree_ro = functools.partial(shutil.rmtree, onerror=remove_ro) else: rmtree_ro = shutil.rmtree ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1734624628.9924474 dulwich-0.22.7/tests/contrib/0000755000175100002000000000000014731042565015442 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/contrib/__init__.py0000644000175100002000000000242114731042555017551 0ustar00runnerdocker# __init__.py -- Contrib module for Dulwich # Copyright (C) 2014 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # def test_suite(): import unittest names = [ "paramiko_vendor", "release_robot", "swift", ] module_names = ["tests.contrib.test_" + name for name in names] loader = unittest.TestLoader() return loader.loadTestsFromNames(module_names) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/contrib/test_paramiko_vendor.py0000644000175100002000000002133014731042555022231 0ustar00runnerdocker# test_paramiko_vendor.py # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for paramiko_vendor.""" import socket import threading from io import StringIO from typing import Optional from unittest import skipIf from .. import TestCase try: import paramiko except ImportError: has_paramiko = False else: has_paramiko = True from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor class Server(paramiko.ServerInterface): """http://docs.paramiko.org/en/2.4/api/server.html.""" def __init__(self, commands, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.commands = commands def check_channel_exec_request(self, channel, command) -> bool: self.commands.append(command) return True def check_auth_password(self, username, password): if username == USER and password == PASSWORD: return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED def check_auth_publickey(self, username, key): pubkey = paramiko.RSAKey.from_private_key(StringIO(CLIENT_KEY)) if username == USER and key == pubkey: return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED def check_channel_request(self, kind, chanid): if kind == "session": return paramiko.OPEN_SUCCEEDED return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED def get_allowed_auths(self, username) -> str: return "password,publickey" USER = "testuser" PASSWORD = "test" SERVER_KEY = """\ -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAy/L1sSYAzxsMprtNXW4u/1jGXXkQmQ2xtmKVlR+RlIL3a1BH bzTpPlZyjltAAwzIP8XRh0iJFKz5y3zSQChhX47ZGN0NvQsVct8R+YwsUonwfAJ+ JN0KBKKvC8fPHlzqBr3gX+ZxqsFH934tQ6wdQPH5eQWtdM8L826lMsH1737uyTGk +mCSDjL3c6EzY83g7qhkJU2R4qbi6ne01FaWADzG8sOzXnHT+xpxtk8TTT8yCVUY MmBNsSoA/ka3iWz70ghB+6Xb0WpFJZXWq1oYovviPAfZGZSrxBZMxsWMye70SdLl TqsBEt0+miIcm9s0fvjWvQuhaHX6mZs5VO4r5QIDAQABAoIBAGYqeYWaYgFdrYLA hUrubUCg+g3NHdFuGL4iuIgRXl4lFUh+2KoOuWDu8Uf60iA1AQNhV0sLvQ/Mbv3O s4xMLisuZfaclctDiCUZNenqnDFkxEF7BjH1QJV94W5nU4wEQ3/JEmM4D2zYkfKb FJW33JeyH6TOgUvohDYYEU1R+J9V8qA243p+ui1uVtNI6Pb0TXJnG5y9Ny4vkSWH Fi0QoMPR1r9xJ4SEearGzA/crb4SmmDTKhGSoMsT3d5ATieLmwcS66xWz8w4oFGJ yzDq24s4Fp9ccNjMf/xR8XRiekJv835gjEqwF9IXyvgOaq6XJ1iCqGPFDKa25nui JnEstOkCgYEA/ZXk7aIanvdeJlTqpX578sJfCnrXLydzE8emk1b7+5mrzGxQ4/pM PBQs2f8glT3t0O0mRX9NoRqnwrid88/b+cY4NCOICFZeasX336/gYQxyVeRLJS6Z hnGEQqry8qS7PdKAyeHMNmZFrUh4EiHiObymEfQS+mkRUObn0cGBTw8CgYEAzeQU D2baec1DawjppKaRynAvWjp+9ry1lZx9unryKVRwjRjkEpw+b3/+hdaF1IvsVSce cNj+6W2guZ2tyHuPhZ64/4SJVyE2hKDSKD4xTb2nVjsMeN0bLD2UWXC9mwbx8nWa 2tmtUZ7a/okQb2cSdosJinRewLNqXIsBXamT1csCgYEA0cXb2RCOQQ6U3dTFPx4A 3vMXuA2iUKmrsqMoEx6T2LBow/Sefdkik1iFOdipVYwjXP+w9zC2QR1Rxez/DR/X 8ymceNUjxPHdrSoTQQG29dFcC92MpDeGXQcuyA+uZjcLhbrLOzYEvsOfxBb87NMG 14hNQPDNekTMREafYo9WrtUCgYAREK54+FVzcwf7fymedA/xb4r9N4v+d3W1iNsC 8d3Qfyc1CrMct8aVB07ZWQaOr2pPRIbJY7L9NhD0UZVt4I/sy1MaGqonhqE2LP4+ R6legDG2e/50ph7yc8gwAaA1kUXMiuLi8Nfkw/3yyvmJwklNegi4aRzRbA2Mzhi2 4q9WMQKBgQCb0JNyxHG4pvLWCF/j0Sm1FfvrpnqSv5678n1j4GX7Ka/TubOK1Y4K U+Oib7dKa/zQMWehVFNTayrsq6bKVZ6q7zG+IHiRLw4wjeAxREFH6WUjDrn9vl2l D48DKbBuBwuVOJWyq3qbfgJXojscgNQklrsPdXVhDwOF0dYxP89HnA== -----END RSA PRIVATE KEY-----""" CLIENT_KEY = """\ -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAxvREKSElPOm/0z/nPO+j5rk2tjdgGcGc7We1QZ6TRXYLu7nN GeEFIL4p8N1i6dmB+Eydt7xqCU79MWD6Yy4prFe1+/K1wCDUxIbFMxqQcX5zjJzd i8j8PbcaUlVhP/OkjtkSxrXaGDO1BzfdV4iEBtTV/2l3zmLKJlt3jnOHLczP24CB DTQKp3rKshbRefzot9Y+wnaK692RsYgsyo9YEP0GyWKG9topCHk13r46J6vGLeuj ryUKqmbLJkzbJbIcEqwTDo5iHaCVqaMr5Hrb8BdMucSseqZQJsXSd+9tdRcIblUQ 38kZjmFMm4SFbruJcpZCNM2wNSZPIRX+3eiwNwIDAQABAoIBAHSacOBSJsr+jIi5 KUOTh9IPtzswVUiDKwARCjB9Sf8p4lKR4N1L/n9kNJyQhApeikgGT2GCMftmqgoo tlculQoHFgemBlOmak0MV8NNzF5YKEy/GzF0CDH7gJfEpoyetVFrdA+2QS5yD6U9 XqKQxiBi2VEqdScmyyeT8AwzNYTnPeH/DOEcnbdRjqiy/CD79F49CQ1lX1Fuqm0K I7BivBH1xo/rVnUP4F+IzocDqoga+Pjdj0LTXIgJlHQDSbhsQqWujWQDDuKb+MAw sNK4Zf8ErV3j1PyA7f/M5LLq6zgstkW4qikDHo4SpZX8kFOO8tjqb7kujj7XqeaB CxqrOTECgYEA73uWkrohcmDJ4KqbuL3tbExSCOUiaIV+sT1eGPNi7GCmXD4eW5Z4 75v2IHymW83lORSu/DrQ6sKr1nkuRpqr2iBzRmQpl/H+wahIhBXlnJ25uUjDsuPO 1Pq2LcmyD+jTxVnmbSe/q7O09gZQw3I6H4+BMHmpbf8tC97lqimzpJ0CgYEA1K0W ZL70Xtn9quyHvbtae/BW07NZnxvUg4UaVIAL9Zu34JyplJzyzbIjrmlDbv6aRogH /KtuG9tfbf55K/jjqNORiuRtzt1hUN1ye4dyW7tHx2/7lXdlqtyK40rQl8P0kqf8 zaS6BqjnobgSdSpg32rWoL/pcBHPdJCJEgQ8zeMCgYEA0/PK8TOhNIzrP1dgGSKn hkkJ9etuB5nW5mEM7gJDFDf6JPupfJ/xiwe6z0fjKK9S57EhqgUYMB55XYnE5iIw ZQ6BV9SAZ4V7VsRs4dJLdNC3tn/rDGHJBgCaym2PlbsX6rvFT+h1IC8dwv0V79Ui Ehq9WTzkMoE8yhvNokvkPZUCgYEAgBAFxv5xGdh79ftdtXLmhnDvZ6S8l6Fjcxqo Ay/jg66Tp43OU226iv/0mmZKM8Dd1xC8dnon4GBVc19jSYYiWBulrRPlx0Xo/o+K CzZBN1lrXH1i6dqufpc0jq8TMf/N+q1q/c1uMupsKCY1/xVYpc+ok71b7J7c49zQ nOeuUW8CgYA9Infooy65FTgbzca0c9kbCUBmcAPQ2ItH3JcPKWPQTDuV62HcT00o fZdIV47Nez1W5Clk191RMy8TXuqI54kocciUWpThc6j44hz49oUueb8U4bLcEHzA WxtWBWHwxfSmqgTXilEA3ALJp0kNolLnEttnhENwJpZHlqtes0ZA4w== -----END RSA PRIVATE KEY-----""" @skipIf(not has_paramiko, "paramiko is not installed") class ParamikoSSHVendorTests(TestCase): def setUp(self) -> None: import paramiko.transport # re-enable server functionality for tests if hasattr(paramiko.transport, "SERVER_DISABLED_BY_GENTOO"): paramiko.transport.SERVER_DISABLED_BY_GENTOO = False self.commands = [] socket.setdefaulttimeout(10) self.addCleanup(socket.setdefaulttimeout, None) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind(("127.0.0.1", 0)) self.socket.listen(5) self.addCleanup(self.socket.close) self.port = self.socket.getsockname()[1] self.thread = threading.Thread(target=self._run) self.thread.start() def tearDown(self) -> None: self.thread.join() def _run(self) -> Optional[bool]: try: conn, addr = self.socket.accept() except OSError: return False self.transport = paramiko.Transport(conn) self.addCleanup(self.transport.close) host_key = paramiko.RSAKey.from_private_key(StringIO(SERVER_KEY)) self.transport.add_server_key(host_key) server = Server(self.commands) self.transport.start_server(server=server) def test_run_command_password(self) -> None: vendor = ParamikoSSHVendor( allow_agent=False, look_for_keys=False, ) vendor.run_command( "127.0.0.1", "test_run_command_password", username=USER, port=self.port, password=PASSWORD, ) self.assertIn(b"test_run_command_password", self.commands) def test_run_command_with_privkey(self) -> None: key = paramiko.RSAKey.from_private_key(StringIO(CLIENT_KEY)) vendor = ParamikoSSHVendor( allow_agent=False, look_for_keys=False, ) vendor.run_command( "127.0.0.1", "test_run_command_with_privkey", username=USER, port=self.port, pkey=key, ) self.assertIn(b"test_run_command_with_privkey", self.commands) def test_run_command_data_transfer(self) -> None: vendor = ParamikoSSHVendor( allow_agent=False, look_for_keys=False, ) con = vendor.run_command( "127.0.0.1", "test_run_command_data_transfer", username=USER, port=self.port, password=PASSWORD, ) self.assertIn(b"test_run_command_data_transfer", self.commands) channel = self.transport.accept(5) channel.send(b"stdout\n") channel.send_stderr(b"stderr\n") channel.close() # Fixme: it's return false # self.assertTrue(con.can_read()) self.assertEqual(b"stdout\n", con.read(4096)) # Fixme: it's return empty string # self.assertEqual(b'stderr\n', con.read_stderr(4096)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/contrib/test_release_robot.py0000644000175100002000000001205214731042555021677 0ustar00runnerdocker# release_robot.py # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for release_robot.""" import datetime import os import re import shutil import tempfile import time import unittest from typing import ClassVar, Optional from dulwich.contrib import release_robot from dulwich.repo import Repo from dulwich.tests.utils import make_commit, make_tag BASEDIR = os.path.abspath(os.path.dirname(__file__)) # this directory def gmtime_to_datetime(gmt): return datetime.datetime(*time.gmtime(gmt)[:6]) class TagPatternTests(unittest.TestCase): """test tag patterns.""" def test_tag_pattern(self) -> None: """Test tag patterns.""" test_cases = { "0.3": "0.3", "v0.3": "0.3", "release0.3": "0.3", "Release-0.3": "0.3", "v0.3rc1": "0.3rc1", "v0.3-rc1": "0.3-rc1", "v0.3-rc.1": "0.3-rc.1", "version 0.3": "0.3", "version_0.3_rc_1": "0.3_rc_1", "v1": "1", "0.3rc1": "0.3rc1", } for testcase, version in test_cases.items(): matches = re.match(release_robot.PATTERN, testcase) self.assertEqual(matches.group(1), version) class GetRecentTagsTest(unittest.TestCase): """test get recent tags.""" # Git repo for dulwich project test_repo = os.path.join(BASEDIR, "dulwich_test_repo.zip") committer = b"Mark Mikofski " test_tags: ClassVar[list[bytes]] = [b"v0.1a", b"v0.1"] tag_test_data: ClassVar[ dict[bytes, tuple[int, bytes, Optional[tuple[int, bytes]]]] ] = { test_tags[0]: (1484788003, b"3" * 40, None), test_tags[1]: (1484788314, b"1" * 40, (1484788401, b"2" * 40)), } @classmethod def setUpClass(cls) -> None: cls.projdir = tempfile.mkdtemp() # temporary project directory cls.repo = Repo.init(cls.projdir) # test repo obj_store = cls.repo.object_store # test repo object store # commit 1 ('2017-01-19T01:06:43') cls.c1 = make_commit( id=cls.tag_test_data[cls.test_tags[0]][1], commit_time=cls.tag_test_data[cls.test_tags[0]][0], message=b"unannotated tag", author=cls.committer, ) obj_store.add_object(cls.c1) # tag 1: unannotated cls.t1 = cls.test_tags[0] cls.repo[b"refs/tags/" + cls.t1] = cls.c1.id # add unannotated tag # commit 2 ('2017-01-19T01:11:54') cls.c2 = make_commit( id=cls.tag_test_data[cls.test_tags[1]][1], commit_time=cls.tag_test_data[cls.test_tags[1]][0], message=b"annotated tag", parents=[cls.c1.id], author=cls.committer, ) obj_store.add_object(cls.c2) # tag 2: annotated ('2017-01-19T01:13:21') cls.t2 = make_tag( cls.c2, id=cls.tag_test_data[cls.test_tags[1]][2][1], name=cls.test_tags[1], tag_time=cls.tag_test_data[cls.test_tags[1]][2][0], ) obj_store.add_object(cls.t2) cls.repo[b"refs/heads/master"] = cls.c2.id cls.repo[b"refs/tags/" + cls.t2.name] = cls.t2.id # add annotated tag @classmethod def tearDownClass(cls) -> None: cls.repo.close() shutil.rmtree(cls.projdir) def test_get_recent_tags(self) -> None: """Test get recent tags.""" tags = release_robot.get_recent_tags(self.projdir) # get test tags for tag, metadata in tags: tag = tag.encode("utf-8") test_data = self.tag_test_data[tag] # test data tag # test commit date, id and author name self.assertEqual(metadata[0], gmtime_to_datetime(test_data[0])) self.assertEqual(metadata[1].encode("utf-8"), test_data[1]) self.assertEqual(metadata[2].encode("utf-8"), self.committer) # skip unannotated tags tag_obj = test_data[2] if not tag_obj: continue # tag date, id and name self.assertEqual(metadata[3][0], gmtime_to_datetime(tag_obj[0])) self.assertEqual(metadata[3][1].encode("utf-8"), tag_obj[1]) self.assertEqual(metadata[3][2].encode("utf-8"), tag) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/contrib/test_swift.py0000644000175100002000000004064114731042555020213 0ustar00runnerdocker# test_swift.py -- Unittests for the Swift backend. # Copyright (C) 2013 eNovance SAS # # Author: Fabien Boucher # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for dulwich.contrib.swift.""" import json import posixpath from io import BytesIO, StringIO from time import time from unittest import skipIf from dulwich.objects import Blob, Commit, Tag, Tree, parse_timezone from .. import TestCase from ..test_object_store import ObjectStoreTests missing_libs = [] try: import gevent # noqa: F401 except ModuleNotFoundError: missing_libs.append("gevent") try: import geventhttpclient # noqa: F401 except ModuleNotFoundError: missing_libs.append("geventhttpclient") try: from unittest.mock import patch except ModuleNotFoundError: missing_libs.append("mock") skipmsg = f"Required libraries are not installed ({missing_libs!r})" if not missing_libs: from dulwich.contrib import swift config_file = """[swift] auth_url = http://127.0.0.1:8080/auth/%(version_str)s auth_ver = %(version_int)s username = test;tester password = testing region_name = %(region_name)s endpoint_type = %(endpoint_type)s concurrency = %(concurrency)s chunk_length = %(chunk_length)s cache_length = %(cache_length)s http_pool_length = %(http_pool_length)s http_timeout = %(http_timeout)s """ def_config_file = { "version_str": "v1.0", "version_int": 1, "concurrency": 1, "chunk_length": 12228, "cache_length": 1, "region_name": "test", "endpoint_type": "internalURL", "http_pool_length": 1, "http_timeout": 1, } def create_swift_connector(store={}): return lambda root, conf: FakeSwiftConnector(root, conf=conf, store=store) class Response: def __init__(self, headers={}, status=200, content=None) -> None: self.headers = headers self.status_code = status self.content = content def __getitem__(self, key): return self.headers[key] def items(self): return self.headers.items() def read(self): return self.content def fake_auth_request_v1(*args, **kwargs): ret = Response( { "X-Storage-Url": "http://127.0.0.1:8080/v1.0/AUTH_fakeuser", "X-Auth-Token": "12" * 10, }, 200, ) return ret def fake_auth_request_v1_error(*args, **kwargs): ret = Response({}, 401) return ret def fake_auth_request_v2(*args, **kwargs): s_url = "http://127.0.0.1:8080/v1.0/AUTH_fakeuser" resp = { "access": { "token": {"id": "12" * 10}, "serviceCatalog": [ { "type": "object-store", "endpoints": [ { "region": "test", "internalURL": s_url, }, ], }, ], } } ret = Response(status=200, content=json.dumps(resp)) return ret def create_commit(data, marker=b"Default", blob=None): if not blob: blob = Blob.from_string(b"The blob content " + marker) tree = Tree() tree.add(b"thefile_" + marker, 0o100644, blob.id) cmt = Commit() if data: assert isinstance(data[-1], Commit) cmt.parents = [data[-1].id] cmt.tree = tree.id author = b"John Doe " + marker + b" " cmt.author = cmt.committer = author tz = parse_timezone(b"-0200")[0] cmt.commit_time = cmt.author_time = int(time()) cmt.commit_timezone = cmt.author_timezone = tz cmt.encoding = b"UTF-8" cmt.message = b"The commit message " + marker tag = Tag() tag.tagger = b"john@doe.net" tag.message = b"Annotated tag" tag.tag_timezone = parse_timezone(b"-0200")[0] tag.tag_time = cmt.author_time tag.object = (Commit, cmt.id) tag.name = b"v_" + marker + b"_0.1" return blob, tree, tag, cmt def create_commits(length=1, marker=b"Default"): data = [] for i in range(length): _marker = (f"{marker}_{i}").encode() blob, tree, tag, cmt = create_commit(data, _marker) data.extend([blob, tree, tag, cmt]) return data @skipIf(missing_libs, skipmsg) class FakeSwiftConnector: def __init__(self, root, conf, store=None) -> None: if store: self.store = store else: self.store = {} self.conf = conf self.root = root self.concurrency = 1 self.chunk_length = 12228 self.cache_length = 1 def put_object(self, name, content) -> None: name = posixpath.join(self.root, name) if hasattr(content, "seek"): content.seek(0) content = content.read() self.store[name] = content def get_object(self, name, range=None): name = posixpath.join(self.root, name) if not range: try: return BytesIO(self.store[name]) except KeyError: return None else: left, right = range.split("-") try: if not left: right = -int(right) return self.store[name][right:] else: return self.store[name][int(left) : int(right)] except KeyError: return None def get_container_objects(self): return [{"name": k.replace(self.root + "/", "")} for k in self.store] def create_root(self) -> None: if self.root in self.store.keys(): pass else: self.store[self.root] = "" def get_object_stat(self, name): name = posixpath.join(self.root, name) if name not in self.store: return None return {"content-length": len(self.store[name])} @skipIf(missing_libs, skipmsg) class TestSwiftRepo(TestCase): def setUp(self) -> None: super().setUp() self.conf = swift.load_conf(file=StringIO(config_file % def_config_file)) def test_init(self) -> None: store = {"fakerepo/objects/pack": ""} with patch( "dulwich.contrib.swift.SwiftConnector", new_callable=create_swift_connector, store=store, ): swift.SwiftRepo("fakerepo", conf=self.conf) def test_init_no_data(self) -> None: with patch( "dulwich.contrib.swift.SwiftConnector", new_callable=create_swift_connector, ): self.assertRaises(Exception, swift.SwiftRepo, "fakerepo", self.conf) def test_init_bad_data(self) -> None: store = {"fakerepo/.git/objects/pack": ""} with patch( "dulwich.contrib.swift.SwiftConnector", new_callable=create_swift_connector, store=store, ): self.assertRaises(Exception, swift.SwiftRepo, "fakerepo", self.conf) def test_put_named_file(self) -> None: store = {"fakerepo/objects/pack": ""} with patch( "dulwich.contrib.swift.SwiftConnector", new_callable=create_swift_connector, store=store, ): repo = swift.SwiftRepo("fakerepo", conf=self.conf) desc = b"Fake repo" repo._put_named_file("description", desc) self.assertEqual(repo.scon.store["fakerepo/description"], desc) def test_init_bare(self) -> None: fsc = FakeSwiftConnector("fakeroot", conf=self.conf) with patch( "dulwich.contrib.swift.SwiftConnector", new_callable=create_swift_connector, store=fsc.store, ): swift.SwiftRepo.init_bare(fsc, conf=self.conf) self.assertIn("fakeroot/objects/pack", fsc.store) self.assertIn("fakeroot/info/refs", fsc.store) self.assertIn("fakeroot/description", fsc.store) @skipIf(missing_libs, skipmsg) class TestSwiftInfoRefsContainer(TestCase): def setUp(self) -> None: super().setUp() content = ( b"22effb216e3a82f97da599b8885a6cadb488b4c5\trefs/heads/master\n" b"cca703b0e1399008b53a1a236d6b4584737649e4\trefs/heads/dev" ) self.store = {"fakerepo/info/refs": content} self.conf = swift.load_conf(file=StringIO(config_file % def_config_file)) self.fsc = FakeSwiftConnector("fakerepo", conf=self.conf) self.object_store = {} def test_init(self) -> None: """info/refs does not exists.""" irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store) self.assertEqual(len(irc._refs), 0) self.fsc.store = self.store irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store) self.assertIn(b"refs/heads/dev", irc.allkeys()) self.assertIn(b"refs/heads/master", irc.allkeys()) def test_set_if_equals(self) -> None: self.fsc.store = self.store irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store) irc.set_if_equals( b"refs/heads/dev", b"cca703b0e1399008b53a1a236d6b4584737649e4", b"1" * 40, ) self.assertEqual(irc[b"refs/heads/dev"], b"1" * 40) def test_remove_if_equals(self) -> None: self.fsc.store = self.store irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store) irc.remove_if_equals( b"refs/heads/dev", b"cca703b0e1399008b53a1a236d6b4584737649e4" ) self.assertNotIn(b"refs/heads/dev", irc.allkeys()) @skipIf(missing_libs, skipmsg) class TestSwiftConnector(TestCase): def setUp(self) -> None: super().setUp() self.conf = swift.load_conf(file=StringIO(config_file % def_config_file)) with patch("geventhttpclient.HTTPClient.request", fake_auth_request_v1): self.conn = swift.SwiftConnector("fakerepo", conf=self.conf) def test_init_connector(self) -> None: self.assertEqual(self.conn.auth_ver, "1") self.assertEqual(self.conn.auth_url, "http://127.0.0.1:8080/auth/v1.0") self.assertEqual(self.conn.user, "test:tester") self.assertEqual(self.conn.password, "testing") self.assertEqual(self.conn.root, "fakerepo") self.assertEqual( self.conn.storage_url, "http://127.0.0.1:8080/v1.0/AUTH_fakeuser" ) self.assertEqual(self.conn.token, "12" * 10) self.assertEqual(self.conn.http_timeout, 1) self.assertEqual(self.conn.http_pool_length, 1) self.assertEqual(self.conn.concurrency, 1) self.conf.set("swift", "auth_ver", "2") self.conf.set("swift", "auth_url", "http://127.0.0.1:8080/auth/v2.0") with patch("geventhttpclient.HTTPClient.request", fake_auth_request_v2): conn = swift.SwiftConnector("fakerepo", conf=self.conf) self.assertEqual(conn.user, "tester") self.assertEqual(conn.tenant, "test") self.conf.set("swift", "auth_ver", "1") self.conf.set("swift", "auth_url", "http://127.0.0.1:8080/auth/v1.0") with patch("geventhttpclient.HTTPClient.request", fake_auth_request_v1_error): self.assertRaises( swift.SwiftException, lambda: swift.SwiftConnector("fakerepo", conf=self.conf), ) def test_root_exists(self) -> None: with patch("geventhttpclient.HTTPClient.request", lambda *args: Response()): self.assertEqual(self.conn.test_root_exists(), True) def test_root_not_exists(self) -> None: with patch( "geventhttpclient.HTTPClient.request", lambda *args: Response(status=404), ): self.assertEqual(self.conn.test_root_exists(), None) def test_create_root(self) -> None: with patch( "dulwich.contrib.swift.SwiftConnector.test_root_exists", lambda *args: None, ): with patch("geventhttpclient.HTTPClient.request", lambda *args: Response()): self.assertEqual(self.conn.create_root(), None) def test_create_root_fails(self) -> None: with patch( "dulwich.contrib.swift.SwiftConnector.test_root_exists", lambda *args: None, ): with patch( "geventhttpclient.HTTPClient.request", lambda *args: Response(status=404), ): self.assertRaises(swift.SwiftException, self.conn.create_root) def test_get_container_objects(self) -> None: with patch( "geventhttpclient.HTTPClient.request", lambda *args: Response(content=json.dumps(({"name": "a"}, {"name": "b"}))), ): self.assertEqual(len(self.conn.get_container_objects()), 2) def test_get_container_objects_fails(self) -> None: with patch( "geventhttpclient.HTTPClient.request", lambda *args: Response(status=404), ): self.assertEqual(self.conn.get_container_objects(), None) def test_get_object_stat(self) -> None: with patch( "geventhttpclient.HTTPClient.request", lambda *args: Response(headers={"content-length": "10"}), ): self.assertEqual(self.conn.get_object_stat("a")["content-length"], "10") def test_get_object_stat_fails(self) -> None: with patch( "geventhttpclient.HTTPClient.request", lambda *args: Response(status=404), ): self.assertEqual(self.conn.get_object_stat("a"), None) def test_put_object(self) -> None: with patch( "geventhttpclient.HTTPClient.request", lambda *args, **kwargs: Response(), ): self.assertEqual(self.conn.put_object("a", BytesIO(b"content")), None) def test_put_object_fails(self) -> None: with patch( "geventhttpclient.HTTPClient.request", lambda *args, **kwargs: Response(status=400), ): self.assertRaises( swift.SwiftException, lambda: self.conn.put_object("a", BytesIO(b"content")), ) def test_get_object(self) -> None: with patch( "geventhttpclient.HTTPClient.request", lambda *args, **kwargs: Response(content=b"content"), ): self.assertEqual(self.conn.get_object("a").read(), b"content") with patch( "geventhttpclient.HTTPClient.request", lambda *args, **kwargs: Response(content=b"content"), ): self.assertEqual(self.conn.get_object("a", range="0-6"), b"content") def test_get_object_fails(self) -> None: with patch( "geventhttpclient.HTTPClient.request", lambda *args, **kwargs: Response(status=404), ): self.assertEqual(self.conn.get_object("a"), None) def test_del_object(self) -> None: with patch("geventhttpclient.HTTPClient.request", lambda *args: Response()): self.assertEqual(self.conn.del_object("a"), None) def test_del_root(self) -> None: with patch( "dulwich.contrib.swift.SwiftConnector.del_object", lambda *args: None, ): with patch( "dulwich.contrib.swift.SwiftConnector." "get_container_objects", lambda *args: ({"name": "a"}, {"name": "b"}), ): with patch( "geventhttpclient.HTTPClient.request", lambda *args: Response(), ): self.assertEqual(self.conn.del_root(), None) @skipIf(missing_libs, skipmsg) class SwiftObjectStoreTests(ObjectStoreTests, TestCase): def setUp(self) -> None: TestCase.setUp(self) conf = swift.load_conf(file=StringIO(config_file % def_config_file)) fsc = FakeSwiftConnector("fakerepo", conf=conf) self.store = swift.SwiftObjectStore(fsc) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/contrib/test_swift_smoke.py0000644000175100002000000003015314731042555021406 0ustar00runnerdocker# test_smoke.py -- Functional tests for the Swift backend. # Copyright (C) 2013 eNovance SAS # # Author: Fabien Boucher # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Start functional tests. A Swift installation must be available before starting those tests. The account and authentication method used during this functional tests must be changed in the configuration file passed as environment variable. The container used to create a fake repository is defined in cls.fakerepo and will be deleted after the tests. DULWICH_SWIFT_CFG=/tmp/conf.cfg PYTHONPATH=. python -m unittest \ dulwich.tests_swift.test_smoke """ import os import shutil import tempfile import unittest import gevent from gevent import monkey monkey.patch_all() from dulwich import client, index, objects, repo, server # noqa: E402 from dulwich.contrib import swift # noqa: E402 class DulwichServer: """Start the TCPGitServer with Swift backend.""" def __init__(self, backend, port) -> None: self.port = port self.backend = backend def run(self) -> None: self.server = server.TCPGitServer(self.backend, "localhost", port=self.port) self.job = gevent.spawn(self.server.serve_forever) def stop(self) -> None: self.server.shutdown() gevent.joinall((self.job,)) class SwiftSystemBackend(server.Backend): def open_repository(self, path): return swift.SwiftRepo(path, conf=swift.load_conf()) class SwiftRepoSmokeTest(unittest.TestCase): @classmethod def setUpClass(cls) -> None: cls.backend = SwiftSystemBackend() cls.port = 9148 cls.server_address = "localhost" cls.fakerepo = "fakerepo" cls.th_server = DulwichServer(cls.backend, cls.port) cls.th_server.run() cls.conf = swift.load_conf() @classmethod def tearDownClass(cls) -> None: cls.th_server.stop() def setUp(self) -> None: self.scon = swift.SwiftConnector(self.fakerepo, self.conf) if self.scon.test_root_exists(): try: self.scon.del_root() except swift.SwiftException: pass self.temp_d = tempfile.mkdtemp() if os.path.isdir(self.temp_d): shutil.rmtree(self.temp_d) def tearDown(self) -> None: if self.scon.test_root_exists(): try: self.scon.del_root() except swift.SwiftException: pass if os.path.isdir(self.temp_d): shutil.rmtree(self.temp_d) def test_init_bare(self) -> None: swift.SwiftRepo.init_bare(self.scon, self.conf) self.assertTrue(self.scon.test_root_exists()) obj = self.scon.get_container_objects() filtered = [ o for o in obj if o["name"] == "info/refs" or o["name"] == "objects/pack" ] self.assertEqual(len(filtered), 2) def test_clone_bare(self) -> None: local_repo = repo.Repo.init(self.temp_d, mkdir=True) swift.SwiftRepo.init_bare(self.scon, self.conf) tcp_client = client.TCPGitClient(self.server_address, port=self.port) remote_refs = tcp_client.fetch(self.fakerepo, local_repo) # The remote repo is empty (no refs retrieved) self.assertEqual(remote_refs, None) def test_push_commit(self) -> None: def determine_wants(*args, **kwargs): return {"refs/heads/master": local_repo.refs["HEAD"]} local_repo = repo.Repo.init(self.temp_d, mkdir=True) # Nothing in the staging area local_repo.do_commit("Test commit", "fbo@localhost") sha = local_repo.refs.read_loose_ref("refs/heads/master") swift.SwiftRepo.init_bare(self.scon, self.conf) tcp_client = client.TCPGitClient(self.server_address, port=self.port) tcp_client.send_pack( self.fakerepo, determine_wants, local_repo.generate_pack_data ) swift_repo = swift.SwiftRepo("fakerepo", self.conf) remote_sha = swift_repo.refs.read_loose_ref("refs/heads/master") self.assertEqual(sha, remote_sha) def test_push_branch(self) -> None: def determine_wants(*args, **kwargs): return {"refs/heads/mybranch": local_repo.refs["refs/heads/mybranch"]} local_repo = repo.Repo.init(self.temp_d, mkdir=True) # Nothing in the staging area local_repo.do_commit("Test commit", "fbo@localhost", ref="refs/heads/mybranch") sha = local_repo.refs.read_loose_ref("refs/heads/mybranch") swift.SwiftRepo.init_bare(self.scon, self.conf) tcp_client = client.TCPGitClient(self.server_address, port=self.port) tcp_client.send_pack( "/fakerepo", determine_wants, local_repo.generate_pack_data ) swift_repo = swift.SwiftRepo(self.fakerepo, self.conf) remote_sha = swift_repo.refs.read_loose_ref("refs/heads/mybranch") self.assertEqual(sha, remote_sha) def test_push_multiple_branch(self) -> None: def determine_wants(*args, **kwargs): return { "refs/heads/mybranch": local_repo.refs["refs/heads/mybranch"], "refs/heads/master": local_repo.refs["refs/heads/master"], "refs/heads/pullr-108": local_repo.refs["refs/heads/pullr-108"], } local_repo = repo.Repo.init(self.temp_d, mkdir=True) # Nothing in the staging area local_shas = {} remote_shas = {} for branch in ("master", "mybranch", "pullr-108"): local_shas[branch] = local_repo.do_commit( f"Test commit {branch}", "fbo@localhost", ref=f"refs/heads/{branch}", ) swift.SwiftRepo.init_bare(self.scon, self.conf) tcp_client = client.TCPGitClient(self.server_address, port=self.port) tcp_client.send_pack( self.fakerepo, determine_wants, local_repo.generate_pack_data ) swift_repo = swift.SwiftRepo("fakerepo", self.conf) for branch in ("master", "mybranch", "pullr-108"): remote_shas[branch] = swift_repo.refs.read_loose_ref(f"refs/heads/{branch}") self.assertDictEqual(local_shas, remote_shas) def test_push_data_branch(self) -> None: def determine_wants(*args, **kwargs): return {"refs/heads/master": local_repo.refs["HEAD"]} local_repo = repo.Repo.init(self.temp_d, mkdir=True) os.mkdir(os.path.join(self.temp_d, "dir")) files = ("testfile", "testfile2", "dir/testfile3") i = 0 for f in files: open(os.path.join(self.temp_d, f), "w").write(f"DATA {i}") i += 1 local_repo.stage(files) local_repo.do_commit("Test commit", "fbo@localhost", ref="refs/heads/master") swift.SwiftRepo.init_bare(self.scon, self.conf) tcp_client = client.TCPGitClient(self.server_address, port=self.port) tcp_client.send_pack( self.fakerepo, determine_wants, local_repo.generate_pack_data ) swift_repo = swift.SwiftRepo("fakerepo", self.conf) commit_sha = swift_repo.refs.read_loose_ref("refs/heads/master") otype, data = swift_repo.object_store.get_raw(commit_sha) commit = objects.ShaFile.from_raw_string(otype, data) otype, data = swift_repo.object_store.get_raw(commit._tree) tree = objects.ShaFile.from_raw_string(otype, data) objs = tree.items() objs_ = [] for tree_entry in objs: objs_.append(swift_repo.object_store.get_raw(tree_entry.sha)) # Blob self.assertEqual(objs_[1][1], "DATA 0") self.assertEqual(objs_[2][1], "DATA 1") # Tree self.assertEqual(objs_[0][0], 2) def test_clone_then_push_data(self) -> None: self.test_push_data_branch() shutil.rmtree(self.temp_d) local_repo = repo.Repo.init(self.temp_d, mkdir=True) tcp_client = client.TCPGitClient(self.server_address, port=self.port) remote_refs = tcp_client.fetch(self.fakerepo, local_repo) files = ( os.path.join(self.temp_d, "testfile"), os.path.join(self.temp_d, "testfile2"), ) local_repo["HEAD"] = remote_refs["refs/heads/master"] indexfile = local_repo.index_path() tree = local_repo["HEAD"].tree index.build_index_from_tree( local_repo.path, indexfile, local_repo.object_store, tree ) for f in files: self.assertEqual(os.path.isfile(f), True) def determine_wants(*args, **kwargs): return {"refs/heads/master": local_repo.refs["HEAD"]} os.mkdir(os.path.join(self.temp_d, "test")) files = ("testfile11", "testfile22", "test/testfile33") i = 0 for f in files: open(os.path.join(self.temp_d, f), "w").write(f"DATA {i}") i += 1 local_repo.stage(files) local_repo.do_commit("Test commit", "fbo@localhost", ref="refs/heads/master") tcp_client.send_pack( "/fakerepo", determine_wants, local_repo.generate_pack_data ) def test_push_remove_branch(self) -> None: def determine_wants(*args, **kwargs): return { "refs/heads/pullr-108": objects.ZERO_SHA, "refs/heads/master": local_repo.refs["refs/heads/master"], "refs/heads/mybranch": local_repo.refs["refs/heads/mybranch"], } self.test_push_multiple_branch() local_repo = repo.Repo(self.temp_d) tcp_client = client.TCPGitClient(self.server_address, port=self.port) tcp_client.send_pack( self.fakerepo, determine_wants, local_repo.generate_pack_data ) swift_repo = swift.SwiftRepo("fakerepo", self.conf) self.assertNotIn("refs/heads/pullr-108", swift_repo.refs.allkeys()) def test_push_annotated_tag(self) -> None: def determine_wants(*args, **kwargs): return { "refs/heads/master": local_repo.refs["HEAD"], "refs/tags/v1.0": local_repo.refs["refs/tags/v1.0"], } local_repo = repo.Repo.init(self.temp_d, mkdir=True) # Nothing in the staging area sha = local_repo.do_commit("Test commit", "fbo@localhost") otype, data = local_repo.object_store.get_raw(sha) commit = objects.ShaFile.from_raw_string(otype, data) tag = objects.Tag() tag.tagger = "fbo@localhost" tag.message = "Annotated tag" tag.tag_timezone = objects.parse_timezone("-0200")[0] tag.tag_time = commit.author_time tag.object = (objects.Commit, commit.id) tag.name = "v0.1" local_repo.object_store.add_object(tag) local_repo.refs["refs/tags/v1.0"] = tag.id swift.SwiftRepo.init_bare(self.scon, self.conf) tcp_client = client.TCPGitClient(self.server_address, port=self.port) tcp_client.send_pack( self.fakerepo, determine_wants, local_repo.generate_pack_data ) swift_repo = swift.SwiftRepo(self.fakerepo, self.conf) tag_sha = swift_repo.refs.read_loose_ref("refs/tags/v1.0") otype, data = swift_repo.object_store.get_raw(tag_sha) rtag = objects.ShaFile.from_raw_string(otype, data) self.assertEqual(rtag.object[1], commit.id) self.assertEqual(rtag.id, tag.id) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_archive.py0000644000175100002000000000751014731042555017036 0ustar00runnerdocker# test_archive.py -- tests for archive # Copyright (C) 2015 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for archive support.""" import struct import tarfile from io import BytesIO from unittest import skipUnless from dulwich.archive import tar_stream from dulwich.object_store import MemoryObjectStore from dulwich.objects import Blob, Tree from dulwich.tests.utils import build_commit_graph from . import TestCase try: from unittest.mock import patch except ImportError: patch = None # type: ignore class ArchiveTests(TestCase): def test_empty(self) -> None: store = MemoryObjectStore() c1, c2, c3 = build_commit_graph(store, [[1], [2, 1], [3, 1, 2]]) tree = store[c3.tree] stream = b"".join(tar_stream(store, tree, 10)) out = BytesIO(stream) tf = tarfile.TarFile(fileobj=out) self.addCleanup(tf.close) self.assertEqual([], tf.getnames()) def _get_example_tar_stream(self, *tar_stream_args, **tar_stream_kwargs): store = MemoryObjectStore() b1 = Blob.from_string(b"somedata") store.add_object(b1) t1 = Tree() t1.add(b"somename", 0o100644, b1.id) store.add_object(t1) stream = b"".join(tar_stream(store, t1, *tar_stream_args, **tar_stream_kwargs)) return BytesIO(stream) def test_simple(self) -> None: stream = self._get_example_tar_stream(mtime=0) tf = tarfile.TarFile(fileobj=stream) self.addCleanup(tf.close) self.assertEqual(["somename"], tf.getnames()) def test_unicode(self) -> None: store = MemoryObjectStore() b1 = Blob.from_string(b"somedata") store.add_object(b1) t1 = Tree() t1.add("ő".encode(), 0o100644, b1.id) store.add_object(t1) stream = b"".join(tar_stream(store, t1, mtime=0)) tf = tarfile.TarFile(fileobj=BytesIO(stream)) self.addCleanup(tf.close) self.assertEqual(["ő"], tf.getnames()) def test_prefix(self) -> None: stream = self._get_example_tar_stream(mtime=0, prefix=b"blah") tf = tarfile.TarFile(fileobj=stream) self.addCleanup(tf.close) self.assertEqual(["blah/somename"], tf.getnames()) def test_gzip_mtime(self) -> None: stream = self._get_example_tar_stream(mtime=1234, format="gz") expected_mtime = struct.pack(" None: contents = [None, None] for format in ["", "gz", "bz2"]: for i in [0, 1]: with patch("time.time", return_value=i): stream = self._get_example_tar_stream(mtime=0, format=format) contents[i] = stream.getvalue() self.assertEqual( contents[0], contents[1], f"Different file contents for format {format!r}", ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_blackbox.py0000644000175100002000000000512614731042555017203 0ustar00runnerdocker# test_blackbox.py -- blackbox tests # Copyright (C) 2010 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Blackbox tests for Dulwich commands.""" import shutil import tempfile from dulwich.repo import Repo from . import BlackboxTestCase class GitReceivePackTests(BlackboxTestCase): """Blackbox tests for dul-receive-pack.""" def setUp(self) -> None: super().setUp() self.path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.path) self.repo = Repo.init(self.path) def test_basic(self) -> None: process = self.run_command("dul-receive-pack", [self.path]) (stdout, stderr) = process.communicate(b"0000") self.assertEqual(b"0000", stdout[-4:]) self.assertEqual(0, process.returncode) def test_missing_arg(self) -> None: process = self.run_command("dul-receive-pack", []) (stdout, stderr) = process.communicate() self.assertEqual( [b"usage: dul-receive-pack "], stderr.splitlines()[-1:] ) self.assertEqual(b"", stdout) self.assertEqual(1, process.returncode) class GitUploadPackTests(BlackboxTestCase): """Blackbox tests for dul-upload-pack.""" def setUp(self) -> None: super().setUp() self.path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.path) self.repo = Repo.init(self.path) def test_missing_arg(self) -> None: process = self.run_command("dul-upload-pack", []) (stdout, stderr) = process.communicate() self.assertEqual( [b"usage: dul-upload-pack "], stderr.splitlines()[-1:] ) self.assertEqual(b"", stdout) self.assertEqual(1, process.returncode) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_bundle.py0000644000175100002000000000370414731042555016667 0ustar00runnerdocker# test_bundle.py -- tests for bundle # Copyright (C) 2020 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for bundle support.""" import os import tempfile from io import BytesIO from dulwich.bundle import Bundle, read_bundle, write_bundle from dulwich.pack import PackData, write_pack_objects from . import TestCase class BundleTests(TestCase): def test_roundtrip_bundle(self) -> None: origbundle = Bundle() origbundle.version = 3 origbundle.capabilities = {"foo": None} origbundle.references = {b"refs/heads/master": b"ab" * 20} origbundle.prerequisites = [(b"cc" * 20, "comment")] b = BytesIO() write_pack_objects(b.write, []) b.seek(0) origbundle.pack_data = PackData.from_file(b) with tempfile.TemporaryDirectory() as td: with open(os.path.join(td, "foo"), "wb") as f: write_bundle(f, origbundle) with open(os.path.join(td, "foo"), "rb") as f: newbundle = read_bundle(f) self.assertEqual(origbundle, newbundle) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_client.py0000644000175100002000000020464714731042555016705 0ustar00runnerdocker# test_client.py -- Tests for the git protocol, client side # Copyright (C) 2009 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # import base64 import os import shutil import sys import tempfile import warnings from io import BytesIO from typing import NoReturn from unittest.mock import patch from urllib.parse import quote as urlquote from urllib.parse import urlparse import dulwich from dulwich import client from dulwich.client import ( FetchPackResult, GitProtocolError, HangupException, HttpGitClient, InvalidWants, LocalGitClient, PLinkSSHVendor, ReportStatusParser, SendPackError, SSHGitClient, StrangeHostname, SubprocessSSHVendor, TCPGitClient, TraditionalGitClient, _extract_symrefs_and_agent, _remote_error_from_stderr, _win32_url_to_path, check_wants, default_urllib3_manager, get_credentials_from_store, get_transport_and_path, get_transport_and_path_from_url, parse_rsync_url, ) from dulwich.config import ConfigDict from dulwich.objects import Commit, Tree from dulwich.pack import pack_objects_to_data, write_pack_data, write_pack_objects from dulwich.protocol import DEFAULT_GIT_PROTOCOL_VERSION_FETCH, TCP_GIT_PORT, Protocol from dulwich.repo import MemoryRepo, Repo from dulwich.tests.utils import open_repo, setup_warning_catcher, tear_down_repo from . import TestCase, skipIf class DummyClient(TraditionalGitClient): def __init__(self, can_read, read, write) -> None: self.can_read = can_read self.read = read self.write = write TraditionalGitClient.__init__(self) def _connect(self, service, path, protocol_version=None): return Protocol(self.read, self.write), self.can_read, None class DummyPopen: def __init__(self, *args, **kwards) -> None: self.stdin = BytesIO(b"stdin") self.stdout = BytesIO(b"stdout") self.stderr = BytesIO(b"stderr") self.returncode = 0 self.args = args self.kwargs = kwards def communicate(self, *args, **kwards): return ("Running", "") def wait(self, *args, **kwards) -> bool: return False # TODO(durin42): add unit-level tests of GitClient class GitClientTests(TestCase): def setUp(self) -> None: super().setUp() self.rout = BytesIO() self.rin = BytesIO() self.client = DummyClient(lambda x: True, self.rin.read, self.rout.write) def test_caps(self) -> None: agent_cap = "agent=dulwich/{}.{}.{}".format(*dulwich.__version__).encode( "ascii" ) self.assertEqual( { b"multi_ack", b"side-band-64k", b"ofs-delta", b"thin-pack", b"multi_ack_detailed", b"shallow", agent_cap, }, set(self.client._fetch_capabilities), ) self.assertEqual( { b"delete-refs", b"ofs-delta", b"report-status", b"side-band-64k", agent_cap, }, set(self.client._send_capabilities), ) def test_archive_ack(self) -> None: self.rin.write(b"0009NACK\n" b"0000") self.rin.seek(0) self.client.archive(b"bla", b"HEAD", None, None) self.assertEqual(self.rout.getvalue(), b"0011argument HEAD0000") def test_fetch_empty(self) -> None: self.rin.write(b"0000") self.rin.seek(0) def check_heads(heads, **kwargs): self.assertEqual(heads, {}) return [] ret = self.client.fetch_pack(b"/", check_heads, None, None) self.assertEqual({}, ret.refs) self.assertEqual({}, ret.symrefs) def test_fetch_pack_ignores_magic_ref(self) -> None: self.rin.write( b"00000000000000000000000000000000000000000000 capabilities^{}" b"\x00 multi_ack " b"thin-pack side-band side-band-64k ofs-delta shallow no-progress " b"include-tag\n" b"0000" ) self.rin.seek(0) def check_heads(heads, **kwargs): self.assertEqual({}, heads) return [] ret = self.client.fetch_pack(b"bla", check_heads, None, None, None) self.assertEqual({}, ret.refs) self.assertEqual({}, ret.symrefs) self.assertEqual(self.rout.getvalue(), b"0000") def test_fetch_pack_none(self) -> None: self.rin.write( b"008855dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7 HEAD\x00multi_ack " b"thin-pack side-band side-band-64k ofs-delta shallow no-progress " b"include-tag\n" b"0000" ) self.rin.seek(0) ret = self.client.fetch_pack( b"bla", lambda heads, **kwargs: [], None, None, None ) self.assertEqual( {b"HEAD": b"55dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7"}, ret.refs ) self.assertEqual({}, ret.symrefs) self.assertEqual(self.rout.getvalue(), b"0000") def test_send_pack_no_sideband64k_with_update_ref_error(self) -> None: # No side-bank-64k reported by server shouldn't try to parse # side band data pkts = [ b"55dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7 capabilities^{}" b"\x00 report-status delete-refs ofs-delta\n", b"", b"unpack ok", b"ng refs/foo/bar pre-receive hook declined", b"", ] for pkt in pkts: if pkt == b"": self.rin.write(b"0000") else: self.rin.write(("%04x" % (len(pkt) + 4)).encode("ascii") + pkt) self.rin.seek(0) tree = Tree() commit = Commit() commit.tree = tree commit.parents = [] commit.author = commit.committer = b"test user" commit.commit_time = commit.author_time = 1174773719 commit.commit_timezone = commit.author_timezone = 0 commit.encoding = b"UTF-8" commit.message = b"test message" def update_refs(refs): return { b"refs/foo/bar": commit.id, } def generate_pack_data(have, want, ofs_delta=False, progress=None): return pack_objects_to_data( [ (commit, None), (tree, b""), ] ) result = self.client.send_pack("blah", update_refs, generate_pack_data) self.assertEqual( {b"refs/foo/bar": "pre-receive hook declined"}, result.ref_status ) self.assertEqual({b"refs/foo/bar": commit.id}, result.refs) def test_send_pack_none(self) -> None: # Set ref to current value self.rin.write( b"0078310ca9477129b8586fa2afc779c1f57cf64bba6c " b"refs/heads/master\x00 report-status delete-refs " b"side-band-64k quiet ofs-delta\n" b"0000" ) self.rin.seek(0) def update_refs(refs): return {b"refs/heads/master": b"310ca9477129b8586fa2afc779c1f57cf64bba6c"} def generate_pack_data(have, want, ofs_delta=False, progress=None): return 0, [] self.client.send_pack(b"/", update_refs, generate_pack_data) self.assertEqual(self.rout.getvalue(), b"0000") def test_send_pack_keep_and_delete(self) -> None: self.rin.write( b"0063310ca9477129b8586fa2afc779c1f57cf64bba6c " b"refs/heads/master\x00report-status delete-refs ofs-delta\n" b"003f310ca9477129b8586fa2afc779c1f57cf64bba6c refs/heads/keepme\n" b"0000000eunpack ok\n" b"0019ok refs/heads/master\n" b"0000" ) self.rin.seek(0) def update_refs(refs): return {b"refs/heads/master": b"0" * 40} def generate_pack_data(have, want, ofs_delta=False, progress=None): return 0, [] self.client.send_pack(b"/", update_refs, generate_pack_data) self.assertEqual( self.rout.getvalue(), b"008b310ca9477129b8586fa2afc779c1f57cf64bba6c " b"0000000000000000000000000000000000000000 " b"refs/heads/master\x00delete-refs ofs-delta report-status0000", ) def test_send_pack_delete_only(self) -> None: self.rin.write( b"0063310ca9477129b8586fa2afc779c1f57cf64bba6c " b"refs/heads/master\x00report-status delete-refs ofs-delta\n" b"0000000eunpack ok\n" b"0019ok refs/heads/master\n" b"0000" ) self.rin.seek(0) def update_refs(refs): return {b"refs/heads/master": b"0" * 40} def generate_pack_data(have, want, ofs_delta=False, progress=None): return 0, [] self.client.send_pack(b"/", update_refs, generate_pack_data) self.assertEqual( self.rout.getvalue(), b"008b310ca9477129b8586fa2afc779c1f57cf64bba6c " b"0000000000000000000000000000000000000000 " b"refs/heads/master\x00delete-refs ofs-delta report-status0000", ) def test_send_pack_new_ref_only(self) -> None: self.rin.write( b"0063310ca9477129b8586fa2afc779c1f57cf64bba6c " b"refs/heads/master\x00report-status delete-refs ofs-delta\n" b"0000000eunpack ok\n" b"0019ok refs/heads/blah12\n" b"0000" ) self.rin.seek(0) def update_refs(refs): return { b"refs/heads/blah12": b"310ca9477129b8586fa2afc779c1f57cf64bba6c", b"refs/heads/master": b"310ca9477129b8586fa2afc779c1f57cf64bba6c", } def generate_pack_data(have, want, ofs_delta=False, progress=None): return 0, [] f = BytesIO() write_pack_objects(f.write, []) self.client.send_pack("/", update_refs, generate_pack_data) self.assertEqual( self.rout.getvalue(), b"008b0000000000000000000000000000000000000000 " b"310ca9477129b8586fa2afc779c1f57cf64bba6c " b"refs/heads/blah12\x00delete-refs ofs-delta report-status0000" + f.getvalue(), ) def test_send_pack_new_ref(self) -> None: self.rin.write( b"0064310ca9477129b8586fa2afc779c1f57cf64bba6c " b"refs/heads/master\x00 report-status delete-refs ofs-delta\n" b"0000000eunpack ok\n" b"0019ok refs/heads/blah12\n" b"0000" ) self.rin.seek(0) tree = Tree() commit = Commit() commit.tree = tree commit.parents = [] commit.author = commit.committer = b"test user" commit.commit_time = commit.author_time = 1174773719 commit.commit_timezone = commit.author_timezone = 0 commit.encoding = b"UTF-8" commit.message = b"test message" def update_refs(refs): return { b"refs/heads/blah12": commit.id, b"refs/heads/master": b"310ca9477129b8586fa2afc779c1f57cf64bba6c", } def generate_pack_data(have, want, ofs_delta=False, progress=None): return pack_objects_to_data( [ (commit, None), (tree, b""), ] ) f = BytesIO() count, records = generate_pack_data(None, None) write_pack_data(f.write, records, num_records=count) self.client.send_pack(b"/", update_refs, generate_pack_data) self.assertEqual( self.rout.getvalue(), b"008b0000000000000000000000000000000000000000 " + commit.id + b" refs/heads/blah12\x00delete-refs ofs-delta report-status0000" + f.getvalue(), ) def test_send_pack_no_deleteref_delete_only(self) -> None: pkts = [ b"310ca9477129b8586fa2afc779c1f57cf64bba6c refs/heads/master" b"\x00 report-status ofs-delta\n", b"", b"", ] for pkt in pkts: if pkt == b"": self.rin.write(b"0000") else: self.rin.write(("%04x" % (len(pkt) + 4)).encode("ascii") + pkt) self.rin.seek(0) def update_refs(refs): return {b"refs/heads/master": b"0" * 40} def generate_pack_data(have, want, ofs_delta=False, progress=None): return 0, [] result = self.client.send_pack(b"/", update_refs, generate_pack_data) self.assertEqual( result.ref_status, {b"refs/heads/master": "remote does not support deleting refs"}, ) self.assertEqual( result.refs, {b"refs/heads/master": b"310ca9477129b8586fa2afc779c1f57cf64bba6c"}, ) self.assertEqual(self.rout.getvalue(), b"0000") class TestGetTransportAndPath(TestCase): def test_tcp(self) -> None: c, path = get_transport_and_path("git://foo.com/bar/baz") self.assertIsInstance(c, TCPGitClient) self.assertEqual("foo.com", c._host) self.assertEqual(TCP_GIT_PORT, c._port) self.assertEqual("/bar/baz", path) def test_tcp_port(self) -> None: c, path = get_transport_and_path("git://foo.com:1234/bar/baz") self.assertIsInstance(c, TCPGitClient) self.assertEqual("foo.com", c._host) self.assertEqual(1234, c._port) self.assertEqual("/bar/baz", path) def test_git_ssh_explicit(self) -> None: c, path = get_transport_and_path("git+ssh://foo.com/bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual("/bar/baz", path) def test_ssh_explicit(self) -> None: c, path = get_transport_and_path("ssh://foo.com/bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual("/bar/baz", path) def test_ssh_port_explicit(self) -> None: c, path = get_transport_and_path("git+ssh://foo.com:1234/bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(1234, c.port) self.assertEqual("/bar/baz", path) def test_username_and_port_explicit_unknown_scheme(self) -> None: c, path = get_transport_and_path("unknown://git@server:7999/dply/stuff.git") self.assertIsInstance(c, SSHGitClient) self.assertEqual("unknown", c.host) self.assertEqual("//git@server:7999/dply/stuff.git", path) def test_username_and_port_explicit(self) -> None: c, path = get_transport_and_path("ssh://git@server:7999/dply/stuff.git") self.assertIsInstance(c, SSHGitClient) self.assertEqual("git", c.username) self.assertEqual("server", c.host) self.assertEqual(7999, c.port) self.assertEqual("/dply/stuff.git", path) def test_ssh_abspath_doubleslash(self) -> None: c, path = get_transport_and_path("git+ssh://foo.com//bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual("//bar/baz", path) def test_ssh_port(self) -> None: c, path = get_transport_and_path("git+ssh://foo.com:1234/bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(1234, c.port) self.assertEqual("/bar/baz", path) def test_ssh_implicit(self) -> None: c, path = get_transport_and_path("foo:/bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo", c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual("/bar/baz", path) def test_ssh_host(self) -> None: c, path = get_transport_and_path("foo.com:/bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual("/bar/baz", path) def test_ssh_user_host(self) -> None: c, path = get_transport_and_path("user@foo.com:/bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(None, c.port) self.assertEqual("user", c.username) self.assertEqual("/bar/baz", path) def test_ssh_relpath(self) -> None: c, path = get_transport_and_path("foo:bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo", c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual("bar/baz", path) def test_ssh_host_relpath(self) -> None: c, path = get_transport_and_path("foo.com:bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual("bar/baz", path) def test_ssh_user_host_relpath(self) -> None: c, path = get_transport_and_path("user@foo.com:bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(None, c.port) self.assertEqual("user", c.username) self.assertEqual("bar/baz", path) def test_local(self) -> None: c, path = get_transport_and_path("foo.bar/baz") self.assertIsInstance(c, LocalGitClient) self.assertEqual("foo.bar/baz", path) @skipIf(sys.platform != "win32", "Behaviour only happens on windows.") def test_local_abs_windows_path(self) -> None: c, path = get_transport_and_path("C:\\foo.bar\\baz") self.assertIsInstance(c, LocalGitClient) self.assertEqual("C:\\foo.bar\\baz", path) def test_error(self) -> None: # Need to use a known urlparse.uses_netloc URL scheme to get the # expected parsing of the URL on Python versions less than 2.6.5 c, path = get_transport_and_path("prospero://bar/baz") self.assertIsInstance(c, SSHGitClient) def test_http(self) -> None: url = "https://github.com/jelmer/dulwich" c, path = get_transport_and_path(url) self.assertIsInstance(c, HttpGitClient) self.assertEqual("/jelmer/dulwich", path) def test_http_auth(self) -> None: url = "https://user:passwd@github.com/jelmer/dulwich" c, path = get_transport_and_path(url) self.assertIsInstance(c, HttpGitClient) self.assertEqual("/jelmer/dulwich", path) self.assertEqual("user", c._username) self.assertEqual("passwd", c._password) def test_http_auth_with_username(self) -> None: url = "https://github.com/jelmer/dulwich" c, path = get_transport_and_path(url, username="user2", password="blah") self.assertIsInstance(c, HttpGitClient) self.assertEqual("/jelmer/dulwich", path) self.assertEqual("user2", c._username) self.assertEqual("blah", c._password) def test_http_auth_with_username_and_in_url(self) -> None: url = "https://user:passwd@github.com/jelmer/dulwich" c, path = get_transport_and_path(url, username="user2", password="blah") self.assertIsInstance(c, HttpGitClient) self.assertEqual("/jelmer/dulwich", path) self.assertEqual("user", c._username) self.assertEqual("passwd", c._password) def test_http_no_auth(self) -> None: url = "https://github.com/jelmer/dulwich" c, path = get_transport_and_path(url) self.assertIsInstance(c, HttpGitClient) self.assertEqual("/jelmer/dulwich", path) self.assertIs(None, c._username) self.assertIs(None, c._password) class TestGetTransportAndPathFromUrl(TestCase): def test_tcp(self) -> None: c, path = get_transport_and_path_from_url("git://foo.com/bar/baz") self.assertIsInstance(c, TCPGitClient) self.assertEqual("foo.com", c._host) self.assertEqual(TCP_GIT_PORT, c._port) self.assertEqual("/bar/baz", path) def test_tcp_port(self) -> None: c, path = get_transport_and_path_from_url("git://foo.com:1234/bar/baz") self.assertIsInstance(c, TCPGitClient) self.assertEqual("foo.com", c._host) self.assertEqual(1234, c._port) self.assertEqual("/bar/baz", path) def test_ssh_explicit(self) -> None: c, path = get_transport_and_path_from_url("git+ssh://foo.com/bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual("/bar/baz", path) def test_ssh_port_explicit(self) -> None: c, path = get_transport_and_path_from_url("git+ssh://foo.com:1234/bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(1234, c.port) self.assertEqual("/bar/baz", path) def test_ssh_homepath(self) -> None: c, path = get_transport_and_path_from_url("git+ssh://foo.com/~/bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(None, c.port) self.assertEqual(None, c.username) self.assertEqual("/~/bar/baz", path) def test_ssh_port_homepath(self) -> None: c, path = get_transport_and_path_from_url("git+ssh://foo.com:1234/~/bar/baz") self.assertIsInstance(c, SSHGitClient) self.assertEqual("foo.com", c.host) self.assertEqual(1234, c.port) self.assertEqual("/~/bar/baz", path) def test_ssh_host_relpath(self) -> None: self.assertRaises( ValueError, get_transport_and_path_from_url, "foo.com:bar/baz" ) def test_ssh_user_host_relpath(self) -> None: self.assertRaises( ValueError, get_transport_and_path_from_url, "user@foo.com:bar/baz" ) def test_local_path(self) -> None: self.assertRaises(ValueError, get_transport_and_path_from_url, "foo.bar/baz") def test_error(self) -> None: # Need to use a known urlparse.uses_netloc URL scheme to get the # expected parsing of the URL on Python versions less than 2.6.5 self.assertRaises( ValueError, get_transport_and_path_from_url, "prospero://bar/baz" ) def test_http(self) -> None: url = "https://github.com/jelmer/dulwich" c, path = get_transport_and_path_from_url(url) self.assertIsInstance(c, HttpGitClient) self.assertEqual("https://github.com", c.get_url(b"/")) self.assertEqual("/jelmer/dulwich", path) def test_http_port(self) -> None: url = "https://github.com:9090/jelmer/dulwich" c, path = get_transport_and_path_from_url(url) self.assertEqual("https://github.com:9090", c.get_url(b"/")) self.assertIsInstance(c, HttpGitClient) self.assertEqual("/jelmer/dulwich", path) @patch("os.name", "posix") @patch("sys.platform", "linux") def test_file(self) -> None: c, path = get_transport_and_path_from_url("file:///home/jelmer/foo") self.assertIsInstance(c, LocalGitClient) self.assertEqual("/home/jelmer/foo", path) def test_win32_url_to_path(self): def check(url, expected): parsed = urlparse(url) self.assertEqual(_win32_url_to_path(parsed), expected) check("file:C:/foo.bar/baz", "C:\\foo.bar\\baz") check("file:/C:/foo.bar/baz", "C:\\foo.bar\\baz") check("file://C:/foo.bar/baz", "C:\\foo.bar\\baz") check("file:///C:/foo.bar/baz", "C:\\foo.bar\\baz") @patch("os.name", "nt") @patch("sys.platform", "win32") def test_file_win(self) -> None: expected = "C:\\foo.bar\\baz" for file_url in [ "file:C:/foo.bar/baz", "file:/C:/foo.bar/baz", "file://C:/foo.bar/baz", "file:///C:/foo.bar/baz", ]: c, path = get_transport_and_path(file_url) self.assertIsInstance(c, LocalGitClient) self.assertEqual(path, expected) for remote_url in [ "file://host.example.com/C:/foo.bar/baz" "file://host.example.com/C:/foo.bar/baz" "file:////host.example/foo.bar/baz", ]: with self.assertRaises(NotImplementedError): c, path = get_transport_and_path(remote_url) class TestSSHVendor: def __init__(self) -> None: self.host = None self.command = "" self.username = None self.port = None self.password = None self.key_filename = None def run_command( self, host, command, username=None, port=None, password=None, key_filename=None, ssh_command=None, protocol_version=None, ): self.host = host self.command = command self.username = username self.port = port self.password = password self.key_filename = key_filename self.ssh_command = ssh_command self.protocol_version = protocol_version class Subprocess: pass Subprocess.read = lambda: None Subprocess.write = lambda: None Subprocess.close = lambda: None Subprocess.can_read = lambda: None return Subprocess() class SSHGitClientTests(TestCase): def setUp(self) -> None: super().setUp() self.server = TestSSHVendor() self.real_vendor = client.get_ssh_vendor client.get_ssh_vendor = lambda: self.server self.client = SSHGitClient("git.samba.org") def tearDown(self) -> None: super().tearDown() client.get_ssh_vendor = self.real_vendor def test_get_url(self) -> None: path = "/tmp/repo.git" c = SSHGitClient("git.samba.org") url = c.get_url(path) self.assertEqual("ssh://git.samba.org/tmp/repo.git", url) def test_get_url_with_username_and_port(self) -> None: path = "/tmp/repo.git" c = SSHGitClient("git.samba.org", port=2222, username="user") url = c.get_url(path) self.assertEqual("ssh://user@git.samba.org:2222/tmp/repo.git", url) def test_default_command(self) -> None: self.assertEqual(b"git-upload-pack", self.client._get_cmd_path(b"upload-pack")) def test_alternative_command_path(self) -> None: self.client.alternative_paths[b"upload-pack"] = b"/usr/lib/git/git-upload-pack" self.assertEqual( b"/usr/lib/git/git-upload-pack", self.client._get_cmd_path(b"upload-pack"), ) def test_alternative_command_path_spaces(self) -> None: self.client.alternative_paths[b"upload-pack"] = ( b"/usr/lib/git/git-upload-pack -ibla" ) self.assertEqual( b"/usr/lib/git/git-upload-pack -ibla", self.client._get_cmd_path(b"upload-pack"), ) def test_connect(self) -> None: server = self.server client = self.client client.username = b"username" client.port = 1337 client._connect(b"command", b"/path/to/repo") self.assertEqual(b"username", server.username) self.assertEqual(1337, server.port) self.assertEqual("git-command '/path/to/repo'", server.command) client._connect(b"relative-command", b"/~/path/to/repo") self.assertEqual("git-relative-command '~/path/to/repo'", server.command) def test_ssh_command_precedence(self) -> None: self.overrideEnv("GIT_SSH", "/path/to/ssh") test_client = SSHGitClient("git.samba.org") self.assertEqual(test_client.ssh_command, "/path/to/ssh") self.overrideEnv("GIT_SSH_COMMAND", "/path/to/ssh -o Option=Value") test_client = SSHGitClient("git.samba.org") self.assertEqual(test_client.ssh_command, "/path/to/ssh -o Option=Value") test_client = SSHGitClient("git.samba.org", ssh_command="ssh -o Option1=Value1") self.assertEqual(test_client.ssh_command, "ssh -o Option1=Value1") class ReportStatusParserTests(TestCase): def test_invalid_pack(self) -> None: parser = ReportStatusParser() parser.handle_packet(b"unpack error - foo bar") parser.handle_packet(b"ok refs/foo/bar") parser.handle_packet(None) self.assertRaises(SendPackError, list, parser.check()) def test_update_refs_error(self) -> None: parser = ReportStatusParser() parser.handle_packet(b"unpack ok") parser.handle_packet(b"ng refs/foo/bar need to pull") parser.handle_packet(None) self.assertEqual([(b"refs/foo/bar", "need to pull")], list(parser.check())) def test_ok(self) -> None: parser = ReportStatusParser() parser.handle_packet(b"unpack ok") parser.handle_packet(b"ok refs/foo/bar") parser.handle_packet(None) self.assertEqual([(b"refs/foo/bar", None)], list(parser.check())) class LocalGitClientTests(TestCase): def test_get_url(self) -> None: path = "/tmp/repo.git" c = LocalGitClient() url = c.get_url(path) self.assertEqual("file:///tmp/repo.git", url) def test_fetch_into_empty(self) -> None: c = LocalGitClient() target = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target) t = Repo.init_bare(target) self.addCleanup(t.close) s = open_repo("a.git") self.addCleanup(tear_down_repo, s) self.assertEqual(s.get_refs(), c.fetch(s.path, t).refs) def test_clone(self) -> None: c = LocalGitClient() s = open_repo("a.git") self.addCleanup(tear_down_repo, s) target = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target) result_repo = c.clone(s.path, target, mkdir=False) self.addCleanup(result_repo.close) expected = dict(s.get_refs()) expected[b"refs/remotes/origin/HEAD"] = expected[b"HEAD"] expected[b"refs/remotes/origin/master"] = expected[b"refs/heads/master"] self.assertEqual(expected, result_repo.get_refs()) def test_fetch_empty(self) -> None: c = LocalGitClient() s = open_repo("a.git") self.addCleanup(tear_down_repo, s) out = BytesIO() walker = {} ret = c.fetch_pack( s.path, lambda heads, **kwargs: [], graph_walker=walker, pack_data=out.write ) self.assertEqual( { b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50", }, ret.refs, ) self.assertEqual({b"HEAD": b"refs/heads/master"}, ret.symrefs) self.assertEqual( b"PACK\x00\x00\x00\x02\x00\x00\x00\x00\x02\x9d\x08" b"\x82;\xd8\xa8\xea\xb5\x10\xadj\xc7\\\x82<\xfd>\xd3\x1e", out.getvalue(), ) def test_fetch_pack_none(self) -> None: c = LocalGitClient() s = open_repo("a.git") self.addCleanup(tear_down_repo, s) out = BytesIO() walker = MemoryRepo().get_graph_walker() ret = c.fetch_pack( s.path, lambda heads, **kwargs: [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"], graph_walker=walker, pack_data=out.write, ) self.assertEqual({b"HEAD": b"refs/heads/master"}, ret.symrefs) self.assertEqual( { b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50", }, ret.refs, ) # Hardcoding is not ideal, but we'll fix that some other day.. self.assertTrue( out.getvalue().startswith(b"PACK\x00\x00\x00\x02\x00\x00\x00\x07") ) def test_send_pack_without_changes(self) -> None: local = open_repo("a.git") self.addCleanup(tear_down_repo, local) target = open_repo("a.git") self.addCleanup(tear_down_repo, target) self.send_and_verify(b"master", local, target) def test_send_pack_with_changes(self) -> None: local = open_repo("a.git") self.addCleanup(tear_down_repo, local) target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) with Repo.init_bare(target_path) as target: self.send_and_verify(b"master", local, target) def test_get_refs(self) -> None: local = open_repo("refs.git") self.addCleanup(tear_down_repo, local) client = LocalGitClient() refs = client.get_refs(local.path) self.assertDictEqual(local.refs.as_dict(), refs) def send_and_verify(self, branch, local, target) -> None: """Send branch from local to remote repository and verify it worked.""" client = LocalGitClient() ref_name = b"refs/heads/" + branch result = client.send_pack( target.path, lambda _: {ref_name: local.refs[ref_name]}, local.generate_pack_data, ) self.assertEqual(local.refs[ref_name], result.refs[ref_name]) self.assertIs(None, result.agent) self.assertEqual({}, result.ref_status) obj_local = local.get_object(result.refs[ref_name]) obj_target = target.get_object(result.refs[ref_name]) self.assertEqual(obj_local, obj_target) class HttpGitClientTests(TestCase): def test_get_url(self) -> None: base_url = "https://github.com/jelmer/dulwich" path = "/jelmer/dulwich" c = HttpGitClient(base_url) url = c.get_url(path) self.assertEqual("https://github.com/jelmer/dulwich", url) def test_get_url_bytes_path(self) -> None: base_url = "https://github.com/jelmer/dulwich" path_bytes = b"/jelmer/dulwich" c = HttpGitClient(base_url) url = c.get_url(path_bytes) self.assertEqual("https://github.com/jelmer/dulwich", url) def test_get_url_with_username_and_passwd(self) -> None: base_url = "https://github.com/jelmer/dulwich" path = "/jelmer/dulwich" c = HttpGitClient(base_url, username="USERNAME", password="PASSWD") url = c.get_url(path) self.assertEqual("https://github.com/jelmer/dulwich", url) def test_init_username_passwd_set(self) -> None: url = "https://github.com/jelmer/dulwich" c = HttpGitClient(url, config=None, username="user", password="passwd") self.assertEqual("user", c._username) self.assertEqual("passwd", c._password) basic_auth = c.pool_manager.headers["authorization"] auth_string = "{}:{}".format("user", "passwd") b64_credentials = base64.b64encode(auth_string.encode("latin1")) expected_basic_auth = "Basic {}".format(b64_credentials.decode("latin1")) self.assertEqual(basic_auth, expected_basic_auth) def test_init_username_set_no_password(self) -> None: url = "https://github.com/jelmer/dulwich" c = HttpGitClient(url, config=None, username="user") self.assertEqual("user", c._username) self.assertIsNone(c._password) basic_auth = c.pool_manager.headers["authorization"] auth_string = b"user:" b64_credentials = base64.b64encode(auth_string) expected_basic_auth = f"Basic {b64_credentials.decode('ascii')}" self.assertEqual(basic_auth, expected_basic_auth) def test_init_no_username_passwd(self) -> None: url = "https://github.com/jelmer/dulwich" c = HttpGitClient(url, config=None) self.assertIs(None, c._username) self.assertIs(None, c._password) self.assertNotIn("authorization", c.pool_manager.headers) def test_from_parsedurl_username_only(self) -> None: username = "user" url = f"https://{username}@github.com/jelmer/dulwich" c = HttpGitClient.from_parsedurl(urlparse(url)) self.assertEqual(c._username, username) self.assertEqual(c._password, None) basic_auth = c.pool_manager.headers["authorization"] auth_string = username.encode("ascii") + b":" b64_credentials = base64.b64encode(auth_string) expected_basic_auth = f"Basic {b64_credentials.decode('ascii')}" self.assertEqual(basic_auth, expected_basic_auth) def test_from_parsedurl_on_url_with_quoted_credentials(self) -> None: original_username = "john|the|first" quoted_username = urlquote(original_username) original_password = "Ya#1$2%3" quoted_password = urlquote(original_password) url = f"https://{quoted_username}:{quoted_password}@github.com/jelmer/dulwich" c = HttpGitClient.from_parsedurl(urlparse(url)) self.assertEqual(original_username, c._username) self.assertEqual(original_password, c._password) basic_auth = c.pool_manager.headers["authorization"] auth_string = f"{original_username}:{original_password}" b64_credentials = base64.b64encode(auth_string.encode("latin1")) expected_basic_auth = "Basic {}".format(b64_credentials.decode("latin1")) self.assertEqual(basic_auth, expected_basic_auth) def test_url_redirect_location(self) -> None: from urllib3.response import HTTPResponse test_data = { "https://gitlab.com/inkscape/inkscape/": { "location": "https://gitlab.com/inkscape/inkscape.git/", "redirect_url": "https://gitlab.com/inkscape/inkscape.git/", "refs_data": ( b"001e# service=git-upload-pack\n00000032" b"fb2bebf4919a011f0fd7cec085443d0031228e76 " b"HEAD\n0000" ), }, "https://github.com/jelmer/dulwich/": { "location": "https://github.com/jelmer/dulwich/", "redirect_url": "https://github.com/jelmer/dulwich/", "refs_data": ( b"001e# service=git-upload-pack\n00000032" b"3ff25e09724aa4d86ea5bca7d5dd0399a3c8bfcf " b"HEAD\n0000" ), }, # check for absolute-path URI reference as location "https://codeberg.org/ashwinvis/radicale-sh.git/": { "location": "/ashwinvis/radicale-auth-sh/", "redirect_url": "https://codeberg.org/ashwinvis/radicale-auth-sh/", "refs_data": ( b"001e# service=git-upload-pack\n00000032" b"470f8603768b608fc988675de2fae8f963c21158 " b"HEAD\n0000" ), }, } tail = "info/refs?service=git-upload-pack" # we need to mock urllib3.PoolManager as this test will fail # otherwise without an active internet connection class PoolManagerMock: def __init__(self) -> None: self.headers: dict[str, str] = {} def request( self, method, url, fields=None, headers=None, redirect=True, preload_content=True, ): base_url = url[: -len(tail)] redirect_base_url = test_data[base_url]["location"] redirect_url = redirect_base_url + tail headers = { "Content-Type": "application/x-git-upload-pack-advertisement" } body = test_data[base_url]["refs_data"] # urllib3 handles automatic redirection by default status = 200 request_url = redirect_url # simulate urllib3 behavior when redirect parameter is False if redirect is False: request_url = url if redirect_base_url != base_url: body = b"" headers["location"] = test_data[base_url]["location"] status = 301 return HTTPResponse( body=BytesIO(body), headers=headers, request_method=method, request_url=request_url, preload_content=preload_content, status=status, ) pool_manager = PoolManagerMock() for base_url in test_data.keys(): # instantiate HttpGitClient with mocked pool manager c = HttpGitClient(base_url, pool_manager=pool_manager, config=None) # call method that detects url redirection _, _, processed_url, _, _ = c._discover_references( b"git-upload-pack", base_url ) # send the same request as the method above without redirection resp = c.pool_manager.request("GET", base_url + tail, redirect=False) # check expected behavior of urllib3 redirect_location = resp.get_redirect_location() if resp.status == 200: self.assertFalse(redirect_location) if redirect_location: # check that url redirection has been correctly detected self.assertEqual(processed_url, test_data[base_url]["redirect_url"]) else: # check also the no redirection case self.assertEqual(processed_url, base_url) def test_smart_request_content_type_with_directive_check(self) -> None: from urllib3.response import HTTPResponse # we need to mock urllib3.PoolManager as this test will fail # otherwise without an active internet connection class PoolManagerMock: def __init__(self) -> None: self.headers: dict[str, str] = {} def request( self, method, url, fields=None, headers=None, redirect=True, preload_content=True, ): return HTTPResponse( headers={ "Content-Type": "application/x-git-upload-pack-result; charset=utf-8" }, request_method=method, request_url=url, preload_content=preload_content, status=200, ) clone_url = "https://hacktivis.me/git/blog.git/" client = HttpGitClient(clone_url, pool_manager=PoolManagerMock(), config=None) self.assertTrue(client._smart_request("git-upload-pack", clone_url, data=None)) def test_urllib3_protocol_error(self) -> None: from urllib3.exceptions import ProtocolError from urllib3.response import HTTPResponse error_msg = "protocol error" # we need to mock urllib3.PoolManager as this test will fail # otherwise without an active internet connection class PoolManagerMock: def __init__(self) -> None: self.headers: dict[str, str] = {} def request( self, method, url, fields=None, headers=None, redirect=True, preload_content=True, ): response = HTTPResponse( headers={"Content-Type": "application/x-git-upload-pack-result"}, request_method=method, request_url=url, preload_content=preload_content, status=200, ) def read(self) -> NoReturn: raise ProtocolError(error_msg) # override HTTPResponse.read to throw urllib3.exceptions.ProtocolError response.read = read return response def check_heads(heads, **kwargs): self.assertEqual(heads, {}) return [] clone_url = "https://git.example.org/user/project.git/" client = HttpGitClient(clone_url, pool_manager=PoolManagerMock(), config=None) with self.assertRaises(GitProtocolError, msg=error_msg): client.fetch_pack(b"/", check_heads, None, None) class TCPGitClientTests(TestCase): def test_get_url(self) -> None: host = "github.com" path = "/jelmer/dulwich" c = TCPGitClient(host) url = c.get_url(path) self.assertEqual("git://github.com/jelmer/dulwich", url) def test_get_url_with_port(self) -> None: host = "github.com" path = "/jelmer/dulwich" port = 9090 c = TCPGitClient(host, port=port) url = c.get_url(path) self.assertEqual("git://github.com:9090/jelmer/dulwich", url) class DefaultUrllib3ManagerTest(TestCase): def test_no_config(self) -> None: manager = default_urllib3_manager(config=None) self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_REQUIRED") def test_config_no_proxy(self) -> None: import urllib3 manager = default_urllib3_manager(config=ConfigDict()) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_config_no_proxy_custom_cls(self) -> None: import urllib3 class CustomPoolManager(urllib3.PoolManager): pass manager = default_urllib3_manager( config=ConfigDict(), pool_manager_cls=CustomPoolManager ) self.assertIsInstance(manager, CustomPoolManager) def test_config_ssl(self) -> None: config = ConfigDict() config.set(b"http", b"sslVerify", b"true") manager = default_urllib3_manager(config=config) self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_REQUIRED") def test_config_no_ssl(self) -> None: config = ConfigDict() config.set(b"http", b"sslVerify", b"false") manager = default_urllib3_manager(config=config) self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_NONE") def test_config_proxy(self) -> None: import urllib3 config = ConfigDict() config.set(b"http", b"proxy", b"http://localhost:3128/") manager = default_urllib3_manager(config=config) self.assertIsInstance(manager, urllib3.ProxyManager) self.assertTrue(hasattr(manager, "proxy")) self.assertEqual(manager.proxy.scheme, "http") self.assertEqual(manager.proxy.host, "localhost") self.assertEqual(manager.proxy.port, 3128) def test_environment_proxy(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") manager = default_urllib3_manager(config=config) self.assertIsInstance(manager, urllib3.ProxyManager) self.assertTrue(hasattr(manager, "proxy")) self.assertEqual(manager.proxy.scheme, "http") self.assertEqual(manager.proxy.host, "myproxy") self.assertEqual(manager.proxy.port, 8080) def test_environment_empty_proxy(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "") manager = default_urllib3_manager(config=config) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_environment_no_proxy_1(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh") base_url = "http://xyz.abc.def.gh:8080/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_environment_no_proxy_2(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com") base_url = "http://ample.com/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_environment_no_proxy_3(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com") base_url = "http://ample.com:80/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_environment_no_proxy_4(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com") base_url = "http://www.ample.com/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_environment_no_proxy_5(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com") base_url = "http://www.example.com/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertIsInstance(manager, urllib3.ProxyManager) self.assertTrue(hasattr(manager, "proxy")) self.assertEqual(manager.proxy.scheme, "http") self.assertEqual(manager.proxy.host, "myproxy") self.assertEqual(manager.proxy.port, 8080) def test_environment_no_proxy_6(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com") base_url = "http://ample.com.org/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertIsInstance(manager, urllib3.ProxyManager) self.assertTrue(hasattr(manager, "proxy")) self.assertEqual(manager.proxy.scheme, "http") self.assertEqual(manager.proxy.host, "myproxy") self.assertEqual(manager.proxy.port, 8080) def test_environment_no_proxy_ipv4_address_1(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv("no_proxy", "xyz,abc.def.gh,192.168.0.10,ample.com") base_url = "http://192.168.0.10/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_environment_no_proxy_ipv4_address_2(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv("no_proxy", "xyz,abc.def.gh,192.168.0.10,ample.com") base_url = "http://192.168.0.10:8888/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_environment_no_proxy_ipv4_address_3(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv( "no_proxy", "xyz,abc.def.gh,ff80:1::/64,192.168.0.0/24,ample.com" ) base_url = "http://192.168.0.10/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_environment_no_proxy_ipv6_address_1(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv("no_proxy", "xyz,abc.def.gh,ff80:1::affe,ample.com") base_url = "http://[ff80:1::affe]/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_environment_no_proxy_ipv6_address_2(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv("no_proxy", "xyz,abc.def.gh,ff80:1::affe,ample.com") base_url = "http://[ff80:1::affe]:1234/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_environment_no_proxy_ipv6_address_3(self) -> None: import urllib3 config = ConfigDict() self.overrideEnv("http_proxy", "http://myproxy:8080") self.overrideEnv( "no_proxy", "xyz,abc.def.gh,192.168.0.0/24,ff80:1::/64,ample.com" ) base_url = "http://[ff80:1::affe]/path/port" manager = default_urllib3_manager(config=config, base_url=base_url) self.assertNotIsInstance(manager, urllib3.ProxyManager) self.assertIsInstance(manager, urllib3.PoolManager) def test_config_proxy_custom_cls(self) -> None: import urllib3 class CustomProxyManager(urllib3.ProxyManager): pass config = ConfigDict() config.set(b"http", b"proxy", b"http://localhost:3128/") manager = default_urllib3_manager( config=config, proxy_manager_cls=CustomProxyManager ) self.assertIsInstance(manager, CustomProxyManager) def test_config_proxy_creds(self) -> None: import urllib3 config = ConfigDict() config.set(b"http", b"proxy", b"http://jelmer:example@localhost:3128/") manager = default_urllib3_manager(config=config) assert isinstance(manager, urllib3.ProxyManager) self.assertEqual( manager.proxy_headers, {"proxy-authorization": "Basic amVsbWVyOmV4YW1wbGU="} ) def test_config_no_verify_ssl(self) -> None: manager = default_urllib3_manager(config=None, cert_reqs="CERT_NONE") self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_NONE") class SubprocessSSHVendorTests(TestCase): def setUp(self) -> None: # Monkey Patch client subprocess popen self._orig_popen = dulwich.client.subprocess.Popen dulwich.client.subprocess.Popen = DummyPopen def tearDown(self) -> None: dulwich.client.subprocess.Popen = self._orig_popen def test_run_command_dashes(self) -> None: vendor = SubprocessSSHVendor() self.assertRaises( StrangeHostname, vendor.run_command, "--weird-host", "git-clone-url", ) def test_run_command_password(self) -> None: vendor = SubprocessSSHVendor() self.assertRaises( NotImplementedError, vendor.run_command, "host", "git-clone-url", password="12345", ) def test_run_command_password_and_privkey(self) -> None: vendor = SubprocessSSHVendor() self.assertRaises( NotImplementedError, vendor.run_command, "host", "git-clone-url", password="12345", key_filename="/tmp/id_rsa", ) def test_run_command_with_port_username_and_privkey(self) -> None: expected = [ "ssh", "-x", "-p", "2200", "-i", "/tmp/id_rsa", ] if DEFAULT_GIT_PROTOCOL_VERSION_FETCH: expected += [ "-o", f"SetEnv GIT_PROTOCOL=version={DEFAULT_GIT_PROTOCOL_VERSION_FETCH}", ] expected += [ "user@host", "git-clone-url", ] vendor = SubprocessSSHVendor() command = vendor.run_command( "host", "git-clone-url", username="user", port="2200", key_filename="/tmp/id_rsa", ) args = command.proc.args self.assertListEqual(expected, args[0]) def test_run_with_ssh_command(self) -> None: expected = [ "/path/to/ssh", "-o", "Option=Value", "-x", ] if DEFAULT_GIT_PROTOCOL_VERSION_FETCH: expected += [ "-o", f"SetEnv GIT_PROTOCOL=version={DEFAULT_GIT_PROTOCOL_VERSION_FETCH}", ] expected += [ "host", "git-clone-url", ] vendor = SubprocessSSHVendor() command = vendor.run_command( "host", "git-clone-url", ssh_command="/path/to/ssh -o Option=Value", ) args = command.proc.args self.assertListEqual(expected, args[0]) class PLinkSSHVendorTests(TestCase): def setUp(self) -> None: # Monkey Patch client subprocess popen self._orig_popen = dulwich.client.subprocess.Popen dulwich.client.subprocess.Popen = DummyPopen def tearDown(self) -> None: dulwich.client.subprocess.Popen = self._orig_popen def test_run_command_dashes(self) -> None: vendor = PLinkSSHVendor() self.assertRaises( StrangeHostname, vendor.run_command, "--weird-host", "git-clone-url", ) def test_run_command_password_and_privkey(self) -> None: vendor = PLinkSSHVendor() warnings.simplefilter("always", UserWarning) self.addCleanup(warnings.resetwarnings) warnings_list, restore_warnings = setup_warning_catcher() self.addCleanup(restore_warnings) command = vendor.run_command( "host", "git-clone-url", password="12345", key_filename="/tmp/id_rsa", ) expected_warning = UserWarning( "Invoking PLink with a password exposes the password in the " "process list." ) for w in warnings_list: if type(w) is type(expected_warning) and w.args == expected_warning.args: break else: raise AssertionError( f"Expected warning {expected_warning!r} not in {warnings_list!r}" ) args = command.proc.args if sys.platform == "win32": binary = ["plink.exe", "-ssh"] else: binary = ["plink", "-ssh"] expected = [ *binary, "-pw", "12345", "-i", "/tmp/id_rsa", "host", "git-clone-url", ] self.assertListEqual(expected, args[0]) def test_run_command_password(self) -> None: if sys.platform == "win32": binary = ["plink.exe", "-ssh"] else: binary = ["plink", "-ssh"] expected = [*binary, "-pw", "12345", "host", "git-clone-url"] vendor = PLinkSSHVendor() warnings.simplefilter("always", UserWarning) self.addCleanup(warnings.resetwarnings) warnings_list, restore_warnings = setup_warning_catcher() self.addCleanup(restore_warnings) command = vendor.run_command("host", "git-clone-url", password="12345") expected_warning = UserWarning( "Invoking PLink with a password exposes the password in the " "process list." ) for w in warnings_list: if type(w) is type(expected_warning) and w.args == expected_warning.args: break else: raise AssertionError( f"Expected warning {expected_warning!r} not in {warnings_list!r}" ) args = command.proc.args self.assertListEqual(expected, args[0]) def test_run_command_with_port_username_and_privkey(self) -> None: if sys.platform == "win32": binary = ["plink.exe", "-ssh"] else: binary = ["plink", "-ssh"] expected = [ *binary, "-P", "2200", "-i", "/tmp/id_rsa", "user@host", "git-clone-url", ] vendor = PLinkSSHVendor() command = vendor.run_command( "host", "git-clone-url", username="user", port="2200", key_filename="/tmp/id_rsa", ) args = command.proc.args self.assertListEqual(expected, args[0]) def test_run_with_ssh_command(self) -> None: expected = [ "/path/to/plink", "-ssh", "host", "git-clone-url", ] vendor = PLinkSSHVendor() command = vendor.run_command( "host", "git-clone-url", ssh_command="/path/to/plink", ) args = command.proc.args self.assertListEqual(expected, args[0]) class RsyncUrlTests(TestCase): def test_simple(self) -> None: self.assertEqual(parse_rsync_url("foo:bar/path"), (None, "foo", "bar/path")) self.assertEqual( parse_rsync_url("user@foo:bar/path"), ("user", "foo", "bar/path") ) def test_path(self) -> None: self.assertRaises(ValueError, parse_rsync_url, "/path") class CheckWantsTests(TestCase): def test_fine(self) -> None: check_wants( [b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"], {b"refs/heads/blah": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"}, ) def test_missing(self) -> None: self.assertRaises( InvalidWants, check_wants, [b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"], {b"refs/heads/blah": b"3f3dc7a53fb752a6961d3a56683df46d4d3bf262"}, ) def test_annotated(self) -> None: self.assertRaises( InvalidWants, check_wants, [b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"], { b"refs/heads/blah": b"3f3dc7a53fb752a6961d3a56683df46d4d3bf262", b"refs/heads/blah^{}": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262", }, ) class FetchPackResultTests(TestCase): def test_eq(self) -> None: self.assertEqual( FetchPackResult( {b"refs/heads/master": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"}, {}, b"user/agent", ), FetchPackResult( {b"refs/heads/master": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"}, {}, b"user/agent", ), ) class GitCredentialStoreTests(TestCase): @classmethod def setUpClass(cls) -> None: with tempfile.NamedTemporaryFile(delete=False) as f: f.write(b"https://user:pass@example.org\n") cls.fname = f.name @classmethod def tearDownClass(cls) -> None: os.unlink(cls.fname) def test_nonmatching_scheme(self) -> None: self.assertEqual( get_credentials_from_store(b"http", b"example.org", fnames=[self.fname]), None, ) def test_nonmatching_hostname(self) -> None: self.assertEqual( get_credentials_from_store(b"https", b"noentry.org", fnames=[self.fname]), None, ) def test_match_without_username(self) -> None: self.assertEqual( get_credentials_from_store(b"https", b"example.org", fnames=[self.fname]), (b"user", b"pass"), ) def test_match_with_matching_username(self) -> None: self.assertEqual( get_credentials_from_store( b"https", b"example.org", b"user", fnames=[self.fname] ), (b"user", b"pass"), ) def test_no_match_with_nonmatching_username(self) -> None: self.assertEqual( get_credentials_from_store( b"https", b"example.org", b"otheruser", fnames=[self.fname] ), None, ) class RemoteErrorFromStderrTests(TestCase): def test_nothing(self) -> None: self.assertEqual(_remote_error_from_stderr(None), HangupException()) def test_error_line(self) -> None: b = BytesIO( b"""\ This is some random output. ERROR: This is the actual error with a tail """ ) self.assertEqual( _remote_error_from_stderr(b), GitProtocolError("This is the actual error"), ) def test_no_error_line(self) -> None: b = BytesIO( b"""\ This is output without an error line. And this line is just random noise, too. """ ) self.assertEqual( _remote_error_from_stderr(b), HangupException( [ b"This is output without an error line.", b"And this line is just random noise, too.", ] ), ) class TestExtractAgentAndSymrefs(TestCase): def test_extract_agent_and_symrefs(self) -> None: (symrefs, agent) = _extract_symrefs_and_agent( [b"agent=git/2.31.1", b"symref=HEAD:refs/heads/master"] ) self.assertEqual(agent, b"git/2.31.1") self.assertEqual(symrefs, {b"HEAD": b"refs/heads/master"}) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_config.py0000644000175100002000000004131214731042555016660 0ustar00runnerdocker# test_config.py -- Tests for reading and writing configuration files # Copyright (C) 2011 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for reading and writing configuration files.""" import os import sys from io import BytesIO from unittest import skipIf from unittest.mock import patch from dulwich.config import ( ConfigDict, ConfigFile, StackedConfig, _check_section_name, _check_variable_name, _escape_value, _format_string, _parse_string, apply_instead_of, parse_submodules, ) from . import TestCase class ConfigFileTests(TestCase): def from_file(self, text): return ConfigFile.from_file(BytesIO(text)) def test_empty(self) -> None: ConfigFile() def test_eq(self) -> None: self.assertEqual(ConfigFile(), ConfigFile()) def test_default_config(self) -> None: cf = self.from_file( b"""[core] \trepositoryformatversion = 0 \tfilemode = true \tbare = false \tlogallrefupdates = true """ ) self.assertEqual( ConfigFile( { (b"core",): { b"repositoryformatversion": b"0", b"filemode": b"true", b"bare": b"false", b"logallrefupdates": b"true", } } ), cf, ) def test_from_file_empty(self) -> None: cf = self.from_file(b"") self.assertEqual(ConfigFile(), cf) def test_empty_line_before_section(self) -> None: cf = self.from_file(b"\n[section]\n") self.assertEqual(ConfigFile({(b"section",): {}}), cf) def test_comment_before_section(self) -> None: cf = self.from_file(b"# foo\n[section]\n") self.assertEqual(ConfigFile({(b"section",): {}}), cf) def test_comment_after_section(self) -> None: cf = self.from_file(b"[section] # foo\n") self.assertEqual(ConfigFile({(b"section",): {}}), cf) def test_comment_after_variable(self) -> None: cf = self.from_file(b"[section]\nbar= foo # a comment\n") self.assertEqual(ConfigFile({(b"section",): {b"bar": b"foo"}}), cf) def test_comment_character_within_value_string(self) -> None: cf = self.from_file(b'[section]\nbar= "foo#bar"\n') self.assertEqual(ConfigFile({(b"section",): {b"bar": b"foo#bar"}}), cf) def test_comment_character_within_section_string(self) -> None: cf = self.from_file(b'[branch "foo#bar"] # a comment\nbar= foo\n') self.assertEqual(ConfigFile({(b"branch", b"foo#bar"): {b"bar": b"foo"}}), cf) def test_closing_bracket_within_section_string(self) -> None: cf = self.from_file(b'[branch "foo]bar"] # a comment\nbar= foo\n') self.assertEqual(ConfigFile({(b"branch", b"foo]bar"): {b"bar": b"foo"}}), cf) def test_from_file_section(self) -> None: cf = self.from_file(b"[core]\nfoo = bar\n") self.assertEqual(b"bar", cf.get((b"core",), b"foo")) self.assertEqual(b"bar", cf.get((b"core", b"foo"), b"foo")) def test_from_file_multiple(self) -> None: cf = self.from_file(b"[core]\nfoo = bar\nfoo = blah\n") self.assertEqual([b"bar", b"blah"], list(cf.get_multivar((b"core",), b"foo"))) self.assertEqual([], list(cf.get_multivar((b"core",), b"blah"))) def test_from_file_utf8_bom(self) -> None: text = "[core]\nfoo = b\u00e4r\n".encode("utf-8-sig") cf = self.from_file(text) self.assertEqual(b"b\xc3\xa4r", cf.get((b"core",), b"foo")) def test_from_file_section_case_insensitive_lower(self) -> None: cf = self.from_file(b"[cOre]\nfOo = bar\n") self.assertEqual(b"bar", cf.get((b"core",), b"foo")) self.assertEqual(b"bar", cf.get((b"core", b"foo"), b"foo")) def test_from_file_section_case_insensitive_mixed(self) -> None: cf = self.from_file(b"[cOre]\nfOo = bar\n") self.assertEqual(b"bar", cf.get((b"core",), b"fOo")) self.assertEqual(b"bar", cf.get((b"cOre", b"fOo"), b"fOo")) def test_from_file_with_mixed_quoted(self) -> None: cf = self.from_file(b'[core]\nfoo = "bar"la\n') self.assertEqual(b"barla", cf.get((b"core",), b"foo")) def test_from_file_section_with_open_brackets(self) -> None: self.assertRaises(ValueError, self.from_file, b"[core\nfoo = bar\n") def test_from_file_value_with_open_quoted(self) -> None: self.assertRaises(ValueError, self.from_file, b'[core]\nfoo = "bar\n') def test_from_file_with_quotes(self) -> None: cf = self.from_file(b"[core]\n" b'foo = " bar"\n') self.assertEqual(b" bar", cf.get((b"core",), b"foo")) def test_from_file_with_interrupted_line(self) -> None: cf = self.from_file(b"[core]\n" b"foo = bar\\\n" b" la\n") self.assertEqual(b"barla", cf.get((b"core",), b"foo")) def test_from_file_with_boolean_setting(self) -> None: cf = self.from_file(b"[core]\n" b"foo\n") self.assertEqual(b"true", cf.get((b"core",), b"foo")) def test_from_file_subsection(self) -> None: cf = self.from_file(b'[branch "foo"]\nfoo = bar\n') self.assertEqual(b"bar", cf.get((b"branch", b"foo"), b"foo")) def test_from_file_subsection_invalid(self) -> None: self.assertRaises(ValueError, self.from_file, b'[branch "foo]\nfoo = bar\n') def test_from_file_subsection_not_quoted(self) -> None: cf = self.from_file(b"[branch.foo]\nfoo = bar\n") self.assertEqual(b"bar", cf.get((b"branch", b"foo"), b"foo")) def test_write_preserve_multivar(self) -> None: cf = self.from_file(b"[core]\nfoo = bar\nfoo = blah\n") f = BytesIO() cf.write_to_file(f) self.assertEqual(b"[core]\n\tfoo = bar\n\tfoo = blah\n", f.getvalue()) def test_write_to_file_empty(self) -> None: c = ConfigFile() f = BytesIO() c.write_to_file(f) self.assertEqual(b"", f.getvalue()) def test_write_to_file_section(self) -> None: c = ConfigFile() c.set((b"core",), b"foo", b"bar") f = BytesIO() c.write_to_file(f) self.assertEqual(b"[core]\n\tfoo = bar\n", f.getvalue()) def test_write_to_file_subsection(self) -> None: c = ConfigFile() c.set((b"branch", b"blie"), b"foo", b"bar") f = BytesIO() c.write_to_file(f) self.assertEqual(b'[branch "blie"]\n\tfoo = bar\n', f.getvalue()) def test_same_line(self) -> None: cf = self.from_file(b"[branch.foo] foo = bar\n") self.assertEqual(b"bar", cf.get((b"branch", b"foo"), b"foo")) def test_quoted_newlines_windows(self) -> None: cf = self.from_file( b"[alias]\r\n" b"c = '!f() { \\\r\n" b' printf \'[git commit -m \\"%s\\"]\\n\' \\"$*\\" && \\\r\n' b' git commit -m \\"$*\\"; \\\r\n' b" }; f'\r\n" ) self.assertEqual(list(cf.sections()), [(b"alias",)]) self.assertEqual( b"'!f() { printf '[git commit -m \"%s\"]\n' " b'"$*" && git commit -m "$*"', cf.get((b"alias",), b"c"), ) def test_quoted(self) -> None: cf = self.from_file( b"""[gui] \tfontdiff = -family \\\"Ubuntu Mono\\\" -size 11 -overstrike 0 """ ) self.assertEqual( ConfigFile( { (b"gui",): { b"fontdiff": b'-family "Ubuntu Mono" -size 11 -overstrike 0', } } ), cf, ) def test_quoted_multiline(self) -> None: cf = self.from_file( b"""[alias] who = \"!who() {\\ git log --no-merges --pretty=format:'%an - %ae' $@ | uniq -c | sort -rn;\\ };\\ who\" """ ) self.assertEqual( ConfigFile( { (b"alias",): { b"who": ( b"!who() {git log --no-merges --pretty=format:'%an - " b"%ae' $@ | uniq -c | sort -rn;};who" ) } } ), cf, ) def test_set_hash_gets_quoted(self) -> None: c = ConfigFile() c.set(b"xandikos", b"color", b"#665544") f = BytesIO() c.write_to_file(f) self.assertEqual(b'[xandikos]\n\tcolor = "#665544"\n', f.getvalue()) class ConfigDictTests(TestCase): def test_get_set(self) -> None: cd = ConfigDict() self.assertRaises(KeyError, cd.get, b"foo", b"core") cd.set((b"core",), b"foo", b"bla") self.assertEqual(b"bla", cd.get((b"core",), b"foo")) cd.set((b"core",), b"foo", b"bloe") self.assertEqual(b"bloe", cd.get((b"core",), b"foo")) def test_get_boolean(self) -> None: cd = ConfigDict() cd.set((b"core",), b"foo", b"true") self.assertTrue(cd.get_boolean((b"core",), b"foo")) cd.set((b"core",), b"foo", b"false") self.assertFalse(cd.get_boolean((b"core",), b"foo")) cd.set((b"core",), b"foo", b"invalid") self.assertRaises(ValueError, cd.get_boolean, (b"core",), b"foo") def test_dict(self) -> None: cd = ConfigDict() cd.set((b"core",), b"foo", b"bla") cd.set((b"core2",), b"foo", b"bloe") self.assertEqual([(b"core",), (b"core2",)], list(cd.keys())) self.assertEqual(cd[(b"core",)], {b"foo": b"bla"}) cd[b"a"] = b"b" self.assertEqual(cd[b"a"], b"b") def test_items(self) -> None: cd = ConfigDict() cd.set((b"core",), b"foo", b"bla") cd.set((b"core2",), b"foo", b"bloe") self.assertEqual([(b"foo", b"bla")], list(cd.items((b"core",)))) def test_items_nonexistant(self) -> None: cd = ConfigDict() cd.set((b"core2",), b"foo", b"bloe") self.assertEqual([], list(cd.items((b"core",)))) def test_sections(self) -> None: cd = ConfigDict() cd.set((b"core2",), b"foo", b"bloe") self.assertEqual([(b"core2",)], list(cd.sections())) class StackedConfigTests(TestCase): def test_default_backends(self) -> None: StackedConfig.default_backends() @skipIf(sys.platform != "win32", "Windows specific config location.") def test_windows_config_from_path(self) -> None: from dulwich.config import get_win_system_paths install_dir = os.path.join("C:", "foo", "Git") self.overrideEnv("PATH", os.path.join(install_dir, "cmd")) with patch("os.path.exists", return_value=True): paths = set(get_win_system_paths()) self.assertEqual( { os.path.join(os.environ.get("PROGRAMDATA"), "Git", "config"), os.path.join(install_dir, "etc", "gitconfig"), }, paths, ) @skipIf(sys.platform != "win32", "Windows specific config location.") def test_windows_config_from_reg(self) -> None: import winreg from dulwich.config import get_win_system_paths self.overrideEnv("PATH", None) install_dir = os.path.join("C:", "foo", "Git") with patch("winreg.OpenKey"): with patch( "winreg.QueryValueEx", return_value=(install_dir, winreg.REG_SZ), ): paths = set(get_win_system_paths()) self.assertEqual( { os.path.join(os.environ.get("PROGRAMDATA"), "Git", "config"), os.path.join(install_dir, "etc", "gitconfig"), }, paths, ) class EscapeValueTests(TestCase): def test_nothing(self) -> None: self.assertEqual(b"foo", _escape_value(b"foo")) def test_backslash(self) -> None: self.assertEqual(b"foo\\\\", _escape_value(b"foo\\")) def test_newline(self) -> None: self.assertEqual(b"foo\\n", _escape_value(b"foo\n")) class FormatStringTests(TestCase): def test_quoted(self) -> None: self.assertEqual(b'" foo"', _format_string(b" foo")) self.assertEqual(b'"\\tfoo"', _format_string(b"\tfoo")) def test_not_quoted(self) -> None: self.assertEqual(b"foo", _format_string(b"foo")) self.assertEqual(b"foo bar", _format_string(b"foo bar")) class ParseStringTests(TestCase): def test_quoted(self) -> None: self.assertEqual(b" foo", _parse_string(b'" foo"')) self.assertEqual(b"\tfoo", _parse_string(b'"\\tfoo"')) def test_not_quoted(self) -> None: self.assertEqual(b"foo", _parse_string(b"foo")) self.assertEqual(b"foo bar", _parse_string(b"foo bar")) def test_nothing(self) -> None: self.assertEqual(b"", _parse_string(b"")) def test_tab(self) -> None: self.assertEqual(b"\tbar\t", _parse_string(b"\\tbar\\t")) def test_newline(self) -> None: self.assertEqual(b"\nbar\t", _parse_string(b"\\nbar\\t\t")) def test_quote(self) -> None: self.assertEqual(b'"foo"', _parse_string(b'\\"foo\\"')) class CheckVariableNameTests(TestCase): def test_invalid(self) -> None: self.assertFalse(_check_variable_name(b"foo ")) self.assertFalse(_check_variable_name(b"bar,bar")) self.assertFalse(_check_variable_name(b"bar.bar")) def test_valid(self) -> None: self.assertTrue(_check_variable_name(b"FOO")) self.assertTrue(_check_variable_name(b"foo")) self.assertTrue(_check_variable_name(b"foo-bar")) class CheckSectionNameTests(TestCase): def test_invalid(self) -> None: self.assertFalse(_check_section_name(b"foo ")) self.assertFalse(_check_section_name(b"bar,bar")) def test_valid(self) -> None: self.assertTrue(_check_section_name(b"FOO")) self.assertTrue(_check_section_name(b"foo")) self.assertTrue(_check_section_name(b"foo-bar")) self.assertTrue(_check_section_name(b"bar.bar")) class SubmodulesTests(TestCase): def testSubmodules(self) -> None: cf = ConfigFile.from_file( BytesIO( b"""\ [submodule "core/lib"] \tpath = core/lib \turl = https://github.com/phhusson/QuasselC.git """ ) ) got = list(parse_submodules(cf)) self.assertEqual( [ ( b"core/lib", b"https://github.com/phhusson/QuasselC.git", b"core/lib", ) ], got, ) def testMalformedSubmodules(self) -> None: cf = ConfigFile.from_file( BytesIO( b"""\ [submodule "core/lib"] \tpath = core/lib \turl = https://github.com/phhusson/QuasselC.git [submodule "dulwich"] \turl = https://github.com/jelmer/dulwich """ ) ) got = list(parse_submodules(cf)) self.assertEqual( [ ( b"core/lib", b"https://github.com/phhusson/QuasselC.git", b"core/lib", ) ], got, ) class ApplyInsteadOfTests(TestCase): def test_none(self) -> None: config = ConfigDict() self.assertEqual( "https://example.com/", apply_instead_of(config, "https://example.com/") ) def test_apply(self) -> None: config = ConfigDict() config.set(("url", "https://samba.org/"), "insteadOf", "https://example.com/") self.assertEqual( "https://samba.org/", apply_instead_of(config, "https://example.com/") ) def test_apply_multiple(self) -> None: config = ConfigDict() config.set(("url", "https://samba.org/"), "insteadOf", "https://blah.com/") config.set(("url", "https://samba.org/"), "insteadOf", "https://example.com/") self.assertEqual( [b"https://blah.com/", b"https://example.com/"], list(config.get_multivar(("url", "https://samba.org/"), "insteadOf")), ) self.assertEqual( "https://samba.org/", apply_instead_of(config, "https://example.com/") ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_credentials.py0000644000175100002000000000607214731042555017714 0ustar00runnerdocker# test_credentials.py -- tests for credentials.py # Copyright (C) 2022 Daniele Trifirò # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # from urllib.parse import urlparse from dulwich.config import ConfigDict from dulwich.credentials import ( match_partial_url, match_urls, urlmatch_credential_sections, ) from . import TestCase class TestCredentialHelpersUtils(TestCase): def test_match_urls(self) -> None: url = urlparse("https://github.com/jelmer/dulwich/") url_1 = urlparse("https://github.com/jelmer/dulwich") url_2 = urlparse("https://github.com/jelmer") url_3 = urlparse("https://github.com") self.assertTrue(match_urls(url, url_1)) self.assertTrue(match_urls(url, url_2)) self.assertTrue(match_urls(url, url_3)) non_matching = urlparse("https://git.sr.ht/") self.assertFalse(match_urls(url, non_matching)) def test_match_partial_url(self) -> None: url = urlparse("https://github.com/jelmer/dulwich/") self.assertTrue(match_partial_url(url, "github.com")) self.assertFalse(match_partial_url(url, "github.com/jelmer/")) self.assertTrue(match_partial_url(url, "github.com/jelmer/dulwich")) self.assertFalse(match_partial_url(url, "github.com/jel")) self.assertFalse(match_partial_url(url, "github.com/jel/")) def test_urlmatch_credential_sections(self) -> None: config = ConfigDict() config.set((b"credential", "https://github.com"), b"helper", "foo") config.set((b"credential", "git.sr.ht"), b"helper", "foo") config.set(b"credential", b"helper", "bar") self.assertEqual( list(urlmatch_credential_sections(config, "https://github.com")), [ (b"credential", b"https://github.com"), (b"credential",), ], ) self.assertEqual( list(urlmatch_credential_sections(config, "https://git.sr.ht")), [ (b"credential", b"git.sr.ht"), (b"credential",), ], ) self.assertEqual( list(urlmatch_credential_sections(config, "missing_url")), [(b"credential",)], ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_diff_tree.py0000644000175100002000000013061014731042555017342 0ustar00runnerdocker# test_diff_tree.py -- Tests for file and tree diff utilities. # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for file and tree diff utilities.""" from itertools import permutations from dulwich.diff_tree import ( CHANGE_COPY, CHANGE_MODIFY, CHANGE_RENAME, CHANGE_UNCHANGED, RenameDetector, TreeChange, _count_blocks, _count_blocks_py, _is_tree, _is_tree_py, _merge_entries, _merge_entries_py, _similarity_score, _tree_change_key, tree_changes, tree_changes_for_merge, ) from dulwich.index import commit_tree from dulwich.object_store import MemoryObjectStore from dulwich.objects import Blob, ShaFile, Tree, TreeEntry from dulwich.tests.utils import F, ext_functest_builder, functest_builder, make_object from . import TestCase class DiffTestCase(TestCase): def setUp(self) -> None: super().setUp() self.store = MemoryObjectStore() self.empty_tree = self.commit_tree([]) def commit_tree(self, entries): commit_blobs = [] for entry in entries: if len(entry) == 2: path, obj = entry mode = F else: path, obj, mode = entry if isinstance(obj, Blob): self.store.add_object(obj) sha = obj.id else: sha = obj commit_blobs.append((path, sha, mode)) return self.store[commit_tree(self.store, commit_blobs)] class TreeChangesTest(DiffTestCase): def setUp(self) -> None: super().setUp() self.detector = RenameDetector(self.store) def assertMergeFails(self, merge_entries, name, mode, sha) -> None: t = Tree() t[name] = (mode, sha) self.assertRaises((TypeError, ValueError), merge_entries, "", t, t) def _do_test_merge_entries(self, merge_entries) -> None: blob_a1 = make_object(Blob, data=b"a1") blob_a2 = make_object(Blob, data=b"a2") blob_b1 = make_object(Blob, data=b"b1") blob_c2 = make_object(Blob, data=b"c2") tree1 = self.commit_tree([(b"a", blob_a1, 0o100644), (b"b", blob_b1, 0o100755)]) tree2 = self.commit_tree([(b"a", blob_a2, 0o100644), (b"c", blob_c2, 0o100755)]) self.assertEqual([], merge_entries(b"", self.empty_tree, self.empty_tree)) self.assertEqual( [ ((None, None, None), (b"a", 0o100644, blob_a1.id)), ((None, None, None), (b"b", 0o100755, blob_b1.id)), ], merge_entries(b"", self.empty_tree, tree1), ) self.assertEqual( [ ((None, None, None), (b"x/a", 0o100644, blob_a1.id)), ((None, None, None), (b"x/b", 0o100755, blob_b1.id)), ], merge_entries(b"x", self.empty_tree, tree1), ) self.assertEqual( [ ((b"a", 0o100644, blob_a2.id), (None, None, None)), ((b"c", 0o100755, blob_c2.id), (None, None, None)), ], merge_entries(b"", tree2, self.empty_tree), ) self.assertEqual( [ ((b"a", 0o100644, blob_a1.id), (b"a", 0o100644, blob_a2.id)), ((b"b", 0o100755, blob_b1.id), (None, None, None)), ((None, None, None), (b"c", 0o100755, blob_c2.id)), ], merge_entries(b"", tree1, tree2), ) self.assertEqual( [ ((b"a", 0o100644, blob_a2.id), (b"a", 0o100644, blob_a1.id)), ((None, None, None), (b"b", 0o100755, blob_b1.id)), ((b"c", 0o100755, blob_c2.id), (None, None, None)), ], merge_entries(b"", tree2, tree1), ) self.assertMergeFails(merge_entries, 0xDEADBEEF, 0o100644, "1" * 40) self.assertMergeFails(merge_entries, b"a", b"deadbeef", "1" * 40) self.assertMergeFails(merge_entries, b"a", 0o100644, 0xDEADBEEF) test_merge_entries = functest_builder(_do_test_merge_entries, _merge_entries_py) test_merge_entries_extension = ext_functest_builder( _do_test_merge_entries, _merge_entries ) def _do_test_is_tree(self, is_tree) -> None: self.assertFalse(is_tree(TreeEntry(None, None, None))) self.assertFalse(is_tree(TreeEntry(b"a", 0o100644, b"a" * 40))) self.assertFalse(is_tree(TreeEntry(b"a", 0o100755, b"a" * 40))) self.assertFalse(is_tree(TreeEntry(b"a", 0o120000, b"a" * 40))) self.assertTrue(is_tree(TreeEntry(b"a", 0o040000, b"a" * 40))) self.assertRaises(TypeError, is_tree, TreeEntry(b"a", b"x", b"a" * 40)) self.assertRaises(AttributeError, is_tree, 1234) test_is_tree = functest_builder(_do_test_is_tree, _is_tree_py) test_is_tree_extension = ext_functest_builder(_do_test_is_tree, _is_tree) def assertChangesEqual(self, expected, tree1, tree2, **kwargs) -> None: actual = list(tree_changes(self.store, tree1.id, tree2.id, **kwargs)) self.assertEqual(expected, actual) # For brevity, the following tests use tuples instead of TreeEntry objects. def test_tree_changes_empty(self) -> None: self.assertChangesEqual([], self.empty_tree, self.empty_tree) def test_tree_changes_no_changes(self) -> None: blob = make_object(Blob, data=b"blob") tree = self.commit_tree([(b"a", blob), (b"b/c", blob)]) self.assertChangesEqual([], self.empty_tree, self.empty_tree) self.assertChangesEqual([], tree, tree) self.assertChangesEqual( [ TreeChange(CHANGE_UNCHANGED, (b"a", F, blob.id), (b"a", F, blob.id)), TreeChange( CHANGE_UNCHANGED, (b"b/c", F, blob.id), (b"b/c", F, blob.id), ), ], tree, tree, want_unchanged=True, ) def test_tree_changes_add_delete(self) -> None: blob_a = make_object(Blob, data=b"a") blob_b = make_object(Blob, data=b"b") tree = self.commit_tree([(b"a", blob_a, 0o100644), (b"x/b", blob_b, 0o100755)]) self.assertChangesEqual( [ TreeChange.add((b"a", 0o100644, blob_a.id)), TreeChange.add((b"x/b", 0o100755, blob_b.id)), ], self.empty_tree, tree, ) self.assertChangesEqual( [ TreeChange.delete((b"a", 0o100644, blob_a.id)), TreeChange.delete((b"x/b", 0o100755, blob_b.id)), ], tree, self.empty_tree, ) def test_tree_changes_modify_contents(self) -> None: blob_a1 = make_object(Blob, data=b"a1") blob_a2 = make_object(Blob, data=b"a2") tree1 = self.commit_tree([(b"a", blob_a1)]) tree2 = self.commit_tree([(b"a", blob_a2)]) self.assertChangesEqual( [TreeChange(CHANGE_MODIFY, (b"a", F, blob_a1.id), (b"a", F, blob_a2.id))], tree1, tree2, ) def test_tree_changes_modify_mode(self) -> None: blob_a = make_object(Blob, data=b"a") tree1 = self.commit_tree([(b"a", blob_a, 0o100644)]) tree2 = self.commit_tree([(b"a", blob_a, 0o100755)]) self.assertChangesEqual( [ TreeChange( CHANGE_MODIFY, (b"a", 0o100644, blob_a.id), (b"a", 0o100755, blob_a.id), ) ], tree1, tree2, ) def test_tree_changes_change_type(self) -> None: blob_a1 = make_object(Blob, data=b"a") blob_a2 = make_object(Blob, data=b"/foo/bar") tree1 = self.commit_tree([(b"a", blob_a1, 0o100644)]) tree2 = self.commit_tree([(b"a", blob_a2, 0o120000)]) self.assertChangesEqual( [ TreeChange.delete((b"a", 0o100644, blob_a1.id)), TreeChange.add((b"a", 0o120000, blob_a2.id)), ], tree1, tree2, ) def test_tree_changes_change_type_same(self) -> None: blob_a1 = make_object(Blob, data=b"a") blob_a2 = make_object(Blob, data=b"/foo/bar") tree1 = self.commit_tree([(b"a", blob_a1, 0o100644)]) tree2 = self.commit_tree([(b"a", blob_a2, 0o120000)]) self.assertChangesEqual( [ TreeChange( CHANGE_MODIFY, (b"a", 0o100644, blob_a1.id), (b"a", 0o120000, blob_a2.id), ) ], tree1, tree2, change_type_same=True, ) def test_tree_changes_to_tree(self) -> None: blob_a = make_object(Blob, data=b"a") blob_x = make_object(Blob, data=b"x") tree1 = self.commit_tree([(b"a", blob_a)]) tree2 = self.commit_tree([(b"a/x", blob_x)]) self.assertChangesEqual( [ TreeChange.delete((b"a", F, blob_a.id)), TreeChange.add((b"a/x", F, blob_x.id)), ], tree1, tree2, ) def test_tree_changes_complex(self) -> None: blob_a_1 = make_object(Blob, data=b"a1_1") blob_bx1_1 = make_object(Blob, data=b"bx1_1") blob_bx2_1 = make_object(Blob, data=b"bx2_1") blob_by1_1 = make_object(Blob, data=b"by1_1") blob_by2_1 = make_object(Blob, data=b"by2_1") tree1 = self.commit_tree( [ (b"a", blob_a_1), (b"b/x/1", blob_bx1_1), (b"b/x/2", blob_bx2_1), (b"b/y/1", blob_by1_1), (b"b/y/2", blob_by2_1), ] ) blob_a_2 = make_object(Blob, data=b"a1_2") blob_bx1_2 = blob_bx1_1 blob_by_2 = make_object(Blob, data=b"by_2") blob_c_2 = make_object(Blob, data=b"c_2") tree2 = self.commit_tree( [ (b"a", blob_a_2), (b"b/x/1", blob_bx1_2), (b"b/y", blob_by_2), (b"c", blob_c_2), ] ) self.assertChangesEqual( [ TreeChange( CHANGE_MODIFY, (b"a", F, blob_a_1.id), (b"a", F, blob_a_2.id), ), TreeChange.delete((b"b/x/2", F, blob_bx2_1.id)), TreeChange.add((b"b/y", F, blob_by_2.id)), TreeChange.delete((b"b/y/1", F, blob_by1_1.id)), TreeChange.delete((b"b/y/2", F, blob_by2_1.id)), TreeChange.add((b"c", F, blob_c_2.id)), ], tree1, tree2, ) def test_tree_changes_name_order(self) -> None: blob = make_object(Blob, data=b"a") tree1 = self.commit_tree([(b"a", blob), (b"a.", blob), (b"a..", blob)]) # Tree order is the reverse of this, so if we used tree order, 'a..' # would not be merged. tree2 = self.commit_tree([(b"a/x", blob), (b"a./x", blob), (b"a..", blob)]) self.assertChangesEqual( [ TreeChange.delete((b"a", F, blob.id)), TreeChange.add((b"a/x", F, blob.id)), TreeChange.delete((b"a.", F, blob.id)), TreeChange.add((b"a./x", F, blob.id)), ], tree1, tree2, ) def test_tree_changes_prune(self) -> None: blob_a1 = make_object(Blob, data=b"a1") blob_a2 = make_object(Blob, data=b"a2") blob_x = make_object(Blob, data=b"x") tree1 = self.commit_tree([(b"a", blob_a1), (b"b/x", blob_x)]) tree2 = self.commit_tree([(b"a", blob_a2), (b"b/x", blob_x)]) # Remove identical items so lookups will fail unless we prune. subtree = self.store[tree1[b"b"][1]] for entry in subtree.items(): del self.store[entry.sha] del self.store[subtree.id] self.assertChangesEqual( [TreeChange(CHANGE_MODIFY, (b"a", F, blob_a1.id), (b"a", F, blob_a2.id))], tree1, tree2, ) def test_tree_changes_rename_detector(self) -> None: blob_a1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob_a2 = make_object(Blob, data=b"a\nb\nc\ne\n") blob_b = make_object(Blob, data=b"b") tree1 = self.commit_tree([(b"a", blob_a1), (b"b", blob_b)]) tree2 = self.commit_tree([(b"c", blob_a2), (b"b", blob_b)]) detector = RenameDetector(self.store) self.assertChangesEqual( [ TreeChange.delete((b"a", F, blob_a1.id)), TreeChange.add((b"c", F, blob_a2.id)), ], tree1, tree2, ) self.assertChangesEqual( [ TreeChange.delete((b"a", F, blob_a1.id)), TreeChange( CHANGE_UNCHANGED, (b"b", F, blob_b.id), (b"b", F, blob_b.id), ), TreeChange.add((b"c", F, blob_a2.id)), ], tree1, tree2, want_unchanged=True, ) self.assertChangesEqual( [TreeChange(CHANGE_RENAME, (b"a", F, blob_a1.id), (b"c", F, blob_a2.id))], tree1, tree2, rename_detector=detector, ) self.assertChangesEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob_a1.id), (b"c", F, blob_a2.id)), TreeChange( CHANGE_UNCHANGED, (b"b", F, blob_b.id), (b"b", F, blob_b.id), ), ], tree1, tree2, rename_detector=detector, want_unchanged=True, ) def assertChangesForMergeEqual( self, expected, parent_trees, merge_tree, **kwargs ) -> None: parent_tree_ids = [t.id for t in parent_trees] actual = list( tree_changes_for_merge(self.store, parent_tree_ids, merge_tree.id, **kwargs) ) self.assertEqual(expected, actual) parent_tree_ids.reverse() expected = [list(reversed(cs)) for cs in expected] actual = list( tree_changes_for_merge(self.store, parent_tree_ids, merge_tree.id, **kwargs) ) self.assertEqual(expected, actual) def test_tree_changes_for_merge_add_no_conflict(self) -> None: blob = make_object(Blob, data=b"blob") parent1 = self.commit_tree([]) parent2 = merge = self.commit_tree([(b"a", blob)]) self.assertChangesForMergeEqual([], [parent1, parent2], merge) self.assertChangesForMergeEqual([], [parent2, parent2], merge) def test_tree_changes_for_merge_add_modify_conflict(self) -> None: blob1 = make_object(Blob, data=b"1") blob2 = make_object(Blob, data=b"2") parent1 = self.commit_tree([]) parent2 = self.commit_tree([(b"a", blob1)]) merge = self.commit_tree([(b"a", blob2)]) self.assertChangesForMergeEqual( [ [ TreeChange.add((b"a", F, blob2.id)), TreeChange(CHANGE_MODIFY, (b"a", F, blob1.id), (b"a", F, blob2.id)), ] ], [parent1, parent2], merge, ) def test_tree_changes_for_merge_modify_modify_conflict(self) -> None: blob1 = make_object(Blob, data=b"1") blob2 = make_object(Blob, data=b"2") blob3 = make_object(Blob, data=b"3") parent1 = self.commit_tree([(b"a", blob1)]) parent2 = self.commit_tree([(b"a", blob2)]) merge = self.commit_tree([(b"a", blob3)]) self.assertChangesForMergeEqual( [ [ TreeChange(CHANGE_MODIFY, (b"a", F, blob1.id), (b"a", F, blob3.id)), TreeChange(CHANGE_MODIFY, (b"a", F, blob2.id), (b"a", F, blob3.id)), ] ], [parent1, parent2], merge, ) def test_tree_changes_for_merge_modify_no_conflict(self) -> None: blob1 = make_object(Blob, data=b"1") blob2 = make_object(Blob, data=b"2") parent1 = self.commit_tree([(b"a", blob1)]) parent2 = merge = self.commit_tree([(b"a", blob2)]) self.assertChangesForMergeEqual([], [parent1, parent2], merge) def test_tree_changes_for_merge_delete_delete_conflict(self) -> None: blob1 = make_object(Blob, data=b"1") blob2 = make_object(Blob, data=b"2") parent1 = self.commit_tree([(b"a", blob1)]) parent2 = self.commit_tree([(b"a", blob2)]) merge = self.commit_tree([]) self.assertChangesForMergeEqual( [ [ TreeChange.delete((b"a", F, blob1.id)), TreeChange.delete((b"a", F, blob2.id)), ] ], [parent1, parent2], merge, ) def test_tree_changes_for_merge_delete_no_conflict(self) -> None: blob = make_object(Blob, data=b"blob") has = self.commit_tree([(b"a", blob)]) doesnt_have = self.commit_tree([]) self.assertChangesForMergeEqual([], [has, has], doesnt_have) self.assertChangesForMergeEqual([], [has, doesnt_have], doesnt_have) def test_tree_changes_for_merge_octopus_no_conflict(self) -> None: r = list(range(5)) blobs = [make_object(Blob, data=bytes(i)) for i in r] parents = [self.commit_tree([(b"a", blobs[i])]) for i in r] for i in r: # Take the SHA from each of the parents. self.assertChangesForMergeEqual([], parents, parents[i]) def test_tree_changes_for_merge_octopus_modify_conflict(self) -> None: # Because the octopus merge strategy is limited, I doubt it's possible # to create this with the git command line. But the output is well- # defined, so test it anyway. r = list(range(5)) parent_blobs = [make_object(Blob, data=bytes(i)) for i in r] merge_blob = make_object(Blob, data=b"merge") parents = [self.commit_tree([(b"a", parent_blobs[i])]) for i in r] merge = self.commit_tree([(b"a", merge_blob)]) expected = [ [ TreeChange( CHANGE_MODIFY, (b"a", F, parent_blobs[i].id), (b"a", F, merge_blob.id), ) for i in r ] ] self.assertChangesForMergeEqual(expected, parents, merge) def test_tree_changes_for_merge_octopus_delete(self) -> None: blob1 = make_object(Blob, data=b"1") blob2 = make_object(Blob, data=b"3") parent1 = self.commit_tree([(b"a", blob1)]) parent2 = self.commit_tree([(b"a", blob2)]) parent3 = merge = self.commit_tree([]) self.assertChangesForMergeEqual([], [parent1, parent1, parent1], merge) self.assertChangesForMergeEqual([], [parent1, parent1, parent3], merge) self.assertChangesForMergeEqual([], [parent1, parent3, parent3], merge) self.assertChangesForMergeEqual( [ [ TreeChange.delete((b"a", F, blob1.id)), TreeChange.delete((b"a", F, blob2.id)), None, ] ], [parent1, parent2, parent3], merge, ) def test_tree_changes_for_merge_add_add_same_conflict(self) -> None: blob = make_object(Blob, data=b"a\nb\nc\nd\n") parent1 = self.commit_tree([(b"a", blob)]) parent2 = self.commit_tree([]) merge = self.commit_tree([(b"b", blob)]) add = TreeChange.add((b"b", F, blob.id)) self.assertChangesForMergeEqual([[add, add]], [parent1, parent2], merge) def test_tree_changes_for_merge_add_exact_rename_conflict(self) -> None: blob = make_object(Blob, data=b"a\nb\nc\nd\n") parent1 = self.commit_tree([(b"a", blob)]) parent2 = self.commit_tree([]) merge = self.commit_tree([(b"b", blob)]) self.assertChangesForMergeEqual( [ [ TreeChange(CHANGE_RENAME, (b"a", F, blob.id), (b"b", F, blob.id)), TreeChange.add((b"b", F, blob.id)), ] ], [parent1, parent2], merge, rename_detector=self.detector, ) def test_tree_changes_for_merge_add_content_rename_conflict(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob2 = make_object(Blob, data=b"a\nb\nc\ne\n") parent1 = self.commit_tree([(b"a", blob1)]) parent2 = self.commit_tree([]) merge = self.commit_tree([(b"b", blob2)]) self.assertChangesForMergeEqual( [ [ TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"b", F, blob2.id)), TreeChange.add((b"b", F, blob2.id)), ] ], [parent1, parent2], merge, rename_detector=self.detector, ) def test_tree_changes_for_merge_modify_rename_conflict(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob2 = make_object(Blob, data=b"a\nb\nc\ne\n") parent1 = self.commit_tree([(b"a", blob1)]) parent2 = self.commit_tree([(b"b", blob1)]) merge = self.commit_tree([(b"b", blob2)]) self.assertChangesForMergeEqual( [ [ TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"b", F, blob2.id)), TreeChange(CHANGE_MODIFY, (b"b", F, blob1.id), (b"b", F, blob2.id)), ] ], [parent1, parent2], merge, rename_detector=self.detector, ) class RenameDetectionTest(DiffTestCase): def _do_test_count_blocks(self, count_blocks) -> None: blob = make_object(Blob, data=b"a\nb\na\n") self.assertBlockCountEqual({b"a\n": 4, b"b\n": 2}, count_blocks(blob)) test_count_blocks = functest_builder(_do_test_count_blocks, _count_blocks_py) test_count_blocks_extension = ext_functest_builder( _do_test_count_blocks, _count_blocks ) def _do_test_count_blocks_no_newline(self, count_blocks) -> None: blob = make_object(Blob, data=b"a\na") self.assertBlockCountEqual({b"a\n": 2, b"a": 1}, _count_blocks(blob)) test_count_blocks_no_newline = functest_builder( _do_test_count_blocks_no_newline, _count_blocks_py ) test_count_blocks_no_newline_extension = ext_functest_builder( _do_test_count_blocks_no_newline, _count_blocks ) def assertBlockCountEqual(self, expected, got) -> None: self.assertEqual( {(hash(block) & 0xFFFFFFFF): count for (block, count) in expected.items()}, {(block & 0xFFFFFFFF): count for (block, count) in got.items()}, ) def _do_test_count_blocks_chunks(self, count_blocks) -> None: blob = ShaFile.from_raw_chunks(Blob.type_num, [b"a\nb", b"\na\n"]) self.assertBlockCountEqual({b"a\n": 4, b"b\n": 2}, _count_blocks(blob)) test_count_blocks_chunks = functest_builder( _do_test_count_blocks_chunks, _count_blocks_py ) test_count_blocks_chunks_extension = ext_functest_builder( _do_test_count_blocks_chunks, _count_blocks ) def _do_test_count_blocks_long_lines(self, count_blocks) -> None: a = b"a" * 64 data = a + b"xxx\ny\n" + a + b"zzz\n" blob = make_object(Blob, data=data) self.assertBlockCountEqual( {b"a" * 64: 128, b"xxx\n": 4, b"y\n": 2, b"zzz\n": 4}, _count_blocks(blob), ) test_count_blocks_long_lines = functest_builder( _do_test_count_blocks_long_lines, _count_blocks_py ) test_count_blocks_long_lines_extension = ext_functest_builder( _do_test_count_blocks_long_lines, _count_blocks ) def assertSimilar(self, expected_score, blob1, blob2) -> None: self.assertEqual(expected_score, _similarity_score(blob1, blob2)) self.assertEqual(expected_score, _similarity_score(blob2, blob1)) def test_similarity_score(self) -> None: blob0 = make_object(Blob, data=b"") blob1 = make_object(Blob, data=b"ab\ncd\ncd\n") blob2 = make_object(Blob, data=b"ab\n") blob3 = make_object(Blob, data=b"cd\n") blob4 = make_object(Blob, data=b"cd\ncd\n") self.assertSimilar(100, blob0, blob0) self.assertSimilar(0, blob0, blob1) self.assertSimilar(33, blob1, blob2) self.assertSimilar(33, blob1, blob3) self.assertSimilar(66, blob1, blob4) self.assertSimilar(0, blob2, blob3) self.assertSimilar(50, blob3, blob4) def test_similarity_score_cache(self) -> None: blob1 = make_object(Blob, data=b"ab\ncd\n") blob2 = make_object(Blob, data=b"ab\n") block_cache = {} self.assertEqual(50, _similarity_score(blob1, blob2, block_cache=block_cache)) self.assertEqual({blob1.id, blob2.id}, set(block_cache)) def fail_chunks() -> None: self.fail("Unexpected call to as_raw_chunks()") blob1.as_raw_chunks = blob2.as_raw_chunks = fail_chunks blob1.raw_length = lambda: 6 blob2.raw_length = lambda: 3 self.assertEqual(50, _similarity_score(blob1, blob2, block_cache=block_cache)) def test_tree_entry_sort(self) -> None: sha = "abcd" * 10 expected_entries = [ TreeChange.add(TreeEntry(b"aaa", F, sha)), TreeChange( CHANGE_COPY, TreeEntry(b"bbb", F, sha), TreeEntry(b"aab", F, sha), ), TreeChange( CHANGE_MODIFY, TreeEntry(b"bbb", F, sha), TreeEntry(b"bbb", F, b"dabc" * 10), ), TreeChange( CHANGE_RENAME, TreeEntry(b"bbc", F, sha), TreeEntry(b"ddd", F, sha), ), TreeChange.delete(TreeEntry(b"ccc", F, sha)), ] for perm in permutations(expected_entries): self.assertEqual(expected_entries, sorted(perm, key=_tree_change_key)) def detect_renames(self, tree1, tree2, want_unchanged=False, **kwargs): detector = RenameDetector(self.store, **kwargs) return detector.changes_with_renames( tree1.id, tree2.id, want_unchanged=want_unchanged ) def test_no_renames(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob2 = make_object(Blob, data=b"a\nb\ne\nf\n") blob3 = make_object(Blob, data=b"a\nb\ng\nh\n") tree1 = self.commit_tree([(b"a", blob1), (b"b", blob2)]) tree2 = self.commit_tree([(b"a", blob1), (b"b", blob3)]) self.assertEqual( [TreeChange(CHANGE_MODIFY, (b"b", F, blob2.id), (b"b", F, blob3.id))], self.detect_renames(tree1, tree2), ) def test_exact_rename_one_to_one(self) -> None: blob1 = make_object(Blob, data=b"1") blob2 = make_object(Blob, data=b"2") tree1 = self.commit_tree([(b"a", blob1), (b"b", blob2)]) tree2 = self.commit_tree([(b"c", blob1), (b"d", blob2)]) self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"c", F, blob1.id)), TreeChange(CHANGE_RENAME, (b"b", F, blob2.id), (b"d", F, blob2.id)), ], self.detect_renames(tree1, tree2), ) def test_exact_rename_split_different_type(self) -> None: blob = make_object(Blob, data=b"/foo") tree1 = self.commit_tree([(b"a", blob, 0o100644)]) tree2 = self.commit_tree([(b"a", blob, 0o120000)]) self.assertEqual( [ TreeChange.add((b"a", 0o120000, blob.id)), TreeChange.delete((b"a", 0o100644, blob.id)), ], self.detect_renames(tree1, tree2), ) def test_exact_rename_and_different_type(self) -> None: blob1 = make_object(Blob, data=b"1") blob2 = make_object(Blob, data=b"2") tree1 = self.commit_tree([(b"a", blob1)]) tree2 = self.commit_tree([(b"a", blob2, 0o120000), (b"b", blob1)]) self.assertEqual( [ TreeChange.add((b"a", 0o120000, blob2.id)), TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"b", F, blob1.id)), ], self.detect_renames(tree1, tree2), ) def test_exact_rename_one_to_many(self) -> None: blob = make_object(Blob, data=b"1") tree1 = self.commit_tree([(b"a", blob)]) tree2 = self.commit_tree([(b"b", blob), (b"c", blob)]) self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob.id), (b"b", F, blob.id)), TreeChange(CHANGE_COPY, (b"a", F, blob.id), (b"c", F, blob.id)), ], self.detect_renames(tree1, tree2), ) def test_exact_rename_many_to_one(self) -> None: blob = make_object(Blob, data=b"1") tree1 = self.commit_tree([(b"a", blob), (b"b", blob)]) tree2 = self.commit_tree([(b"c", blob)]) self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob.id), (b"c", F, blob.id)), TreeChange.delete((b"b", F, blob.id)), ], self.detect_renames(tree1, tree2), ) def test_exact_rename_many_to_many(self) -> None: blob = make_object(Blob, data=b"1") tree1 = self.commit_tree([(b"a", blob), (b"b", blob)]) tree2 = self.commit_tree([(b"c", blob), (b"d", blob), (b"e", blob)]) self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob.id), (b"c", F, blob.id)), TreeChange(CHANGE_COPY, (b"a", F, blob.id), (b"e", F, blob.id)), TreeChange(CHANGE_RENAME, (b"b", F, blob.id), (b"d", F, blob.id)), ], self.detect_renames(tree1, tree2), ) def test_exact_copy_modify(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob2 = make_object(Blob, data=b"a\nb\nc\ne\n") tree1 = self.commit_tree([(b"a", blob1)]) tree2 = self.commit_tree([(b"a", blob2), (b"b", blob1)]) self.assertEqual( [ TreeChange(CHANGE_MODIFY, (b"a", F, blob1.id), (b"a", F, blob2.id)), TreeChange(CHANGE_COPY, (b"a", F, blob1.id), (b"b", F, blob1.id)), ], self.detect_renames(tree1, tree2), ) def test_exact_copy_change_mode(self) -> None: blob = make_object(Blob, data=b"a\nb\nc\nd\n") tree1 = self.commit_tree([(b"a", blob)]) tree2 = self.commit_tree([(b"a", blob, 0o100755), (b"b", blob)]) self.assertEqual( [ TreeChange( CHANGE_MODIFY, (b"a", F, blob.id), (b"a", 0o100755, blob.id), ), TreeChange(CHANGE_COPY, (b"a", F, blob.id), (b"b", F, blob.id)), ], self.detect_renames(tree1, tree2), ) def test_rename_threshold(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\n") blob2 = make_object(Blob, data=b"a\nb\nd\n") tree1 = self.commit_tree([(b"a", blob1)]) tree2 = self.commit_tree([(b"b", blob2)]) self.assertEqual( [TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"b", F, blob2.id))], self.detect_renames(tree1, tree2, rename_threshold=50), ) self.assertEqual( [ TreeChange.delete((b"a", F, blob1.id)), TreeChange.add((b"b", F, blob2.id)), ], self.detect_renames(tree1, tree2, rename_threshold=75), ) def test_content_rename_max_files(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\nd") blob4 = make_object(Blob, data=b"a\nb\nc\ne\n") blob2 = make_object(Blob, data=b"e\nf\ng\nh\n") blob3 = make_object(Blob, data=b"e\nf\ng\ni\n") tree1 = self.commit_tree([(b"a", blob1), (b"b", blob2)]) tree2 = self.commit_tree([(b"c", blob3), (b"d", blob4)]) self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"d", F, blob4.id)), TreeChange(CHANGE_RENAME, (b"b", F, blob2.id), (b"c", F, blob3.id)), ], self.detect_renames(tree1, tree2), ) self.assertEqual( [ TreeChange.delete((b"a", F, blob1.id)), TreeChange.delete((b"b", F, blob2.id)), TreeChange.add((b"c", F, blob3.id)), TreeChange.add((b"d", F, blob4.id)), ], self.detect_renames(tree1, tree2, max_files=1), ) def test_content_rename_one_to_one(self) -> None: b11 = make_object(Blob, data=b"a\nb\nc\nd\n") b12 = make_object(Blob, data=b"a\nb\nc\ne\n") b21 = make_object(Blob, data=b"e\nf\ng\n\nh") b22 = make_object(Blob, data=b"e\nf\ng\n\ni") tree1 = self.commit_tree([(b"a", b11), (b"b", b21)]) tree2 = self.commit_tree([(b"c", b12), (b"d", b22)]) self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, b11.id), (b"c", F, b12.id)), TreeChange(CHANGE_RENAME, (b"b", F, b21.id), (b"d", F, b22.id)), ], self.detect_renames(tree1, tree2), ) def test_content_rename_one_to_one_ordering(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\nd\ne\nf\n") blob2 = make_object(Blob, data=b"a\nb\nc\nd\ng\nh\n") # 6/10 match to blob1, 8/10 match to blob2 blob3 = make_object(Blob, data=b"a\nb\nc\nd\ng\ni\n") tree1 = self.commit_tree([(b"a", blob1), (b"b", blob2)]) tree2 = self.commit_tree([(b"c", blob3)]) self.assertEqual( [ TreeChange.delete((b"a", F, blob1.id)), TreeChange(CHANGE_RENAME, (b"b", F, blob2.id), (b"c", F, blob3.id)), ], self.detect_renames(tree1, tree2), ) tree3 = self.commit_tree([(b"a", blob2), (b"b", blob1)]) tree4 = self.commit_tree([(b"c", blob3)]) self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob2.id), (b"c", F, blob3.id)), TreeChange.delete((b"b", F, blob1.id)), ], self.detect_renames(tree3, tree4), ) def test_content_rename_one_to_many(self) -> None: blob1 = make_object(Blob, data=b"aa\nb\nc\nd\ne\n") blob2 = make_object(Blob, data=b"ab\nb\nc\nd\ne\n") # 8/11 match blob3 = make_object(Blob, data=b"aa\nb\nc\nd\nf\n") # 9/11 match tree1 = self.commit_tree([(b"a", blob1)]) tree2 = self.commit_tree([(b"b", blob2), (b"c", blob3)]) self.assertEqual( [ TreeChange(CHANGE_COPY, (b"a", F, blob1.id), (b"b", F, blob2.id)), TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"c", F, blob3.id)), ], self.detect_renames(tree1, tree2), ) def test_content_rename_many_to_one(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob2 = make_object(Blob, data=b"a\nb\nc\ne\n") blob3 = make_object(Blob, data=b"a\nb\nc\nf\n") tree1 = self.commit_tree([(b"a", blob1), (b"b", blob2)]) tree2 = self.commit_tree([(b"c", blob3)]) self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"c", F, blob3.id)), TreeChange.delete((b"b", F, blob2.id)), ], self.detect_renames(tree1, tree2), ) def test_content_rename_many_to_many(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob2 = make_object(Blob, data=b"a\nb\nc\ne\n") blob3 = make_object(Blob, data=b"a\nb\nc\nf\n") blob4 = make_object(Blob, data=b"a\nb\nc\ng\n") tree1 = self.commit_tree([(b"a", blob1), (b"b", blob2)]) tree2 = self.commit_tree([(b"c", blob3), (b"d", blob4)]) # TODO(dborowitz): Distribute renames rather than greedily choosing # copies. self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"c", F, blob3.id)), TreeChange(CHANGE_COPY, (b"a", F, blob1.id), (b"d", F, blob4.id)), TreeChange.delete((b"b", F, blob2.id)), ], self.detect_renames(tree1, tree2), ) def test_content_rename_with_more_deletions(self) -> None: blob1 = make_object(Blob, data=b"") tree1 = self.commit_tree( [(b"a", blob1), (b"b", blob1), (b"c", blob1), (b"d", blob1)] ) tree2 = self.commit_tree([(b"e", blob1), (b"f", blob1), (b"g", blob1)]) self.maxDiff = None self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"e", F, blob1.id)), TreeChange(CHANGE_RENAME, (b"b", F, blob1.id), (b"f", F, blob1.id)), TreeChange(CHANGE_RENAME, (b"c", F, blob1.id), (b"g", F, blob1.id)), TreeChange.delete((b"d", F, blob1.id)), ], self.detect_renames(tree1, tree2), ) def test_content_rename_gitlink(self) -> None: blob1 = make_object(Blob, data=b"blob1") blob2 = make_object(Blob, data=b"blob2") link1 = b"1" * 40 link2 = b"2" * 40 tree1 = self.commit_tree([(b"a", blob1), (b"b", link1, 0o160000)]) tree2 = self.commit_tree([(b"c", blob2), (b"d", link2, 0o160000)]) self.assertEqual( [ TreeChange.delete((b"a", 0o100644, blob1.id)), TreeChange.delete((b"b", 0o160000, link1)), TreeChange.add((b"c", 0o100644, blob2.id)), TreeChange.add((b"d", 0o160000, link2)), ], self.detect_renames(tree1, tree2), ) def test_exact_rename_swap(self) -> None: blob1 = make_object(Blob, data=b"1") blob2 = make_object(Blob, data=b"2") tree1 = self.commit_tree([(b"a", blob1), (b"b", blob2)]) tree2 = self.commit_tree([(b"a", blob2), (b"b", blob1)]) self.assertEqual( [ TreeChange(CHANGE_MODIFY, (b"a", F, blob1.id), (b"a", F, blob2.id)), TreeChange(CHANGE_MODIFY, (b"b", F, blob2.id), (b"b", F, blob1.id)), ], self.detect_renames(tree1, tree2), ) self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"b", F, blob1.id)), TreeChange(CHANGE_RENAME, (b"b", F, blob2.id), (b"a", F, blob2.id)), ], self.detect_renames(tree1, tree2, rewrite_threshold=50), ) def test_content_rename_swap(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob2 = make_object(Blob, data=b"e\nf\ng\nh\n") blob3 = make_object(Blob, data=b"a\nb\nc\ne\n") blob4 = make_object(Blob, data=b"e\nf\ng\ni\n") tree1 = self.commit_tree([(b"a", blob1), (b"b", blob2)]) tree2 = self.commit_tree([(b"a", blob4), (b"b", blob3)]) self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"b", F, blob3.id)), TreeChange(CHANGE_RENAME, (b"b", F, blob2.id), (b"a", F, blob4.id)), ], self.detect_renames(tree1, tree2, rewrite_threshold=60), ) def test_rewrite_threshold(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob2 = make_object(Blob, data=b"a\nb\nc\ne\n") blob3 = make_object(Blob, data=b"a\nb\nf\ng\n") tree1 = self.commit_tree([(b"a", blob1)]) tree2 = self.commit_tree([(b"a", blob3), (b"b", blob2)]) no_renames = [ TreeChange(CHANGE_MODIFY, (b"a", F, blob1.id), (b"a", F, blob3.id)), TreeChange(CHANGE_COPY, (b"a", F, blob1.id), (b"b", F, blob2.id)), ] self.assertEqual(no_renames, self.detect_renames(tree1, tree2)) self.assertEqual( no_renames, self.detect_renames(tree1, tree2, rewrite_threshold=40) ) self.assertEqual( [ TreeChange.add((b"a", F, blob3.id)), TreeChange(CHANGE_RENAME, (b"a", F, blob1.id), (b"b", F, blob2.id)), ], self.detect_renames(tree1, tree2, rewrite_threshold=80), ) def test_find_copies_harder_exact(self) -> None: blob = make_object(Blob, data=b"blob") tree1 = self.commit_tree([(b"a", blob)]) tree2 = self.commit_tree([(b"a", blob), (b"b", blob)]) self.assertEqual( [TreeChange.add((b"b", F, blob.id))], self.detect_renames(tree1, tree2), ) self.assertEqual( [TreeChange(CHANGE_COPY, (b"a", F, blob.id), (b"b", F, blob.id))], self.detect_renames(tree1, tree2, find_copies_harder=True), ) def test_find_copies_harder_content(self) -> None: blob1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob2 = make_object(Blob, data=b"a\nb\nc\ne\n") tree1 = self.commit_tree([(b"a", blob1)]) tree2 = self.commit_tree([(b"a", blob1), (b"b", blob2)]) self.assertEqual( [TreeChange.add((b"b", F, blob2.id))], self.detect_renames(tree1, tree2), ) self.assertEqual( [TreeChange(CHANGE_COPY, (b"a", F, blob1.id), (b"b", F, blob2.id))], self.detect_renames(tree1, tree2, find_copies_harder=True), ) def test_find_copies_harder_with_rewrites(self) -> None: blob_a1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob_a2 = make_object(Blob, data=b"f\ng\nh\ni\n") blob_b2 = make_object(Blob, data=b"a\nb\nc\ne\n") tree1 = self.commit_tree([(b"a", blob_a1)]) tree2 = self.commit_tree([(b"a", blob_a2), (b"b", blob_b2)]) self.assertEqual( [ TreeChange(CHANGE_MODIFY, (b"a", F, blob_a1.id), (b"a", F, blob_a2.id)), TreeChange(CHANGE_COPY, (b"a", F, blob_a1.id), (b"b", F, blob_b2.id)), ], self.detect_renames(tree1, tree2, find_copies_harder=True), ) self.assertEqual( [ TreeChange.add((b"a", F, blob_a2.id)), TreeChange(CHANGE_RENAME, (b"a", F, blob_a1.id), (b"b", F, blob_b2.id)), ], self.detect_renames( tree1, tree2, rewrite_threshold=50, find_copies_harder=True ), ) def test_reuse_detector(self) -> None: blob = make_object(Blob, data=b"blob") tree1 = self.commit_tree([(b"a", blob)]) tree2 = self.commit_tree([(b"b", blob)]) detector = RenameDetector(self.store) changes = [TreeChange(CHANGE_RENAME, (b"a", F, blob.id), (b"b", F, blob.id))] self.assertEqual(changes, detector.changes_with_renames(tree1.id, tree2.id)) self.assertEqual(changes, detector.changes_with_renames(tree1.id, tree2.id)) def test_want_unchanged(self) -> None: blob_a1 = make_object(Blob, data=b"a\nb\nc\nd\n") blob_b = make_object(Blob, data=b"b") blob_c2 = make_object(Blob, data=b"a\nb\nc\ne\n") tree1 = self.commit_tree([(b"a", blob_a1), (b"b", blob_b)]) tree2 = self.commit_tree([(b"c", blob_c2), (b"b", blob_b)]) self.assertEqual( [TreeChange(CHANGE_RENAME, (b"a", F, blob_a1.id), (b"c", F, blob_c2.id))], self.detect_renames(tree1, tree2), ) self.assertEqual( [ TreeChange(CHANGE_RENAME, (b"a", F, blob_a1.id), (b"c", F, blob_c2.id)), TreeChange( CHANGE_UNCHANGED, (b"b", F, blob_b.id), (b"b", F, blob_b.id), ), ], self.detect_renames(tree1, tree2, want_unchanged=True), ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_fastexport.py0000644000175100002000000002421414731042555017614 0ustar00runnerdocker# test_fastexport.py -- Fast export/import functionality # Copyright (C) 2010 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # import stat from io import BytesIO from dulwich.object_store import MemoryObjectStore from dulwich.objects import ZERO_SHA, Blob, Commit, Tree from dulwich.repo import MemoryRepo from dulwich.tests.utils import build_commit_graph from . import SkipTest, TestCase class GitFastExporterTests(TestCase): """Tests for the GitFastExporter tests.""" def setUp(self) -> None: super().setUp() self.store = MemoryObjectStore() self.stream = BytesIO() try: from dulwich.fastexport import GitFastExporter except ImportError as exc: raise SkipTest("python-fastimport not available") from exc self.fastexporter = GitFastExporter(self.stream, self.store) def test_emit_blob(self) -> None: b = Blob() b.data = b"fooBAR" self.fastexporter.emit_blob(b) self.assertEqual(b"blob\nmark :1\ndata 6\nfooBAR\n", self.stream.getvalue()) def test_emit_commit(self) -> None: b = Blob() b.data = b"FOO" t = Tree() t.add(b"foo", stat.S_IFREG | 0o644, b.id) c = Commit() c.committer = c.author = b"Jelmer " c.author_time = c.commit_time = 1271345553 c.author_timezone = c.commit_timezone = 0 c.message = b"msg" c.tree = t.id self.store.add_objects([(b, None), (t, None), (c, None)]) self.fastexporter.emit_commit(c, b"refs/heads/master") self.assertEqual( b"""blob mark :1 data 3 FOO commit refs/heads/master mark :2 author Jelmer 1271345553 +0000 committer Jelmer 1271345553 +0000 data 3 msg M 644 :1 foo """, self.stream.getvalue(), ) class GitImportProcessorTests(TestCase): """Tests for the GitImportProcessor tests.""" def setUp(self) -> None: super().setUp() self.repo = MemoryRepo() try: from dulwich.fastexport import GitImportProcessor except ImportError as exc: raise SkipTest("python-fastimport not available") from exc self.processor = GitImportProcessor(self.repo) def test_reset_handler(self) -> None: from fastimport import commands [c1] = build_commit_graph(self.repo.object_store, [[1]]) cmd = commands.ResetCommand(b"refs/heads/foo", c1.id) self.processor.reset_handler(cmd) self.assertEqual(c1.id, self.repo.get_refs()[b"refs/heads/foo"]) self.assertEqual(c1.id, self.processor.last_commit) def test_reset_handler_marker(self) -> None: from fastimport import commands [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]]) self.processor.markers[b"10"] = c1.id cmd = commands.ResetCommand(b"refs/heads/foo", b":10") self.processor.reset_handler(cmd) self.assertEqual(c1.id, self.repo.get_refs()[b"refs/heads/foo"]) def test_reset_handler_default(self) -> None: from fastimport import commands [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]]) cmd = commands.ResetCommand(b"refs/heads/foo", None) self.processor.reset_handler(cmd) self.assertEqual(ZERO_SHA, self.repo.get_refs()[b"refs/heads/foo"]) def test_commit_handler(self) -> None: from fastimport import commands cmd = commands.CommitCommand( b"refs/heads/foo", b"mrkr", (b"Jelmer", b"jelmer@samba.org", 432432432.0, 3600), (b"Jelmer", b"jelmer@samba.org", 432432432.0, 3600), b"FOO", None, [], [], ) self.processor.commit_handler(cmd) commit = self.repo[self.processor.last_commit] self.assertEqual(b"Jelmer ", commit.author) self.assertEqual(b"Jelmer ", commit.committer) self.assertEqual(b"FOO", commit.message) self.assertEqual([], commit.parents) self.assertEqual(432432432.0, commit.commit_time) self.assertEqual(432432432.0, commit.author_time) self.assertEqual(3600, commit.commit_timezone) self.assertEqual(3600, commit.author_timezone) self.assertEqual(commit, self.repo[b"refs/heads/foo"]) def test_commit_handler_markers(self) -> None: from fastimport import commands [c1, c2, c3] = build_commit_graph(self.repo.object_store, [[1], [2], [3]]) self.processor.markers[b"10"] = c1.id self.processor.markers[b"42"] = c2.id self.processor.markers[b"98"] = c3.id cmd = commands.CommitCommand( b"refs/heads/foo", b"mrkr", (b"Jelmer", b"jelmer@samba.org", 432432432.0, 3600), (b"Jelmer", b"jelmer@samba.org", 432432432.0, 3600), b"FOO", b":10", [b":42", b":98"], [], ) self.processor.commit_handler(cmd) commit = self.repo[self.processor.last_commit] self.assertEqual(c1.id, commit.parents[0]) self.assertEqual(c2.id, commit.parents[1]) self.assertEqual(c3.id, commit.parents[2]) def test_import_stream(self) -> None: markers = self.processor.import_stream( BytesIO( b"""blob mark :1 data 11 text for a commit refs/heads/master mark :2 committer Joe Foo 1288287382 +0000 data 20 M 100644 :1 a """ ) ) self.assertEqual(2, len(markers)) self.assertIsInstance(self.repo[markers[b"1"]], Blob) self.assertIsInstance(self.repo[markers[b"2"]], Commit) def test_file_add(self) -> None: from fastimport import commands cmd = commands.BlobCommand(b"23", b"data") self.processor.blob_handler(cmd) cmd = commands.CommitCommand( b"refs/heads/foo", b"mrkr", (b"Jelmer", b"jelmer@samba.org", 432432432.0, 3600), (b"Jelmer", b"jelmer@samba.org", 432432432.0, 3600), b"FOO", None, [], [commands.FileModifyCommand(b"path", 0o100644, b":23", None)], ) self.processor.commit_handler(cmd) commit = self.repo[self.processor.last_commit] self.assertEqual( [(b"path", 0o100644, b"6320cd248dd8aeaab759d5871f8781b5c0505172")], self.repo[commit.tree].items(), ) def simple_commit(self): from fastimport import commands cmd = commands.BlobCommand(b"23", b"data") self.processor.blob_handler(cmd) cmd = commands.CommitCommand( b"refs/heads/foo", b"mrkr", (b"Jelmer", b"jelmer@samba.org", 432432432.0, 3600), (b"Jelmer", b"jelmer@samba.org", 432432432.0, 3600), b"FOO", None, [], [commands.FileModifyCommand(b"path", 0o100644, b":23", None)], ) self.processor.commit_handler(cmd) commit = self.repo[self.processor.last_commit] return commit def make_file_commit(self, file_cmds): """Create a trivial commit with the specified file commands. Args: file_cmds: File commands to run. Returns: The created commit object """ from fastimport import commands cmd = commands.CommitCommand( b"refs/heads/foo", b"mrkr", (b"Jelmer", b"jelmer@samba.org", 432432432.0, 3600), (b"Jelmer", b"jelmer@samba.org", 432432432.0, 3600), b"FOO", None, [], file_cmds, ) self.processor.commit_handler(cmd) return self.repo[self.processor.last_commit] def test_file_copy(self) -> None: from fastimport import commands self.simple_commit() commit = self.make_file_commit([commands.FileCopyCommand(b"path", b"new_path")]) self.assertEqual( [ ( b"new_path", 0o100644, b"6320cd248dd8aeaab759d5871f8781b5c0505172", ), ( b"path", 0o100644, b"6320cd248dd8aeaab759d5871f8781b5c0505172", ), ], self.repo[commit.tree].items(), ) def test_file_move(self) -> None: from fastimport import commands self.simple_commit() commit = self.make_file_commit( [commands.FileRenameCommand(b"path", b"new_path")] ) self.assertEqual( [ ( b"new_path", 0o100644, b"6320cd248dd8aeaab759d5871f8781b5c0505172", ), ], self.repo[commit.tree].items(), ) def test_file_delete(self) -> None: from fastimport import commands self.simple_commit() commit = self.make_file_commit([commands.FileDeleteCommand(b"path")]) self.assertEqual([], self.repo[commit.tree].items()) def test_file_deleteall(self) -> None: from fastimport import commands self.simple_commit() commit = self.make_file_commit([commands.FileDeleteAllCommand()]) self.assertEqual([], self.repo[commit.tree].items()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_file.py0000644000175100002000000001441114731042555016332 0ustar00runnerdocker# test_file.py -- Test for git files # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # import io import os import shutil import sys import tempfile from dulwich.file import FileLocked, GitFile, _fancy_rename from . import SkipTest, TestCase class FancyRenameTests(TestCase): def setUp(self) -> None: super().setUp() self._tempdir = tempfile.mkdtemp() self.foo = self.path("foo") self.bar = self.path("bar") self.create(self.foo, b"foo contents") def tearDown(self) -> None: shutil.rmtree(self._tempdir) super().tearDown() def path(self, filename): return os.path.join(self._tempdir, filename) def create(self, path, contents) -> None: f = open(path, "wb") f.write(contents) f.close() def test_no_dest_exists(self) -> None: self.assertFalse(os.path.exists(self.bar)) _fancy_rename(self.foo, self.bar) self.assertFalse(os.path.exists(self.foo)) new_f = open(self.bar, "rb") self.assertEqual(b"foo contents", new_f.read()) new_f.close() def test_dest_exists(self) -> None: self.create(self.bar, b"bar contents") _fancy_rename(self.foo, self.bar) self.assertFalse(os.path.exists(self.foo)) new_f = open(self.bar, "rb") self.assertEqual(b"foo contents", new_f.read()) new_f.close() def test_dest_opened(self) -> None: if sys.platform != "win32": raise SkipTest("platform allows overwriting open files") self.create(self.bar, b"bar contents") dest_f = open(self.bar, "rb") self.assertRaises(OSError, _fancy_rename, self.foo, self.bar) dest_f.close() self.assertTrue(os.path.exists(self.path("foo"))) new_f = open(self.foo, "rb") self.assertEqual(b"foo contents", new_f.read()) new_f.close() new_f = open(self.bar, "rb") self.assertEqual(b"bar contents", new_f.read()) new_f.close() class GitFileTests(TestCase): def setUp(self) -> None: super().setUp() self._tempdir = tempfile.mkdtemp() f = open(self.path("foo"), "wb") f.write(b"foo contents") f.close() def tearDown(self) -> None: shutil.rmtree(self._tempdir) super().tearDown() def path(self, filename): return os.path.join(self._tempdir, filename) def test_invalid(self) -> None: foo = self.path("foo") self.assertRaises(IOError, GitFile, foo, mode="r") self.assertRaises(IOError, GitFile, foo, mode="ab") self.assertRaises(IOError, GitFile, foo, mode="r+b") self.assertRaises(IOError, GitFile, foo, mode="w+b") self.assertRaises(IOError, GitFile, foo, mode="a+bU") def test_readonly(self) -> None: f = GitFile(self.path("foo"), "rb") self.assertIsInstance(f, io.IOBase) self.assertEqual(b"foo contents", f.read()) self.assertEqual(b"", f.read()) f.seek(4) self.assertEqual(b"contents", f.read()) f.close() def test_default_mode(self) -> None: f = GitFile(self.path("foo")) self.assertEqual(b"foo contents", f.read()) f.close() def test_write(self) -> None: foo = self.path("foo") foo_lock = f"{foo}.lock" orig_f = open(foo, "rb") self.assertEqual(orig_f.read(), b"foo contents") orig_f.close() self.assertFalse(os.path.exists(foo_lock)) f = GitFile(foo, "wb") self.assertFalse(f.closed) self.assertRaises(AttributeError, getattr, f, "not_a_file_property") self.assertTrue(os.path.exists(foo_lock)) f.write(b"new stuff") f.seek(4) f.write(b"contents") f.close() self.assertFalse(os.path.exists(foo_lock)) new_f = open(foo, "rb") self.assertEqual(b"new contents", new_f.read()) new_f.close() def test_open_twice(self) -> None: foo = self.path("foo") f1 = GitFile(foo, "wb") f1.write(b"new") try: f2 = GitFile(foo, "wb") self.fail() except FileLocked: pass else: f2.close() f1.write(b" contents") f1.close() # Ensure trying to open twice doesn't affect original. f = open(foo, "rb") self.assertEqual(b"new contents", f.read()) f.close() def test_abort(self) -> None: foo = self.path("foo") foo_lock = f"{foo}.lock" orig_f = open(foo, "rb") self.assertEqual(orig_f.read(), b"foo contents") orig_f.close() f = GitFile(foo, "wb") f.write(b"new contents") f.abort() self.assertTrue(f.closed) self.assertFalse(os.path.exists(foo_lock)) new_orig_f = open(foo, "rb") self.assertEqual(new_orig_f.read(), b"foo contents") new_orig_f.close() def test_abort_close(self) -> None: foo = self.path("foo") f = GitFile(foo, "wb") f.abort() try: f.close() except OSError: self.fail() f = GitFile(foo, "wb") f.close() try: f.abort() except OSError: self.fail() def test_abort_close_removed(self) -> None: foo = self.path("foo") f = GitFile(foo, "wb") f._file.close() os.remove(foo + ".lock") f.abort() self.assertTrue(f._closed) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_grafts.py0000644000175100002000000001500614731042555016702 0ustar00runnerdocker# test_grafts.py -- Tests for graftpoints # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for graftpoints.""" import os import shutil import tempfile from dulwich.errors import ObjectFormatException from dulwich.objects import Tree from dulwich.repo import MemoryRepo, Repo, parse_graftpoints, serialize_graftpoints from . import TestCase def makesha(digit): return (str(digit).encode("ascii") * 40)[:40] class GraftParserTests(TestCase): def assertParse(self, expected, graftpoints) -> None: self.assertEqual(expected, parse_graftpoints(iter(graftpoints))) def test_no_grafts(self) -> None: self.assertParse({}, []) def test_no_parents(self) -> None: self.assertParse({makesha(0): []}, [makesha(0)]) def test_parents(self) -> None: self.assertParse( {makesha(0): [makesha(1), makesha(2)]}, [b" ".join([makesha(0), makesha(1), makesha(2)])], ) def test_multiple_hybrid(self) -> None: self.assertParse( { makesha(0): [], makesha(1): [makesha(2)], makesha(3): [makesha(4), makesha(5)], }, [ makesha(0), b" ".join([makesha(1), makesha(2)]), b" ".join([makesha(3), makesha(4), makesha(5)]), ], ) class GraftSerializerTests(TestCase): def assertSerialize(self, expected, graftpoints) -> None: self.assertEqual(sorted(expected), sorted(serialize_graftpoints(graftpoints))) def test_no_grafts(self) -> None: self.assertSerialize(b"", {}) def test_no_parents(self) -> None: self.assertSerialize(makesha(0), {makesha(0): []}) def test_parents(self) -> None: self.assertSerialize( b" ".join([makesha(0), makesha(1), makesha(2)]), {makesha(0): [makesha(1), makesha(2)]}, ) def test_multiple_hybrid(self) -> None: self.assertSerialize( b"\n".join( [ makesha(0), b" ".join([makesha(1), makesha(2)]), b" ".join([makesha(3), makesha(4), makesha(5)]), ] ), { makesha(0): [], makesha(1): [makesha(2)], makesha(3): [makesha(4), makesha(5)], }, ) class GraftsInRepositoryBase: def tearDown(self) -> None: super().tearDown() def get_repo_with_grafts(self, grafts): r = self._repo r._add_graftpoints(grafts) return r def test_no_grafts(self) -> None: r = self.get_repo_with_grafts({}) shas = [e.commit.id for e in r.get_walker()] self.assertEqual(shas, self._shas[::-1]) def test_no_parents_graft(self) -> None: r = self.get_repo_with_grafts({self._repo.head(): []}) self.assertEqual([e.commit.id for e in r.get_walker()], [r.head()]) def test_existing_parent_graft(self) -> None: r = self.get_repo_with_grafts({self._shas[-1]: [self._shas[0]]}) self.assertEqual( [e.commit.id for e in r.get_walker()], [self._shas[-1], self._shas[0]], ) def test_remove_graft(self) -> None: r = self.get_repo_with_grafts({self._repo.head(): []}) r._remove_graftpoints([self._repo.head()]) self.assertEqual([e.commit.id for e in r.get_walker()], self._shas[::-1]) def test_object_store_fail_invalid_parents(self) -> None: r = self._repo self.assertRaises( ObjectFormatException, r._add_graftpoints, {self._shas[-1]: ["1"]} ) class GraftsInRepoTests(GraftsInRepositoryBase, TestCase): def setUp(self) -> None: super().setUp() self._repo_dir = os.path.join(tempfile.mkdtemp()) r = self._repo = Repo.init(self._repo_dir) self.addCleanup(shutil.rmtree, self._repo_dir) self._shas = [] commit_kwargs = { "committer": b"Test Committer ", "author": b"Test Author ", "commit_timestamp": 12395, "commit_timezone": 0, "author_timestamp": 12395, "author_timezone": 0, } self._shas.append(r.do_commit(b"empty commit", **commit_kwargs)) self._shas.append(r.do_commit(b"empty commit", **commit_kwargs)) self._shas.append(r.do_commit(b"empty commit", **commit_kwargs)) def test_init_with_empty_info_grafts(self) -> None: r = self._repo r._put_named_file(os.path.join("info", "grafts"), b"") r = Repo(self._repo_dir) self.assertEqual({}, r._graftpoints) def test_init_with_info_grafts(self) -> None: r = self._repo r._put_named_file( os.path.join("info", "grafts"), self._shas[-1] + b" " + self._shas[0], ) r = Repo(self._repo_dir) self.assertEqual({self._shas[-1]: [self._shas[0]]}, r._graftpoints) class GraftsInMemoryRepoTests(GraftsInRepositoryBase, TestCase): def setUp(self) -> None: super().setUp() r = self._repo = MemoryRepo() self._shas = [] tree = Tree() commit_kwargs = { "committer": b"Test Committer ", "author": b"Test Author ", "commit_timestamp": 12395, "commit_timezone": 0, "author_timestamp": 12395, "author_timezone": 0, "tree": tree.id, } self._shas.append(r.do_commit(b"empty commit", **commit_kwargs)) self._shas.append(r.do_commit(b"empty commit", **commit_kwargs)) self._shas.append(r.do_commit(b"empty commit", **commit_kwargs)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_graph.py0000644000175100002000000001563714731042555016527 0ustar00runnerdocker# test_graph.py -- Tests for merge base # Copyright (c) 2020 Kevin B. Hendricks, Stratford Ontario Canada # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. """Tests for dulwich.graph.""" from dulwich.graph import WorkList, _find_lcas, can_fast_forward from dulwich.repo import MemoryRepo from dulwich.tests.utils import make_commit from . import TestCase class FindMergeBaseTests(TestCase): @staticmethod def run_test(dag, inputs): def lookup_parents(commit_id): return dag[commit_id] def lookup_stamp(commit_id) -> int: # any constant timestamp value here will work to force # this test to test the same behaviour as done previously return 100 c1 = inputs[0] c2s = inputs[1:] return set(_find_lcas(lookup_parents, c1, c2s, lookup_stamp)) def test_multiple_lca(self) -> None: # two lowest common ancestors graph = { "5": ["1", "2"], "4": ["3", "1"], "3": ["2"], "2": ["0"], "1": [], "0": [], } self.assertEqual(self.run_test(graph, ["4", "5"]), {"1", "2"}) def test_no_common_ancestor(self) -> None: # no common ancestor graph = { "4": ["2"], "3": ["1"], "2": [], "1": ["0"], "0": [], } self.assertEqual(self.run_test(graph, ["4", "3"]), set()) def test_ancestor(self) -> None: # ancestor graph = { "G": ["D", "F"], "F": ["E"], "D": ["C"], "C": ["B"], "E": ["B"], "B": ["A"], "A": [], } self.assertEqual(self.run_test(graph, ["D", "C"]), {"C"}) def test_direct_parent(self) -> None: # parent graph = { "G": ["D", "F"], "F": ["E"], "D": ["C"], "C": ["B"], "E": ["B"], "B": ["A"], "A": [], } self.assertEqual(self.run_test(graph, ["G", "D"]), {"D"}) def test_another_crossover(self) -> None: # Another cross over graph = { "G": ["D", "F"], "F": ["E", "C"], "D": ["C", "E"], "C": ["B"], "E": ["B"], "B": ["A"], "A": [], } self.assertEqual(self.run_test(graph, ["D", "F"]), {"E", "C"}) def test_three_way_merge_lca(self) -> None: # three way merge commit straight from git docs graph = { "C": ["C1"], "C1": ["C2"], "C2": ["C3"], "C3": ["C4"], "C4": ["2"], "B": ["B1"], "B1": ["B2"], "B2": ["B3"], "B3": ["1"], "A": ["A1"], "A1": ["A2"], "A2": ["A3"], "A3": ["1"], "1": ["2"], "2": [], } # assumes a theoretical merge M exists that merges B and C first # which actually means find the first LCA from either of B OR C with A self.assertEqual(self.run_test(graph, ["A", "B", "C"]), {"1"}) def test_octopus(self) -> None: # octopus algorithm test # test straight from git docs of A, B, and C # but this time use octopus to find lcas of A, B, and C simultaneously graph = { "C": ["C1"], "C1": ["C2"], "C2": ["C3"], "C3": ["C4"], "C4": ["2"], "B": ["B1"], "B1": ["B2"], "B2": ["B3"], "B3": ["1"], "A": ["A1"], "A1": ["A2"], "A2": ["A3"], "A3": ["1"], "1": ["2"], "2": [], } def lookup_parents(cid): return graph[cid] def lookup_stamp(commit_id) -> int: # any constant timestamp value here will work to force # this test to test the same behaviour as done previously return 100 lcas = ["A"] others = ["B", "C"] for cmt in others: next_lcas = [] for ca in lcas: res = _find_lcas(lookup_parents, cmt, [ca], lookup_stamp) next_lcas.extend(res) lcas = next_lcas[:] self.assertEqual(set(lcas), {"2"}) class CanFastForwardTests(TestCase): def test_ff(self) -> None: r = MemoryRepo() base = make_commit() c1 = make_commit(parents=[base.id]) c2 = make_commit(parents=[c1.id]) r.object_store.add_objects([(base, None), (c1, None), (c2, None)]) self.assertTrue(can_fast_forward(r, c1.id, c1.id)) self.assertTrue(can_fast_forward(r, base.id, c1.id)) self.assertTrue(can_fast_forward(r, c1.id, c2.id)) self.assertFalse(can_fast_forward(r, c2.id, c1.id)) def test_diverged(self) -> None: r = MemoryRepo() base = make_commit() c1 = make_commit(parents=[base.id]) c2a = make_commit(parents=[c1.id], message=b"2a") c2b = make_commit(parents=[c1.id], message=b"2b") r.object_store.add_objects([(base, None), (c1, None), (c2a, None), (c2b, None)]) self.assertTrue(can_fast_forward(r, c1.id, c2a.id)) self.assertTrue(can_fast_forward(r, c1.id, c2b.id)) self.assertFalse(can_fast_forward(r, c2a.id, c2b.id)) self.assertFalse(can_fast_forward(r, c2b.id, c2a.id)) class WorkListTest(TestCase): def test_WorkList(self) -> None: # tuples of (timestamp, value) are stored in a Priority MaxQueue # repeated use of get should return them in maxheap timestamp # order: largest time value (most recent in time) first then earlier/older wlst = WorkList() wlst.add((100, "Test Value 1")) wlst.add((50, "Test Value 2")) wlst.add((200, "Test Value 3")) self.assertEqual(wlst.get(), (200, "Test Value 3")) self.assertEqual(wlst.get(), (100, "Test Value 1")) wlst.add((150, "Test Value 4")) self.assertEqual(wlst.get(), (150, "Test Value 4")) self.assertEqual(wlst.get(), (50, "Test Value 2")) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_greenthreads.py0000644000175100002000000000605314731042555020071 0ustar00runnerdocker# test_greenthreads.py -- Unittests for eventlet. # Copyright (C) 2013 eNovance SAS # # Author: Fabien Boucher # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # import time from dulwich.object_store import MemoryObjectStore from dulwich.objects import Blob, Commit, Tree, parse_timezone from . import TestCase, skipIf try: import gevent # noqa: F401 gevent_support = True except ImportError: gevent_support = False if gevent_support: from dulwich.greenthreads import GreenThreadsMissingObjectFinder skipmsg = "Gevent library is not installed" def create_commit(marker=None): blob = Blob.from_string(b"The blob content " + marker) tree = Tree() tree.add(b"thefile " + marker, 0o100644, blob.id) cmt = Commit() cmt.tree = tree.id cmt.author = cmt.committer = b"John Doe " cmt.message = marker tz = parse_timezone(b"-0200")[0] cmt.commit_time = cmt.author_time = int(time.time()) cmt.commit_timezone = cmt.author_timezone = tz return cmt, tree, blob def init_store(store, count=1): ret = [] for i in range(count): objs = create_commit(marker=str(i).encode("ascii")) for obj in objs: ret.append(obj) store.add_object(obj) return ret @skipIf(not gevent_support, skipmsg) class TestGreenThreadsMissingObjectFinder(TestCase): def setUp(self) -> None: super().setUp() self.store = MemoryObjectStore() self.cmt_amount = 10 self.objs = init_store(self.store, self.cmt_amount) def test_finder(self) -> None: wants = [sha.id for sha in self.objs if isinstance(sha, Commit)] finder = GreenThreadsMissingObjectFinder(self.store, (), wants) self.assertEqual(len(finder.sha_done), 0) self.assertEqual(len(finder.objects_to_send), self.cmt_amount) finder = GreenThreadsMissingObjectFinder( self.store, wants[0 : int(self.cmt_amount / 2)], wants ) # sha_done will contains commit id and sha of blob referred in tree self.assertEqual(len(finder.sha_done), (self.cmt_amount / 2) * 2) self.assertEqual(len(finder.objects_to_send), self.cmt_amount / 2) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_hooks.py0000644000175100002000000001320314731042555016534 0ustar00runnerdocker# test_hooks.py -- Tests for executing hooks # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for executing hooks.""" import os import shutil import stat import sys import tempfile from dulwich import errors from dulwich.hooks import CommitMsgShellHook, PostCommitShellHook, PreCommitShellHook from . import TestCase class ShellHookTests(TestCase): def setUp(self) -> None: super().setUp() if os.name != "posix": self.skipTest("shell hook tests requires POSIX shell") self.assertTrue(os.path.exists("/bin/sh")) def test_hook_pre_commit(self) -> None: repo_dir = os.path.join(tempfile.mkdtemp()) os.mkdir(os.path.join(repo_dir, "hooks")) self.addCleanup(shutil.rmtree, repo_dir) pre_commit_fail = """#!/bin/sh exit 1 """ pre_commit_success = """#!/bin/sh exit 0 """ pre_commit_cwd = ( """#!/bin/sh if [ "$(pwd)" != '""" + repo_dir + """' ]; then echo "Expected path '""" + repo_dir + """', got '$(pwd)'" exit 1 fi exit 0 """ ) pre_commit = os.path.join(repo_dir, "hooks", "pre-commit") hook = PreCommitShellHook(repo_dir, repo_dir) with open(pre_commit, "w") as f: f.write(pre_commit_fail) os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) self.assertRaises(errors.HookError, hook.execute) if sys.platform != "darwin": # Don't bother running this test on darwin since path # canonicalization messages with our simple string comparison. with open(pre_commit, "w") as f: f.write(pre_commit_cwd) os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) hook.execute() with open(pre_commit, "w") as f: f.write(pre_commit_success) os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) hook.execute() def test_hook_commit_msg(self) -> None: repo_dir = os.path.join(tempfile.mkdtemp()) os.mkdir(os.path.join(repo_dir, "hooks")) self.addCleanup(shutil.rmtree, repo_dir) commit_msg_fail = """#!/bin/sh exit 1 """ commit_msg_success = """#!/bin/sh exit 0 """ commit_msg_cwd = ( """#!/bin/sh if [ "$(pwd)" = '""" + repo_dir + "' ]; then exit 0; else exit 1; fi\n" ) commit_msg = os.path.join(repo_dir, "hooks", "commit-msg") hook = CommitMsgShellHook(repo_dir) with open(commit_msg, "w") as f: f.write(commit_msg_fail) os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) self.assertRaises(errors.HookError, hook.execute, b"failed commit") if sys.platform != "darwin": # Don't bother running this test on darwin since path # canonicalization messages with our simple string comparison. with open(commit_msg, "w") as f: f.write(commit_msg_cwd) os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) hook.execute(b"cwd test commit") with open(commit_msg, "w") as f: f.write(commit_msg_success) os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) hook.execute(b"empty commit") def test_hook_post_commit(self) -> None: (fd, path) = tempfile.mkstemp() os.close(fd) repo_dir = os.path.join(tempfile.mkdtemp()) os.mkdir(os.path.join(repo_dir, "hooks")) self.addCleanup(shutil.rmtree, repo_dir) post_commit_success = ( """#!/bin/sh rm """ + path + "\n" ) post_commit_fail = """#!/bin/sh exit 1 """ post_commit_cwd = ( """#!/bin/sh if [ "$(pwd)" = '""" + repo_dir + "' ]; then exit 0; else exit 1; fi\n" ) post_commit = os.path.join(repo_dir, "hooks", "post-commit") hook = PostCommitShellHook(repo_dir) with open(post_commit, "w") as f: f.write(post_commit_fail) os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) self.assertRaises(errors.HookError, hook.execute) if sys.platform != "darwin": # Don't bother running this test on darwin since path # canonicalization messages with our simple string comparison. with open(post_commit, "w") as f: f.write(post_commit_cwd) os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) hook.execute() with open(post_commit, "w") as f: f.write(post_commit_success) os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) hook.execute() self.assertFalse(os.path.exists(path)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_ignore.py0000644000175100002000000002421714731042555016703 0ustar00runnerdocker# test_ignore.py -- Tests for ignore files. # Copyright (C) 2017 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for ignore files.""" import os import re import shutil import tempfile from io import BytesIO from dulwich.ignore import ( IgnoreFilter, IgnoreFilterManager, IgnoreFilterStack, Pattern, match_pattern, read_ignore_patterns, translate, ) from dulwich.repo import Repo from . import TestCase POSITIVE_MATCH_TESTS = [ (b"foo.c", b"*.c"), (b".c", b"*.c"), (b"foo/foo.c", b"*.c"), (b"foo/foo.c", b"foo.c"), (b"foo.c", b"/*.c"), (b"foo.c", b"/foo.c"), (b"foo.c", b"foo.c"), (b"foo.c", b"foo.[ch]"), (b"foo/bar/bla.c", b"foo/**"), (b"foo/bar/bla/blie.c", b"foo/**/blie.c"), (b"foo/bar/bla.c", b"**/bla.c"), (b"bla.c", b"**/bla.c"), (b"foo/bar", b"foo/**/bar"), (b"foo/bla/bar", b"foo/**/bar"), (b"foo/bar/", b"bar/"), (b"foo/bar/", b"bar"), (b"foo/bar/something", b"foo/bar/*"), ] NEGATIVE_MATCH_TESTS = [ (b"foo.c", b"foo.[dh]"), (b"foo/foo.c", b"/foo.c"), (b"foo/foo.c", b"/*.c"), (b"foo/bar/", b"/bar/"), (b"foo/bar/", b"foo/bar/*"), (b"foo/bar", b"foo?bar"), ] TRANSLATE_TESTS = [ (b"*.c", b"(?ms)(.*/)?[^/]*\\.c/?\\Z"), (b"foo.c", b"(?ms)(.*/)?foo\\.c/?\\Z"), (b"/*.c", b"(?ms)[^/]*\\.c/?\\Z"), (b"/foo.c", b"(?ms)foo\\.c/?\\Z"), (b"foo.c", b"(?ms)(.*/)?foo\\.c/?\\Z"), (b"foo.[ch]", b"(?ms)(.*/)?foo\\.[ch]/?\\Z"), (b"bar/", b"(?ms)(.*/)?bar\\/\\Z"), (b"foo/**", b"(?ms)foo(/.*)?/?\\Z"), (b"foo/**/blie.c", b"(?ms)foo(/.*)?\\/blie\\.c/?\\Z"), (b"**/bla.c", b"(?ms)(.*/)?bla\\.c/?\\Z"), (b"foo/**/bar", b"(?ms)foo(/.*)?\\/bar/?\\Z"), (b"foo/bar/*", b"(?ms)foo\\/bar\\/[^/]+/?\\Z"), (b"/foo\\[bar\\]", b"(?ms)foo\\[bar\\]/?\\Z"), (b"/foo[bar]", b"(?ms)foo[bar]/?\\Z"), (b"/foo[0-9]", b"(?ms)foo[0-9]/?\\Z"), ] class TranslateTests(TestCase): def test_translate(self) -> None: for pattern, regex in TRANSLATE_TESTS: if re.escape(b"/") == b"/": # Slash is no longer escaped in Python3.7, so undo the escaping # in the expected return value.. regex = regex.replace(b"\\/", b"/") self.assertEqual( regex, translate(pattern), f"orig pattern: {pattern!r}, regex: {translate(pattern)!r}, expected: {regex!r}", ) class ReadIgnorePatterns(TestCase): def test_read_file(self) -> None: f = BytesIO( b""" # a comment \x20\x20 # and an empty line: \\#not a comment !negative with trailing whitespace with escaped trailing whitespace\\ """ ) self.assertEqual( list(read_ignore_patterns(f)), [ b"\\#not a comment", b"!negative", b"with trailing whitespace", b"with escaped trailing whitespace ", ], ) class MatchPatternTests(TestCase): def test_matches(self) -> None: for path, pattern in POSITIVE_MATCH_TESTS: self.assertTrue( match_pattern(path, pattern), f"path: {path!r}, pattern: {pattern!r}", ) def test_no_matches(self) -> None: for path, pattern in NEGATIVE_MATCH_TESTS: self.assertFalse( match_pattern(path, pattern), f"path: {path!r}, pattern: {pattern!r}", ) class IgnoreFilterTests(TestCase): def test_included(self) -> None: filter = IgnoreFilter([b"a.c", b"b.c"]) self.assertTrue(filter.is_ignored(b"a.c")) self.assertIs(None, filter.is_ignored(b"c.c")) self.assertEqual([Pattern(b"a.c")], list(filter.find_matching(b"a.c"))) self.assertEqual([], list(filter.find_matching(b"c.c"))) def test_included_ignorecase(self) -> None: filter = IgnoreFilter([b"a.c", b"b.c"], ignorecase=False) self.assertTrue(filter.is_ignored(b"a.c")) self.assertFalse(filter.is_ignored(b"A.c")) filter = IgnoreFilter([b"a.c", b"b.c"], ignorecase=True) self.assertTrue(filter.is_ignored(b"a.c")) self.assertTrue(filter.is_ignored(b"A.c")) self.assertTrue(filter.is_ignored(b"A.C")) def test_excluded(self) -> None: filter = IgnoreFilter([b"a.c", b"b.c", b"!c.c"]) self.assertFalse(filter.is_ignored(b"c.c")) self.assertIs(None, filter.is_ignored(b"d.c")) self.assertEqual([Pattern(b"!c.c")], list(filter.find_matching(b"c.c"))) self.assertEqual([], list(filter.find_matching(b"d.c"))) def test_include_exclude_include(self) -> None: filter = IgnoreFilter([b"a.c", b"!a.c", b"a.c"]) self.assertTrue(filter.is_ignored(b"a.c")) self.assertEqual( [Pattern(b"a.c"), Pattern(b"!a.c"), Pattern(b"a.c")], list(filter.find_matching(b"a.c")), ) def test_manpage(self) -> None: # A specific example from the gitignore manpage filter = IgnoreFilter([b"/*", b"!/foo", b"/foo/*", b"!/foo/bar"]) self.assertTrue(filter.is_ignored(b"a.c")) self.assertTrue(filter.is_ignored(b"foo/blie")) self.assertFalse(filter.is_ignored(b"foo")) self.assertFalse(filter.is_ignored(b"foo/bar")) self.assertFalse(filter.is_ignored(b"foo/bar/")) self.assertFalse(filter.is_ignored(b"foo/bar/bloe")) def test_regex_special(self) -> None: # See https://github.com/dulwich/dulwich/issues/930#issuecomment-1026166429 filter = IgnoreFilter([b"/foo\\[bar\\]", b"/foo"]) self.assertTrue(filter.is_ignored("foo")) self.assertTrue(filter.is_ignored("foo[bar]")) class IgnoreFilterStackTests(TestCase): def test_stack_first(self) -> None: filter1 = IgnoreFilter([b"[a].c", b"[b].c", b"![d].c"]) filter2 = IgnoreFilter([b"[a].c", b"![b],c", b"[c].c", b"[d].c"]) stack = IgnoreFilterStack([filter1, filter2]) self.assertIs(True, stack.is_ignored(b"a.c")) self.assertIs(True, stack.is_ignored(b"b.c")) self.assertIs(True, stack.is_ignored(b"c.c")) self.assertIs(False, stack.is_ignored(b"d.c")) self.assertIs(None, stack.is_ignored(b"e.c")) class IgnoreFilterManagerTests(TestCase): def test_load_ignore(self) -> None: tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) repo = Repo.init(tmp_dir) with open(os.path.join(repo.path, ".gitignore"), "wb") as f: f.write(b"/foo/bar\n") f.write(b"/dir2\n") f.write(b"/dir3/\n") os.mkdir(os.path.join(repo.path, "dir")) with open(os.path.join(repo.path, "dir", ".gitignore"), "wb") as f: f.write(b"/blie\n") with open(os.path.join(repo.path, "dir", "blie"), "wb") as f: f.write(b"IGNORED") p = os.path.join(repo.controldir(), "info", "exclude") with open(p, "wb") as f: f.write(b"/excluded\n") m = IgnoreFilterManager.from_repo(repo) self.assertTrue(m.is_ignored("dir/blie")) self.assertIs(None, m.is_ignored(os.path.join("dir", "bloe"))) self.assertIs(None, m.is_ignored("dir")) self.assertTrue(m.is_ignored(os.path.join("foo", "bar"))) self.assertTrue(m.is_ignored(os.path.join("excluded"))) self.assertTrue(m.is_ignored(os.path.join("dir2", "fileinignoreddir"))) self.assertFalse(m.is_ignored("dir3")) self.assertTrue(m.is_ignored("dir3/")) self.assertTrue(m.is_ignored("dir3/bla")) def test_nested_gitignores(self) -> None: tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) repo = Repo.init(tmp_dir) with open(os.path.join(repo.path, ".gitignore"), "wb") as f: f.write(b"/*\n") f.write(b"!/foo\n") os.mkdir(os.path.join(repo.path, "foo")) with open(os.path.join(repo.path, "foo", ".gitignore"), "wb") as f: f.write(b"/bar\n") with open(os.path.join(repo.path, "foo", "bar"), "wb") as f: f.write(b"IGNORED") m = IgnoreFilterManager.from_repo(repo) self.assertTrue(m.is_ignored("foo/bar")) def test_load_ignore_ignorecase(self) -> None: tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) repo = Repo.init(tmp_dir) config = repo.get_config() config.set(b"core", b"ignorecase", True) config.write_to_path() with open(os.path.join(repo.path, ".gitignore"), "wb") as f: f.write(b"/foo/bar\n") f.write(b"/dir\n") m = IgnoreFilterManager.from_repo(repo) self.assertTrue(m.is_ignored(os.path.join("dir", "blie"))) self.assertTrue(m.is_ignored(os.path.join("DIR", "blie"))) def test_ignored_contents(self) -> None: tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) repo = Repo.init(tmp_dir) with open(os.path.join(repo.path, ".gitignore"), "wb") as f: f.write(b"a/*\n") f.write(b"!a/*.txt\n") m = IgnoreFilterManager.from_repo(repo) os.mkdir(os.path.join(repo.path, "a")) self.assertIs(None, m.is_ignored("a")) self.assertIs(None, m.is_ignored("a/")) self.assertFalse(m.is_ignored("a/b.txt")) self.assertTrue(m.is_ignored("a/c.dat")) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_index.py0000644000175100002000000006457714731042555016544 0ustar00runnerdocker# test_index.py -- Tests for the git index # Copyright (C) 2008-2009 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for the index.""" import os import shutil import stat import struct import sys import tempfile from io import BytesIO from dulwich.index import ( Index, IndexEntry, SerializedIndexEntry, _fs_to_tree_path, _tree_to_fs_path, build_index_from_tree, cleanup_mode, commit_tree, get_unstaged_changes, index_entry_from_stat, read_index, read_index_dict, validate_path_element_default, validate_path_element_ntfs, write_cache_time, write_index, write_index_dict, ) from dulwich.object_store import MemoryObjectStore from dulwich.objects import S_IFGITLINK, Blob, Commit, Tree from dulwich.repo import Repo from . import TestCase, skipIf def can_symlink() -> bool: """Return whether running process can create symlinks.""" if sys.platform != "win32": # Platforms other than Windows should allow symlinks without issues. return True test_source = tempfile.mkdtemp() test_target = test_source + "can_symlink" try: os.symlink(test_source, test_target) except (NotImplementedError, OSError): return False return True class IndexTestCase(TestCase): datadir = os.path.join(os.path.dirname(__file__), "../testdata/indexes") def get_simple_index(self, name): return Index(os.path.join(self.datadir, name)) class SimpleIndexTestCase(IndexTestCase): def test_len(self) -> None: self.assertEqual(1, len(self.get_simple_index("index"))) def test_iter(self) -> None: self.assertEqual([b"bla"], list(self.get_simple_index("index"))) def test_iterobjects(self) -> None: self.assertEqual( [(b"bla", b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", 33188)], list(self.get_simple_index("index").iterobjects()), ) def test_getitem(self) -> None: self.assertEqual( IndexEntry( (1230680220, 0), (1230680220, 0), 2050, 3761020, 33188, 1000, 1000, 0, b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", ), self.get_simple_index("index")[b"bla"], ) def test_empty(self) -> None: i = self.get_simple_index("notanindex") self.assertEqual(0, len(i)) self.assertFalse(os.path.exists(i._filename)) def test_against_empty_tree(self) -> None: i = self.get_simple_index("index") changes = list(i.changes_from_tree(MemoryObjectStore(), None)) self.assertEqual(1, len(changes)) (oldname, newname), (oldmode, newmode), (oldsha, newsha) = changes[0] self.assertEqual(b"bla", newname) self.assertEqual(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", newsha) class SimpleIndexWriterTestCase(IndexTestCase): def setUp(self) -> None: IndexTestCase.setUp(self) self.tempdir = tempfile.mkdtemp() def tearDown(self) -> None: IndexTestCase.tearDown(self) shutil.rmtree(self.tempdir) def test_simple_write(self) -> None: entries = [ ( SerializedIndexEntry( b"barbla", (1230680220, 0), (1230680220, 0), 2050, 3761020, 33188, 1000, 1000, 0, b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", 0, 0, ) ) ] filename = os.path.join(self.tempdir, "test-simple-write-index") with open(filename, "wb+") as x: write_index(x, entries) with open(filename, "rb") as x: self.assertEqual(entries, list(read_index(x))) class ReadIndexDictTests(IndexTestCase): def setUp(self) -> None: IndexTestCase.setUp(self) self.tempdir = tempfile.mkdtemp() def tearDown(self) -> None: IndexTestCase.tearDown(self) shutil.rmtree(self.tempdir) def test_simple_write(self) -> None: entries = { b"barbla": IndexEntry( (1230680220, 0), (1230680220, 0), 2050, 3761020, 33188, 1000, 1000, 0, b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", ) } filename = os.path.join(self.tempdir, "test-simple-write-index") with open(filename, "wb+") as x: write_index_dict(x, entries) with open(filename, "rb") as x: self.assertEqual(entries, read_index_dict(x)) class CommitTreeTests(TestCase): def setUp(self) -> None: super().setUp() self.store = MemoryObjectStore() def test_single_blob(self) -> None: blob = Blob() blob.data = b"foo" self.store.add_object(blob) blobs = [(b"bla", blob.id, stat.S_IFREG)] rootid = commit_tree(self.store, blobs) self.assertEqual(rootid, b"1a1e80437220f9312e855c37ac4398b68e5c1d50") self.assertEqual((stat.S_IFREG, blob.id), self.store[rootid][b"bla"]) self.assertEqual({rootid, blob.id}, set(self.store._data.keys())) def test_nested(self) -> None: blob = Blob() blob.data = b"foo" self.store.add_object(blob) blobs = [(b"bla/bar", blob.id, stat.S_IFREG)] rootid = commit_tree(self.store, blobs) self.assertEqual(rootid, b"d92b959b216ad0d044671981196781b3258fa537") dirid = self.store[rootid][b"bla"][1] self.assertEqual(dirid, b"c1a1deb9788150829579a8b4efa6311e7b638650") self.assertEqual((stat.S_IFDIR, dirid), self.store[rootid][b"bla"]) self.assertEqual((stat.S_IFREG, blob.id), self.store[dirid][b"bar"]) self.assertEqual({rootid, dirid, blob.id}, set(self.store._data.keys())) class CleanupModeTests(TestCase): def assertModeEqual(self, expected, got) -> None: self.assertEqual(expected, got, f"{expected:o} != {got:o}") def test_file(self) -> None: self.assertModeEqual(0o100644, cleanup_mode(0o100000)) def test_executable(self) -> None: self.assertModeEqual(0o100755, cleanup_mode(0o100711)) self.assertModeEqual(0o100755, cleanup_mode(0o100700)) def test_symlink(self) -> None: self.assertModeEqual(0o120000, cleanup_mode(0o120711)) def test_dir(self) -> None: self.assertModeEqual(0o040000, cleanup_mode(0o40531)) def test_submodule(self) -> None: self.assertModeEqual(0o160000, cleanup_mode(0o160744)) class WriteCacheTimeTests(TestCase): def test_write_string(self) -> None: f = BytesIO() self.assertRaises(TypeError, write_cache_time, f, "foo") def test_write_int(self) -> None: f = BytesIO() write_cache_time(f, 434343) self.assertEqual(struct.pack(">LL", 434343, 0), f.getvalue()) def test_write_tuple(self) -> None: f = BytesIO() write_cache_time(f, (434343, 21)) self.assertEqual(struct.pack(">LL", 434343, 21), f.getvalue()) def test_write_float(self) -> None: f = BytesIO() write_cache_time(f, 434343.000000021) self.assertEqual(struct.pack(">LL", 434343, 21), f.getvalue()) class IndexEntryFromStatTests(TestCase): def test_simple(self) -> None: st = os.stat_result( ( 16877, 131078, 64769, 154, 1000, 1000, 12288, 1323629595, 1324180496, 1324180496, ) ) entry = index_entry_from_stat(st, b"22" * 20) self.assertEqual( entry, IndexEntry( 1324180496, 1324180496, 64769, 131078, 16384, 1000, 1000, 12288, b"2222222222222222222222222222222222222222", ), ) def test_override_mode(self) -> None: st = os.stat_result( ( stat.S_IFREG + 0o644, 131078, 64769, 154, 1000, 1000, 12288, 1323629595, 1324180496, 1324180496, ) ) entry = index_entry_from_stat(st, b"22" * 20, mode=stat.S_IFREG + 0o755) self.assertEqual( entry, IndexEntry( 1324180496, 1324180496, 64769, 131078, 33261, 1000, 1000, 12288, b"2222222222222222222222222222222222222222", ), ) class BuildIndexTests(TestCase): def assertReasonableIndexEntry(self, index_entry, mode, filesize, sha) -> None: self.assertEqual(index_entry.mode, mode) # mode self.assertEqual(index_entry.size, filesize) # filesize self.assertEqual(index_entry.sha, sha) # sha def assertFileContents(self, path, contents, symlink=False) -> None: if symlink: self.assertEqual(os.readlink(path), contents) else: with open(path, "rb") as f: self.assertEqual(f.read(), contents) def test_empty(self) -> None: repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: tree = Tree() repo.object_store.add_object(tree) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id ) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 0) # Verify no files self.assertEqual([".git"], os.listdir(repo.path)) def test_git_dir(self) -> None: repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo filea = Blob.from_string(b"file a") filee = Blob.from_string(b"d") tree = Tree() tree[b".git/a"] = (stat.S_IFREG | 0o644, filea.id) tree[b"c/e"] = (stat.S_IFREG | 0o644, filee.id) repo.object_store.add_objects([(o, None) for o in [filea, filee, tree]]) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id ) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 1) # filea apath = os.path.join(repo.path, ".git", "a") self.assertFalse(os.path.exists(apath)) # filee epath = os.path.join(repo.path, "c", "e") self.assertTrue(os.path.exists(epath)) self.assertReasonableIndexEntry( index[b"c/e"], stat.S_IFREG | 0o644, 1, filee.id ) self.assertFileContents(epath, b"d") def test_nonempty(self) -> None: repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo filea = Blob.from_string(b"file a") fileb = Blob.from_string(b"file b") filed = Blob.from_string(b"file d") tree = Tree() tree[b"a"] = (stat.S_IFREG | 0o644, filea.id) tree[b"b"] = (stat.S_IFREG | 0o644, fileb.id) tree[b"c/d"] = (stat.S_IFREG | 0o644, filed.id) repo.object_store.add_objects( [(o, None) for o in [filea, fileb, filed, tree]] ) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id ) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 3) # filea apath = os.path.join(repo.path, "a") self.assertTrue(os.path.exists(apath)) self.assertReasonableIndexEntry( index[b"a"], stat.S_IFREG | 0o644, 6, filea.id ) self.assertFileContents(apath, b"file a") # fileb bpath = os.path.join(repo.path, "b") self.assertTrue(os.path.exists(bpath)) self.assertReasonableIndexEntry( index[b"b"], stat.S_IFREG | 0o644, 6, fileb.id ) self.assertFileContents(bpath, b"file b") # filed dpath = os.path.join(repo.path, "c", "d") self.assertTrue(os.path.exists(dpath)) self.assertReasonableIndexEntry( index[b"c/d"], stat.S_IFREG | 0o644, 6, filed.id ) self.assertFileContents(dpath, b"file d") # Verify no extra files self.assertEqual([".git", "a", "b", "c"], sorted(os.listdir(repo.path))) self.assertEqual(["d"], sorted(os.listdir(os.path.join(repo.path, "c")))) @skipIf(not getattr(os, "sync", None), "Requires sync support") def test_norewrite(self) -> None: repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo filea = Blob.from_string(b"file a") filea_path = os.path.join(repo_dir, "a") tree = Tree() tree[b"a"] = (stat.S_IFREG | 0o644, filea.id) repo.object_store.add_objects([(o, None) for o in [filea, tree]]) # First Write build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id ) # Use sync as metadata can be cached on some FS os.sync() mtime = os.stat(filea_path).st_mtime # Test Rewrite build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id ) os.sync() self.assertEqual(mtime, os.stat(filea_path).st_mtime) # Modify content with open(filea_path, "wb") as fh: fh.write(b"test a") os.sync() mtime = os.stat(filea_path).st_mtime # Test rewrite build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id ) os.sync() with open(filea_path, "rb") as fh: self.assertEqual(b"file a", fh.read()) @skipIf(not can_symlink(), "Requires symlink support") def test_symlink(self) -> None: repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo filed = Blob.from_string(b"file d") filee = Blob.from_string(b"d") tree = Tree() tree[b"c/d"] = (stat.S_IFREG | 0o644, filed.id) tree[b"c/e"] = (stat.S_IFLNK, filee.id) # symlink repo.object_store.add_objects([(o, None) for o in [filed, filee, tree]]) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id ) # Verify index entries index = repo.open_index() # symlink to d epath = os.path.join(repo.path, "c", "e") self.assertTrue(os.path.exists(epath)) self.assertReasonableIndexEntry( index[b"c/e"], stat.S_IFLNK, 0 if sys.platform == "win32" else 1, filee.id, ) self.assertFileContents(epath, "d", symlink=True) def test_no_decode_encode(self) -> None: repo_dir = tempfile.mkdtemp() repo_dir_bytes = os.fsencode(repo_dir) self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo file = Blob.from_string(b"foo") tree = Tree() latin1_name = "À".encode("latin1") try: latin1_path = os.path.join(repo_dir_bytes, latin1_name) except UnicodeDecodeError: self.skipTest("can not decode as latin1") utf8_name = "À".encode() utf8_path = os.path.join(repo_dir_bytes, utf8_name) tree[latin1_name] = (stat.S_IFREG | 0o644, file.id) tree[utf8_name] = (stat.S_IFREG | 0o644, file.id) repo.object_store.add_objects([(o, None) for o in [file, tree]]) try: build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id ) except OSError as e: if e.errno == 92 and sys.platform == "darwin": # Our filename isn't supported by the platform :( self.skipTest(f"can not write filename {e.filename!r}") else: raise except UnicodeDecodeError: # This happens e.g. with python3.6 on Windows. # It implicitly decodes using utf8, which doesn't work. self.skipTest("can not implicitly convert as utf8") # Verify index entries index = repo.open_index() self.assertIn(latin1_name, index) self.assertIn(utf8_name, index) self.assertTrue(os.path.exists(latin1_path)) self.assertTrue(os.path.exists(utf8_path)) def test_git_submodule(self) -> None: repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: filea = Blob.from_string(b"file alalala") subtree = Tree() subtree[b"a"] = (stat.S_IFREG | 0o644, filea.id) c = Commit() c.tree = subtree.id c.committer = c.author = b"Somebody " c.commit_time = c.author_time = 42342 c.commit_timezone = c.author_timezone = 0 c.parents = [] c.message = b"Subcommit" tree = Tree() tree[b"c"] = (S_IFGITLINK, c.id) repo.object_store.add_objects([(o, None) for o in [tree]]) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id ) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 1) # filea apath = os.path.join(repo.path, "c/a") self.assertFalse(os.path.exists(apath)) # dir c cpath = os.path.join(repo.path, "c") self.assertTrue(os.path.isdir(cpath)) self.assertEqual(index[b"c"].mode, S_IFGITLINK) # mode self.assertEqual(index[b"c"].sha, c.id) # sha def test_git_submodule_exists(self) -> None: repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: filea = Blob.from_string(b"file alalala") subtree = Tree() subtree[b"a"] = (stat.S_IFREG | 0o644, filea.id) c = Commit() c.tree = subtree.id c.committer = c.author = b"Somebody " c.commit_time = c.author_time = 42342 c.commit_timezone = c.author_timezone = 0 c.parents = [] c.message = b"Subcommit" tree = Tree() tree[b"c"] = (S_IFGITLINK, c.id) os.mkdir(os.path.join(repo_dir, "c")) repo.object_store.add_objects([(o, None) for o in [tree]]) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id ) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 1) # filea apath = os.path.join(repo.path, "c/a") self.assertFalse(os.path.exists(apath)) # dir c cpath = os.path.join(repo.path, "c") self.assertTrue(os.path.isdir(cpath)) self.assertEqual(index[b"c"].mode, S_IFGITLINK) # mode self.assertEqual(index[b"c"].sha, c.id) # sha class GetUnstagedChangesTests(TestCase): def test_get_unstaged_changes(self) -> None: """Unit test for get_unstaged_changes.""" repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Commit a dummy file then modify it foo1_fullpath = os.path.join(repo_dir, "foo1") with open(foo1_fullpath, "wb") as f: f.write(b"origstuff") foo2_fullpath = os.path.join(repo_dir, "foo2") with open(foo2_fullpath, "wb") as f: f.write(b"origstuff") repo.stage(["foo1", "foo2"]) repo.do_commit( b"test status", author=b"author ", committer=b"committer ", ) with open(foo1_fullpath, "wb") as f: f.write(b"newstuff") # modify access and modify time of path os.utime(foo1_fullpath, (0, 0)) changes = get_unstaged_changes(repo.open_index(), repo_dir) self.assertEqual(list(changes), [b"foo1"]) def test_get_unstaged_deleted_changes(self) -> None: """Unit test for get_unstaged_changes.""" repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Commit a dummy file then remove it foo1_fullpath = os.path.join(repo_dir, "foo1") with open(foo1_fullpath, "wb") as f: f.write(b"origstuff") repo.stage(["foo1"]) repo.do_commit( b"test status", author=b"author ", committer=b"committer ", ) os.unlink(foo1_fullpath) changes = get_unstaged_changes(repo.open_index(), repo_dir) self.assertEqual(list(changes), [b"foo1"]) def test_get_unstaged_changes_removed_replaced_by_directory(self) -> None: """Unit test for get_unstaged_changes.""" repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Commit a dummy file then modify it foo1_fullpath = os.path.join(repo_dir, "foo1") with open(foo1_fullpath, "wb") as f: f.write(b"origstuff") repo.stage(["foo1"]) repo.do_commit( b"test status", author=b"author ", committer=b"committer ", ) os.remove(foo1_fullpath) os.mkdir(foo1_fullpath) changes = get_unstaged_changes(repo.open_index(), repo_dir) self.assertEqual(list(changes), [b"foo1"]) @skipIf(not can_symlink(), "Requires symlink support") def test_get_unstaged_changes_removed_replaced_by_link(self) -> None: """Unit test for get_unstaged_changes.""" repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Commit a dummy file then modify it foo1_fullpath = os.path.join(repo_dir, "foo1") with open(foo1_fullpath, "wb") as f: f.write(b"origstuff") repo.stage(["foo1"]) repo.do_commit( b"test status", author=b"author ", committer=b"committer ", ) os.remove(foo1_fullpath) os.symlink(os.path.dirname(foo1_fullpath), foo1_fullpath) changes = get_unstaged_changes(repo.open_index(), repo_dir) self.assertEqual(list(changes), [b"foo1"]) class TestValidatePathElement(TestCase): def test_default(self) -> None: self.assertTrue(validate_path_element_default(b"bla")) self.assertTrue(validate_path_element_default(b".bla")) self.assertFalse(validate_path_element_default(b".git")) self.assertFalse(validate_path_element_default(b".giT")) self.assertFalse(validate_path_element_default(b"..")) self.assertTrue(validate_path_element_default(b"git~1")) def test_ntfs(self) -> None: self.assertTrue(validate_path_element_ntfs(b"bla")) self.assertTrue(validate_path_element_ntfs(b".bla")) self.assertFalse(validate_path_element_ntfs(b".git")) self.assertFalse(validate_path_element_ntfs(b".giT")) self.assertFalse(validate_path_element_ntfs(b"..")) self.assertFalse(validate_path_element_ntfs(b"git~1")) class TestTreeFSPathConversion(TestCase): def test_tree_to_fs_path(self) -> None: tree_path = "délwíçh/foo".encode() fs_path = _tree_to_fs_path(b"/prefix/path", tree_path) self.assertEqual( fs_path, os.fsencode(os.path.join("/prefix/path", "délwíçh", "foo")), ) def test_fs_to_tree_path_str(self) -> None: fs_path = os.path.join(os.path.join("délwíçh", "foo")) tree_path = _fs_to_tree_path(fs_path) self.assertEqual(tree_path, "délwíçh/foo".encode()) def test_fs_to_tree_path_bytes(self) -> None: fs_path = os.path.join(os.fsencode(os.path.join("délwíçh", "foo"))) tree_path = _fs_to_tree_path(fs_path) self.assertEqual(tree_path, "délwíçh/foo".encode()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_lfs.py0000644000175100002000000000315314731042555016200 0ustar00runnerdocker# test_lfs.py -- tests for LFS # Copyright (C) 2020 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for LFS support.""" import shutil import tempfile from dulwich.lfs import LFSStore from . import TestCase class LFSTests(TestCase): def setUp(self) -> None: super().setUp() self.test_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.test_dir) self.lfs = LFSStore.create(self.test_dir) def test_create(self) -> None: sha = self.lfs.write_object([b"a", b"b"]) with self.lfs.open_object(sha) as f: self.assertEqual(b"ab", f.read()) def test_missing(self) -> None: self.assertRaises(KeyError, self.lfs.open_object, "abcdeabcdeabcdeabcde") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_line_ending.py0000644000175100002000000001627014731042555017673 0ustar00runnerdocker# test_line_ending.py -- Tests for the line ending functions # Copyright (C) 2018-2019 Boris Feld # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for the line ending conversion.""" from dulwich.line_ending import ( convert_crlf_to_lf, convert_lf_to_crlf, get_checkin_filter_autocrlf, get_checkout_filter_autocrlf, normalize_blob, ) from dulwich.objects import Blob from . import TestCase class LineEndingConversion(TestCase): """Test the line ending conversion functions in various cases.""" def test_convert_crlf_to_lf_no_op(self) -> None: self.assertEqual(convert_crlf_to_lf(b"foobar"), b"foobar") def test_convert_crlf_to_lf(self) -> None: self.assertEqual(convert_crlf_to_lf(b"line1\r\nline2"), b"line1\nline2") def test_convert_crlf_to_lf_mixed(self) -> None: self.assertEqual(convert_crlf_to_lf(b"line1\r\n\nline2"), b"line1\n\nline2") def test_convert_lf_to_crlf_no_op(self) -> None: self.assertEqual(convert_lf_to_crlf(b"foobar"), b"foobar") def test_convert_lf_to_crlf(self) -> None: self.assertEqual(convert_lf_to_crlf(b"line1\nline2"), b"line1\r\nline2") def test_convert_lf_to_crlf_mixed(self) -> None: self.assertEqual(convert_lf_to_crlf(b"line1\r\n\nline2"), b"line1\r\n\r\nline2") class GetLineEndingAutocrlfFilters(TestCase): def test_get_checkin_filter_autocrlf_default(self) -> None: checkin_filter = get_checkin_filter_autocrlf(b"false") self.assertEqual(checkin_filter, None) def test_get_checkin_filter_autocrlf_true(self) -> None: checkin_filter = get_checkin_filter_autocrlf(b"true") self.assertEqual(checkin_filter, convert_crlf_to_lf) def test_get_checkin_filter_autocrlf_input(self) -> None: checkin_filter = get_checkin_filter_autocrlf(b"input") self.assertEqual(checkin_filter, convert_crlf_to_lf) def test_get_checkout_filter_autocrlf_default(self) -> None: checkout_filter = get_checkout_filter_autocrlf(b"false") self.assertEqual(checkout_filter, None) def test_get_checkout_filter_autocrlf_true(self) -> None: checkout_filter = get_checkout_filter_autocrlf(b"true") self.assertEqual(checkout_filter, convert_lf_to_crlf) def test_get_checkout_filter_autocrlf_input(self) -> None: checkout_filter = get_checkout_filter_autocrlf(b"input") self.assertEqual(checkout_filter, None) class NormalizeBlobTestCase(TestCase): def test_normalize_to_lf_no_op(self) -> None: base_content = b"line1\nline2" base_sha = "f8be7bb828880727816015d21abcbc37d033f233" base_blob = Blob() base_blob.set_raw_string(base_content) self.assertEqual(base_blob.as_raw_chunks(), [base_content]) self.assertEqual(base_blob.sha().hexdigest(), base_sha) filtered_blob = normalize_blob( base_blob, convert_crlf_to_lf, binary_detection=False ) self.assertEqual(filtered_blob.as_raw_chunks(), [base_content]) self.assertEqual(filtered_blob.sha().hexdigest(), base_sha) def test_normalize_to_lf(self) -> None: base_content = b"line1\r\nline2" base_sha = "3a1bd7a52799fe5cf6411f1d35f4c10bacb1db96" base_blob = Blob() base_blob.set_raw_string(base_content) self.assertEqual(base_blob.as_raw_chunks(), [base_content]) self.assertEqual(base_blob.sha().hexdigest(), base_sha) filtered_blob = normalize_blob( base_blob, convert_crlf_to_lf, binary_detection=False ) normalized_content = b"line1\nline2" normalized_sha = "f8be7bb828880727816015d21abcbc37d033f233" self.assertEqual(filtered_blob.as_raw_chunks(), [normalized_content]) self.assertEqual(filtered_blob.sha().hexdigest(), normalized_sha) def test_normalize_to_lf_binary(self) -> None: base_content = b"line1\r\nline2\0" base_sha = "b44504193b765f7cd79673812de8afb55b372ab2" base_blob = Blob() base_blob.set_raw_string(base_content) self.assertEqual(base_blob.as_raw_chunks(), [base_content]) self.assertEqual(base_blob.sha().hexdigest(), base_sha) filtered_blob = normalize_blob( base_blob, convert_crlf_to_lf, binary_detection=True ) self.assertEqual(filtered_blob.as_raw_chunks(), [base_content]) self.assertEqual(filtered_blob.sha().hexdigest(), base_sha) def test_normalize_to_crlf_no_op(self) -> None: base_content = b"line1\r\nline2" base_sha = "3a1bd7a52799fe5cf6411f1d35f4c10bacb1db96" base_blob = Blob() base_blob.set_raw_string(base_content) self.assertEqual(base_blob.as_raw_chunks(), [base_content]) self.assertEqual(base_blob.sha().hexdigest(), base_sha) filtered_blob = normalize_blob( base_blob, convert_lf_to_crlf, binary_detection=False ) self.assertEqual(filtered_blob.as_raw_chunks(), [base_content]) self.assertEqual(filtered_blob.sha().hexdigest(), base_sha) def test_normalize_to_crlf(self) -> None: base_content = b"line1\nline2" base_sha = "f8be7bb828880727816015d21abcbc37d033f233" base_blob = Blob() base_blob.set_raw_string(base_content) self.assertEqual(base_blob.as_raw_chunks(), [base_content]) self.assertEqual(base_blob.sha().hexdigest(), base_sha) filtered_blob = normalize_blob( base_blob, convert_lf_to_crlf, binary_detection=False ) normalized_content = b"line1\r\nline2" normalized_sha = "3a1bd7a52799fe5cf6411f1d35f4c10bacb1db96" self.assertEqual(filtered_blob.as_raw_chunks(), [normalized_content]) self.assertEqual(filtered_blob.sha().hexdigest(), normalized_sha) def test_normalize_to_crlf_binary(self) -> None: base_content = b"line1\r\nline2\0" base_sha = "b44504193b765f7cd79673812de8afb55b372ab2" base_blob = Blob() base_blob.set_raw_string(base_content) self.assertEqual(base_blob.as_raw_chunks(), [base_content]) self.assertEqual(base_blob.sha().hexdigest(), base_sha) filtered_blob = normalize_blob( base_blob, convert_lf_to_crlf, binary_detection=True ) self.assertEqual(filtered_blob.as_raw_chunks(), [base_content]) self.assertEqual(filtered_blob.sha().hexdigest(), base_sha) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_lru_cache.py0000644000175100002000000004007614731042555017346 0ustar00runnerdocker# Copyright (C) 2006, 2008 Canonical Ltd # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for the lru_cache module.""" from dulwich import lru_cache from . import TestCase class TestLRUCache(TestCase): """Test that LRU cache properly keeps track of entries.""" def test_cache_size(self) -> None: cache = lru_cache.LRUCache(max_cache=10) self.assertEqual(10, cache.cache_size()) cache = lru_cache.LRUCache(max_cache=256) self.assertEqual(256, cache.cache_size()) cache.resize(512) self.assertEqual(512, cache.cache_size()) def test_missing(self) -> None: cache = lru_cache.LRUCache(max_cache=10) self.assertNotIn("foo", cache) self.assertRaises(KeyError, cache.__getitem__, "foo") cache["foo"] = "bar" self.assertEqual("bar", cache["foo"]) self.assertIn("foo", cache) self.assertNotIn("bar", cache) def test_map_None(self) -> None: # Make sure that we can properly map None as a key. cache = lru_cache.LRUCache(max_cache=10) self.assertNotIn(None, cache) cache[None] = 1 self.assertEqual(1, cache[None]) cache[None] = 2 self.assertEqual(2, cache[None]) # Test the various code paths of __getitem__, to make sure that we can # handle when None is the key for the LRU and the MRU cache[1] = 3 cache[None] = 1 cache[None] cache[1] cache[None] self.assertEqual([None, 1], [n.key for n in cache._walk_lru()]) def test_add__null_key(self) -> None: cache = lru_cache.LRUCache(max_cache=10) self.assertRaises(ValueError, cache.add, lru_cache._null_key, 1) def test_overflow(self) -> None: """Adding extra entries will pop out old ones.""" cache = lru_cache.LRUCache(max_cache=1, after_cleanup_count=1) cache["foo"] = "bar" # With a max cache of 1, adding 'baz' should pop out 'foo' cache["baz"] = "biz" self.assertNotIn("foo", cache) self.assertIn("baz", cache) self.assertEqual("biz", cache["baz"]) def test_by_usage(self) -> None: """Accessing entries bumps them up in priority.""" cache = lru_cache.LRUCache(max_cache=2) cache["baz"] = "biz" cache["foo"] = "bar" self.assertEqual("biz", cache["baz"]) # This must kick out 'foo' because it was the last accessed cache["nub"] = "in" self.assertNotIn("foo", cache) def test_cleanup(self) -> None: """Test that we can use a cleanup function.""" cleanup_called = [] def cleanup_func(key, val) -> None: cleanup_called.append((key, val)) cache = lru_cache.LRUCache(max_cache=2, after_cleanup_count=2) cache.add("baz", "1", cleanup=cleanup_func) cache.add("foo", "2", cleanup=cleanup_func) cache.add("biz", "3", cleanup=cleanup_func) self.assertEqual([("baz", "1")], cleanup_called) # 'foo' is now most recent, so final cleanup will call it last cache["foo"] cache.clear() self.assertEqual([("baz", "1"), ("biz", "3"), ("foo", "2")], cleanup_called) def test_cleanup_on_replace(self) -> None: """Replacing an object should cleanup the old value.""" cleanup_called = [] def cleanup_func(key, val) -> None: cleanup_called.append((key, val)) cache = lru_cache.LRUCache(max_cache=2) cache.add(1, 10, cleanup=cleanup_func) cache.add(2, 20, cleanup=cleanup_func) cache.add(2, 25, cleanup=cleanup_func) self.assertEqual([(2, 20)], cleanup_called) self.assertEqual(25, cache[2]) # Even __setitem__ should make sure cleanup() is called cache[2] = 26 self.assertEqual([(2, 20), (2, 25)], cleanup_called) def test_len(self) -> None: cache = lru_cache.LRUCache(max_cache=10, after_cleanup_count=10) cache[1] = 10 cache[2] = 20 cache[3] = 30 cache[4] = 40 self.assertEqual(4, len(cache)) cache[5] = 50 cache[6] = 60 cache[7] = 70 cache[8] = 80 self.assertEqual(8, len(cache)) cache[1] = 15 # replacement self.assertEqual(8, len(cache)) cache[9] = 90 cache[10] = 100 cache[11] = 110 # We hit the max self.assertEqual(10, len(cache)) self.assertEqual( [11, 10, 9, 1, 8, 7, 6, 5, 4, 3], [n.key for n in cache._walk_lru()], ) def test_cleanup_shrinks_to_after_clean_count(self) -> None: cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=3) cache.add(1, 10) cache.add(2, 20) cache.add(3, 25) cache.add(4, 30) cache.add(5, 35) self.assertEqual(5, len(cache)) # This will bump us over the max, which causes us to shrink down to # after_cleanup_cache size cache.add(6, 40) self.assertEqual(3, len(cache)) def test_after_cleanup_larger_than_max(self) -> None: cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=10) self.assertEqual(5, cache._after_cleanup_count) def test_after_cleanup_none(self) -> None: cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=None) # By default _after_cleanup_size is 80% of the normal size self.assertEqual(4, cache._after_cleanup_count) def test_cleanup_2(self) -> None: cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=2) # Add these in order cache.add(1, 10) cache.add(2, 20) cache.add(3, 25) cache.add(4, 30) cache.add(5, 35) self.assertEqual(5, len(cache)) # Force a compaction cache.cleanup() self.assertEqual(2, len(cache)) def test_preserve_last_access_order(self) -> None: cache = lru_cache.LRUCache(max_cache=5) # Add these in order cache.add(1, 10) cache.add(2, 20) cache.add(3, 25) cache.add(4, 30) cache.add(5, 35) self.assertEqual([5, 4, 3, 2, 1], [n.key for n in cache._walk_lru()]) # Now access some randomly cache[2] cache[5] cache[3] cache[2] self.assertEqual([2, 3, 5, 4, 1], [n.key for n in cache._walk_lru()]) def test_get(self) -> None: cache = lru_cache.LRUCache(max_cache=5) cache.add(1, 10) cache.add(2, 20) self.assertEqual(20, cache.get(2)) self.assertEqual(None, cache.get(3)) obj = object() self.assertIs(obj, cache.get(3, obj)) self.assertEqual([2, 1], [n.key for n in cache._walk_lru()]) self.assertEqual(10, cache.get(1)) self.assertEqual([1, 2], [n.key for n in cache._walk_lru()]) def test_keys(self) -> None: cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=5) cache[1] = 2 cache[2] = 3 cache[3] = 4 self.assertEqual([1, 2, 3], sorted(cache.keys())) cache[4] = 5 cache[5] = 6 cache[6] = 7 self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys())) def test_resize_smaller(self) -> None: cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4) cache[1] = 2 cache[2] = 3 cache[3] = 4 cache[4] = 5 cache[5] = 6 self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys())) cache[6] = 7 self.assertEqual([3, 4, 5, 6], sorted(cache.keys())) # Now resize to something smaller, which triggers a cleanup cache.resize(max_cache=3, after_cleanup_count=2) self.assertEqual([5, 6], sorted(cache.keys())) # Adding something will use the new size cache[7] = 8 self.assertEqual([5, 6, 7], sorted(cache.keys())) cache[8] = 9 self.assertEqual([7, 8], sorted(cache.keys())) def test_resize_larger(self) -> None: cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4) cache[1] = 2 cache[2] = 3 cache[3] = 4 cache[4] = 5 cache[5] = 6 self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys())) cache[6] = 7 self.assertEqual([3, 4, 5, 6], sorted(cache.keys())) cache.resize(max_cache=8, after_cleanup_count=6) self.assertEqual([3, 4, 5, 6], sorted(cache.keys())) cache[7] = 8 cache[8] = 9 cache[9] = 10 cache[10] = 11 self.assertEqual([3, 4, 5, 6, 7, 8, 9, 10], sorted(cache.keys())) cache[11] = 12 # triggers cleanup back to new after_cleanup_count self.assertEqual([6, 7, 8, 9, 10, 11], sorted(cache.keys())) class TestLRUSizeCache(TestCase): def test_basic_init(self) -> None: cache = lru_cache.LRUSizeCache() self.assertEqual(2048, cache._max_cache) self.assertEqual(int(cache._max_size * 0.8), cache._after_cleanup_size) self.assertEqual(0, cache._value_size) def test_add__null_key(self) -> None: cache = lru_cache.LRUSizeCache() self.assertRaises(ValueError, cache.add, lru_cache._null_key, 1) def test_add_tracks_size(self) -> None: cache = lru_cache.LRUSizeCache() self.assertEqual(0, cache._value_size) cache.add("my key", "my value text") self.assertEqual(13, cache._value_size) def test_remove_tracks_size(self) -> None: cache = lru_cache.LRUSizeCache() self.assertEqual(0, cache._value_size) cache.add("my key", "my value text") self.assertEqual(13, cache._value_size) node = cache._cache["my key"] cache._remove_node(node) self.assertEqual(0, cache._value_size) def test_no_add_over_size(self) -> None: """Adding a large value may not be cached at all.""" cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5) self.assertEqual(0, cache._value_size) self.assertEqual({}, cache.items()) cache.add("test", "key") self.assertEqual(3, cache._value_size) self.assertEqual({"test": "key"}, cache.items()) cache.add("test2", "key that is too big") self.assertEqual(3, cache._value_size) self.assertEqual({"test": "key"}, cache.items()) # If we would add a key, only to cleanup and remove all cached entries, # then obviously that value should not be stored cache.add("test3", "bigkey") self.assertEqual(3, cache._value_size) self.assertEqual({"test": "key"}, cache.items()) cache.add("test4", "bikey") self.assertEqual(3, cache._value_size) self.assertEqual({"test": "key"}, cache.items()) def test_no_add_over_size_cleanup(self) -> None: """If a large value is not cached, we will call cleanup right away.""" cleanup_calls = [] def cleanup(key, value) -> None: cleanup_calls.append((key, value)) cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5) self.assertEqual(0, cache._value_size) self.assertEqual({}, cache.items()) cache.add("test", "key that is too big", cleanup=cleanup) # key was not added self.assertEqual(0, cache._value_size) self.assertEqual({}, cache.items()) # and cleanup was called self.assertEqual([("test", "key that is too big")], cleanup_calls) def test_adding_clears_cache_based_on_size(self) -> None: """The cache is cleared in LRU order until small enough.""" cache = lru_cache.LRUSizeCache(max_size=20) cache.add("key1", "value") # 5 chars cache.add("key2", "value2") # 6 chars cache.add("key3", "value23") # 7 chars self.assertEqual(5 + 6 + 7, cache._value_size) cache["key2"] # reference key2 so it gets a newer reference time cache.add("key4", "value234") # 8 chars, over limit # We have to remove 2 keys to get back under limit self.assertEqual(6 + 8, cache._value_size) self.assertEqual({"key2": "value2", "key4": "value234"}, cache.items()) def test_adding_clears_to_after_cleanup_size(self) -> None: cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10) cache.add("key1", "value") # 5 chars cache.add("key2", "value2") # 6 chars cache.add("key3", "value23") # 7 chars self.assertEqual(5 + 6 + 7, cache._value_size) cache["key2"] # reference key2 so it gets a newer reference time cache.add("key4", "value234") # 8 chars, over limit # We have to remove 3 keys to get back under limit self.assertEqual(8, cache._value_size) self.assertEqual({"key4": "value234"}, cache.items()) def test_custom_sizes(self) -> None: def size_of_list(lst): return sum(len(x) for x in lst) cache = lru_cache.LRUSizeCache( max_size=20, after_cleanup_size=10, compute_size=size_of_list ) cache.add("key1", ["val", "ue"]) # 5 chars cache.add("key2", ["val", "ue2"]) # 6 chars cache.add("key3", ["val", "ue23"]) # 7 chars self.assertEqual(5 + 6 + 7, cache._value_size) cache["key2"] # reference key2 so it gets a newer reference time cache.add("key4", ["value", "234"]) # 8 chars, over limit # We have to remove 3 keys to get back under limit self.assertEqual(8, cache._value_size) self.assertEqual({"key4": ["value", "234"]}, cache.items()) def test_cleanup(self) -> None: cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10) # Add these in order cache.add("key1", "value") # 5 chars cache.add("key2", "value2") # 6 chars cache.add("key3", "value23") # 7 chars self.assertEqual(5 + 6 + 7, cache._value_size) cache.cleanup() # Only the most recent fits after cleaning up self.assertEqual(7, cache._value_size) def test_keys(self) -> None: cache = lru_cache.LRUSizeCache(max_size=10) cache[1] = "a" cache[2] = "b" cache[3] = "cdef" self.assertEqual([1, 2, 3], sorted(cache.keys())) def test_resize_smaller(self) -> None: cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9) cache[1] = "abc" cache[2] = "def" cache[3] = "ghi" cache[4] = "jkl" # Triggers a cleanup self.assertEqual([2, 3, 4], sorted(cache.keys())) # Resize should also cleanup again cache.resize(max_size=6, after_cleanup_size=4) self.assertEqual([4], sorted(cache.keys())) # Adding should use the new max size cache[5] = "mno" self.assertEqual([4, 5], sorted(cache.keys())) cache[6] = "pqr" self.assertEqual([6], sorted(cache.keys())) def test_resize_larger(self) -> None: cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9) cache[1] = "abc" cache[2] = "def" cache[3] = "ghi" cache[4] = "jkl" # Triggers a cleanup self.assertEqual([2, 3, 4], sorted(cache.keys())) cache.resize(max_size=15, after_cleanup_size=12) self.assertEqual([2, 3, 4], sorted(cache.keys())) cache[5] = "mno" cache[6] = "pqr" self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys())) cache[7] = "stu" self.assertEqual([4, 5, 6, 7], sorted(cache.keys())) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_mailmap.py0000644000175100002000000000746614731042555017047 0ustar00runnerdocker# test_mailmap.py -- Tests for dulwich.mailmap # Copyright (C) 2018 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for dulwich.mailmap.""" from io import BytesIO from unittest import TestCase from dulwich.mailmap import Mailmap, read_mailmap class ReadMailmapTests(TestCase): def test_read(self) -> None: b = BytesIO( b"""\ Jane Doe Joe R. Developer # A comment # Comment Some Dude nick1 Other Author nick2 Other Author Santa Claus """ ) self.assertEqual( [ ((b"Jane Doe", b"jane@desktop.(none)"), None), ((b"Joe R. Developer", b"joe@example.com"), None), ((None, b"cto@company.xx"), (None, b"cto@coompany.xx")), ( (b"Some Dude", b"some@dude.xx"), (b"nick1", b"bugs@company.xx"), ), ( (b"Other Author", b"other@author.xx"), (b"nick2", b"bugs@company.xx"), ), ( (b"Other Author", b"other@author.xx"), (None, b"nick2@company.xx"), ), ( (b"Santa Claus", b"santa.claus@northpole.xx"), (None, b"me@company.xx"), ), ], list(read_mailmap(b)), ) class MailmapTests(TestCase): def test_lookup(self) -> None: m = Mailmap() m.add_entry((b"Jane Doe", b"jane@desktop.(none)"), (None, None)) m.add_entry((b"Joe R. Developer", b"joe@example.com"), None) m.add_entry((None, b"cto@company.xx"), (None, b"cto@coompany.xx")) m.add_entry((b"Some Dude", b"some@dude.xx"), (b"nick1", b"bugs@company.xx")) m.add_entry( (b"Other Author", b"other@author.xx"), (b"nick2", b"bugs@company.xx"), ) m.add_entry((b"Other Author", b"other@author.xx"), (None, b"nick2@company.xx")) m.add_entry( (b"Santa Claus", b"santa.claus@northpole.xx"), (None, b"me@company.xx"), ) self.assertEqual( b"Jane Doe ", m.lookup(b"Jane Doe "), ) self.assertEqual( b"Jane Doe ", m.lookup(b"Jane Doe "), ) self.assertEqual( b"Jane Doe ", m.lookup(b"Jane D. "), ) self.assertEqual( b"Some Dude ", m.lookup(b"nick1 ") ) self.assertEqual(b"CTO ", m.lookup(b"CTO ")) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_missing_obj_finder.py0000644000175100002000000002614714731042555021256 0ustar00runnerdocker# test_missing_obj_finder.py -- tests for MissingObjectFinder # Copyright (C) 2012 syntevo GmbH # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # from dulwich.object_store import MemoryObjectStore, MissingObjectFinder from dulwich.objects import Blob from dulwich.tests.utils import build_commit_graph, make_object, make_tag from . import TestCase class MissingObjectFinderTest(TestCase): def setUp(self) -> None: super().setUp() self.store = MemoryObjectStore() self.commits = [] def cmt(self, n): return self.commits[n - 1] def assertMissingMatch(self, haves, wants, expected) -> None: for sha, path in MissingObjectFinder(self.store, haves, wants, shallow=set()): self.assertIn( sha, expected, f"({sha},{path}) erroneously reported as missing" ) expected.remove(sha) self.assertEqual( len(expected), 0, f"some objects are not reported as missing: {expected}", ) class MOFLinearRepoTest(MissingObjectFinderTest): def setUp(self) -> None: super().setUp() # present in 1, removed in 3 f1_1 = make_object(Blob, data=b"f1") # present in all revisions, changed in 2 and 3 f2_1 = make_object(Blob, data=b"f2") f2_2 = make_object(Blob, data=b"f2-changed") f2_3 = make_object(Blob, data=b"f2-changed-again") # added in 2, left unmodified in 3 f3_2 = make_object(Blob, data=b"f3") commit_spec = [[1], [2, 1], [3, 2]] trees = { 1: [(b"f1", f1_1), (b"f2", f2_1)], 2: [(b"f1", f1_1), (b"f2", f2_2), (b"f3", f3_2)], 3: [(b"f2", f2_3), (b"f3", f3_2)], } # commit 1: f1 and f2 # commit 2: f3 added, f2 changed. Missing shall report commit id and a # tree referenced by commit # commit 3: f1 removed, f2 changed. Commit sha and root tree sha shall # be reported as modified self.commits = build_commit_graph(self.store, commit_spec, trees) self.missing_1_2 = [self.cmt(2).id, self.cmt(2).tree, f2_2.id, f3_2.id] self.missing_2_3 = [self.cmt(3).id, self.cmt(3).tree, f2_3.id] self.missing_1_3 = [ self.cmt(2).id, self.cmt(3).id, self.cmt(2).tree, self.cmt(3).tree, f2_2.id, f3_2.id, f2_3.id, ] def test_1_to_2(self) -> None: self.assertMissingMatch([self.cmt(1).id], [self.cmt(2).id], self.missing_1_2) def test_2_to_3(self) -> None: self.assertMissingMatch([self.cmt(2).id], [self.cmt(3).id], self.missing_2_3) def test_1_to_3(self) -> None: self.assertMissingMatch([self.cmt(1).id], [self.cmt(3).id], self.missing_1_3) def test_bogus_haves(self) -> None: """Ensure non-existent SHA in haves are tolerated.""" bogus_sha = self.cmt(2).id[::-1] haves = [self.cmt(1).id, bogus_sha] wants = [self.cmt(3).id] self.assertMissingMatch(haves, wants, self.missing_1_3) def test_bogus_wants_failure(self) -> None: """Ensure non-existent SHA in wants are not tolerated.""" bogus_sha = self.cmt(2).id[::-1] haves = [self.cmt(1).id] wants = [self.cmt(3).id, bogus_sha] self.assertRaises( KeyError, MissingObjectFinder, self.store, haves, wants, shallow=set() ) def test_no_changes(self) -> None: self.assertMissingMatch([self.cmt(3).id], [self.cmt(3).id], []) class MOFMergeForkRepoTest(MissingObjectFinderTest): # 1 --- 2 --- 4 --- 6 --- 7 # \ / # 3 --- # \ # 5 def setUp(self) -> None: super().setUp() f1_1 = make_object(Blob, data=b"f1") f1_2 = make_object(Blob, data=b"f1-2") f1_4 = make_object(Blob, data=b"f1-4") f1_7 = make_object(Blob, data=b"f1-2") # same data as in rev 2 f2_1 = make_object(Blob, data=b"f2") f2_3 = make_object(Blob, data=b"f2-3") f3_3 = make_object(Blob, data=b"f3") f3_5 = make_object(Blob, data=b"f3-5") commit_spec = [[1], [2, 1], [3, 2], [4, 2], [5, 3], [6, 3, 4], [7, 6]] trees = { 1: [(b"f1", f1_1), (b"f2", f2_1)], 2: [(b"f1", f1_2), (b"f2", f2_1)], # f1 changed # f3 added, f2 changed 3: [(b"f1", f1_2), (b"f2", f2_3), (b"f3", f3_3)], 4: [(b"f1", f1_4), (b"f2", f2_1)], # f1 changed 5: [(b"f1", f1_2), (b"f3", f3_5)], # f2 removed, f3 changed # merged 3 and 4 6: [(b"f1", f1_4), (b"f2", f2_3), (b"f3", f3_3)], # f1 changed to match rev2. f3 removed 7: [(b"f1", f1_7), (b"f2", f2_3)], } self.commits = build_commit_graph(self.store, commit_spec, trees) self.f1_2_id = f1_2.id self.f1_4_id = f1_4.id self.f1_7_id = f1_7.id self.f2_3_id = f2_3.id self.f3_3_id = f3_3.id self.assertEqual(f1_2.id, f1_7.id, "[sanity]") def test_have6_want7(self) -> None: # have 6, want 7. Ideally, shall not report f1_7 as it's the same as # f1_2, however, to do so, MissingObjectFinder shall not record trees # of common commits only, but also all parent trees and tree items, # which is an overkill (i.e. in sha_done it records f1_4 as known, and # doesn't record f1_2 was known prior to that, hence can't detect f1_7 # is in fact f1_2 and shall not be reported) self.assertMissingMatch( [self.cmt(6).id], [self.cmt(7).id], [self.cmt(7).id, self.cmt(7).tree, self.f1_7_id], ) def test_have4_want7(self) -> None: # have 4, want 7. Shall not include rev5 as it is not in the tree # between 4 and 7 (well, it is, but its SHA's are irrelevant for 4..7 # commit hierarchy) self.assertMissingMatch( [self.cmt(4).id], [self.cmt(7).id], [ self.cmt(7).id, self.cmt(6).id, self.cmt(3).id, self.cmt(7).tree, self.cmt(6).tree, self.cmt(3).tree, self.f2_3_id, self.f3_3_id, ], ) def test_have1_want6(self) -> None: # have 1, want 6. Shall not include rev5 self.assertMissingMatch( [self.cmt(1).id], [self.cmt(6).id], [ self.cmt(6).id, self.cmt(4).id, self.cmt(3).id, self.cmt(2).id, self.cmt(6).tree, self.cmt(4).tree, self.cmt(3).tree, self.cmt(2).tree, self.f1_2_id, self.f1_4_id, self.f2_3_id, self.f3_3_id, ], ) def test_have3_want6(self) -> None: # have 3, want 7. Shall not report rev2 and its tree, because # haves(3) means has parents, i.e. rev2, too # BUT shall report any changes descending rev2 (excluding rev3) # Shall NOT report f1_7 as it's technically == f1_2 self.assertMissingMatch( [self.cmt(3).id], [self.cmt(7).id], [ self.cmt(7).id, self.cmt(6).id, self.cmt(4).id, self.cmt(7).tree, self.cmt(6).tree, self.cmt(4).tree, self.f1_4_id, ], ) def test_have5_want7(self) -> None: # have 5, want 7. Common parent is rev2, hence children of rev2 from # a descent line other than rev5 shall be reported # expects f1_4 from rev6. f3_5 is known in rev5; # f1_7 shall be the same as f1_2 (known, too) self.assertMissingMatch( [self.cmt(5).id], [self.cmt(7).id], [ self.cmt(7).id, self.cmt(6).id, self.cmt(4).id, self.cmt(7).tree, self.cmt(6).tree, self.cmt(4).tree, self.f1_4_id, ], ) class MOFTagsTest(MissingObjectFinderTest): def setUp(self) -> None: super().setUp() f1_1 = make_object(Blob, data=b"f1") commit_spec = [[1]] trees = {1: [(b"f1", f1_1)]} self.commits = build_commit_graph(self.store, commit_spec, trees) self._normal_tag = make_tag(self.cmt(1)) self.store.add_object(self._normal_tag) self._tag_of_tag = make_tag(self._normal_tag) self.store.add_object(self._tag_of_tag) self._tag_of_tree = make_tag(self.store[self.cmt(1).tree]) self.store.add_object(self._tag_of_tree) self._tag_of_blob = make_tag(f1_1) self.store.add_object(self._tag_of_blob) self._tag_of_tag_of_blob = make_tag(self._tag_of_blob) self.store.add_object(self._tag_of_tag_of_blob) self.f1_1_id = f1_1.id def test_tagged_commit(self) -> None: # The user already has the tagged commit, all they want is the tag, # so send them only the tag object. self.assertMissingMatch( [self.cmt(1).id], [self._normal_tag.id], [self._normal_tag.id] ) # The remaining cases are unusual, but do happen in the wild. def test_tagged_tag(self) -> None: # User already has tagged tag, send only tag of tag self.assertMissingMatch( [self._normal_tag.id], [self._tag_of_tag.id], [self._tag_of_tag.id] ) # User needs both tags, but already has commit self.assertMissingMatch( [self.cmt(1).id], [self._tag_of_tag.id], [self._normal_tag.id, self._tag_of_tag.id], ) def test_tagged_tree(self) -> None: self.assertMissingMatch( [], [self._tag_of_tree.id], [self._tag_of_tree.id, self.cmt(1).tree, self.f1_1_id], ) def test_tagged_blob(self) -> None: self.assertMissingMatch( [], [self._tag_of_blob.id], [self._tag_of_blob.id, self.f1_1_id] ) def test_tagged_tagged_blob(self) -> None: self.assertMissingMatch( [], [self._tag_of_tag_of_blob.id], [self._tag_of_tag_of_blob.id, self._tag_of_blob.id, self.f1_1_id], ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_object_store.py0000644000175100002000000004511514731042555020102 0ustar00runnerdocker# test_object_store.py -- tests for object_store.py # Copyright (C) 2008 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for the object store interface.""" import os import shutil import stat import sys import tempfile from contextlib import closing from io import BytesIO from dulwich.errors import NotTreeError from dulwich.index import commit_tree from dulwich.object_store import ( DiskObjectStore, MemoryObjectStore, ObjectStoreGraphWalker, OverlayObjectStore, commit_tree_changes, read_packs_file, tree_lookup_path, ) from dulwich.objects import ( S_IFGITLINK, Blob, EmptyFileException, SubmoduleEncountered, Tree, TreeEntry, sha_to_hex, ) from dulwich.pack import REF_DELTA, write_pack_objects from dulwich.tests.test_object_store import ObjectStoreTests, PackBasedObjectStoreTests from dulwich.tests.utils import build_pack, make_object from . import TestCase testobject = make_object(Blob, data=b"yummy data") class OverlayObjectStoreTests(ObjectStoreTests, TestCase): def setUp(self) -> None: TestCase.setUp(self) self.bases = [MemoryObjectStore(), MemoryObjectStore()] self.store = OverlayObjectStore(self.bases, self.bases[0]) class MemoryObjectStoreTests(ObjectStoreTests, TestCase): def setUp(self) -> None: TestCase.setUp(self) self.store = MemoryObjectStore() def test_add_pack(self) -> None: o = MemoryObjectStore() f, commit, abort = o.add_pack() try: b = make_object(Blob, data=b"more yummy data") write_pack_objects(f.write, [(b, None)]) except BaseException: abort() raise else: commit() def test_add_pack_emtpy(self) -> None: o = MemoryObjectStore() f, commit, abort = o.add_pack() commit() def test_add_thin_pack(self) -> None: o = MemoryObjectStore() blob = make_object(Blob, data=b"yummy data") o.add_object(blob) f = BytesIO() entries = build_pack( f, [ (REF_DELTA, (blob.id, b"more yummy data")), ], store=o, ) o.add_thin_pack(f.read, None) packed_blob_sha = sha_to_hex(entries[0][3]) self.assertEqual( (Blob.type_num, b"more yummy data"), o.get_raw(packed_blob_sha) ) def test_add_thin_pack_empty(self) -> None: o = MemoryObjectStore() f = BytesIO() entries = build_pack(f, [], store=o) self.assertEqual([], entries) o.add_thin_pack(f.read, None) class DiskObjectStoreTests(PackBasedObjectStoreTests, TestCase): def setUp(self) -> None: TestCase.setUp(self) self.store_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.store_dir) self.store = DiskObjectStore.init(self.store_dir) def tearDown(self) -> None: TestCase.tearDown(self) PackBasedObjectStoreTests.tearDown(self) def test_loose_compression_level(self) -> None: alternate_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, alternate_dir) alternate_store = DiskObjectStore(alternate_dir, loose_compression_level=6) b2 = make_object(Blob, data=b"yummy data") alternate_store.add_object(b2) def test_alternates(self) -> None: alternate_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, alternate_dir) alternate_store = DiskObjectStore(alternate_dir) b2 = make_object(Blob, data=b"yummy data") alternate_store.add_object(b2) store = DiskObjectStore(self.store_dir) self.assertRaises(KeyError, store.__getitem__, b2.id) store.add_alternate_path(alternate_dir) self.assertIn(b2.id, store) self.assertEqual(b2, store[b2.id]) def test_read_alternate_paths(self) -> None: store = DiskObjectStore(self.store_dir) abs_path = os.path.abspath(os.path.normpath("/abspath")) # ensures in particular existence of the alternates file store.add_alternate_path(abs_path) self.assertEqual(set(store._read_alternate_paths()), {abs_path}) store.add_alternate_path("relative-path") self.assertIn( os.path.join(store.path, "relative-path"), set(store._read_alternate_paths()), ) # arguably, add_alternate_path() could strip comments. # Meanwhile it's more convenient to use it than to import INFODIR store.add_alternate_path("# comment") for alt_path in store._read_alternate_paths(): self.assertNotIn("#", alt_path) def test_file_modes(self) -> None: self.store.add_object(testobject) path = self.store._get_shafile_path(testobject.id) mode = os.stat(path).st_mode packmode = "0o100444" if sys.platform != "win32" else "0o100666" self.assertEqual(oct(mode), packmode) def test_corrupted_object_raise_exception(self) -> None: """Corrupted sha1 disk file should raise specific exception.""" self.store.add_object(testobject) self.assertEqual( (Blob.type_num, b"yummy data"), self.store.get_raw(testobject.id) ) self.assertTrue(self.store.contains_loose(testobject.id)) self.assertIsNotNone(self.store._get_loose_object(testobject.id)) path = self.store._get_shafile_path(testobject.id) old_mode = os.stat(path).st_mode os.chmod(path, 0o600) with open(path, "wb") as f: # corrupt the file f.write(b"") os.chmod(path, old_mode) expected_error_msg = "Corrupted empty file detected" try: self.store.contains_loose(testobject.id) except EmptyFileException as e: self.assertEqual(str(e), expected_error_msg) try: self.store._get_loose_object(testobject.id) except EmptyFileException as e: self.assertEqual(str(e), expected_error_msg) # this does not change iteration on loose objects though self.assertEqual([testobject.id], list(self.store._iter_loose_objects())) def test_tempfile_in_loose_store(self) -> None: self.store.add_object(testobject) self.assertEqual([testobject.id], list(self.store._iter_loose_objects())) # add temporary files to the loose store for i in range(256): dirname = os.path.join(self.store_dir, f"{i:02x}") if not os.path.isdir(dirname): os.makedirs(dirname) fd, n = tempfile.mkstemp(prefix="tmp_obj_", dir=dirname) os.close(fd) self.assertEqual([testobject.id], list(self.store._iter_loose_objects())) def test_add_alternate_path(self) -> None: store = DiskObjectStore(self.store_dir) self.assertEqual([], list(store._read_alternate_paths())) store.add_alternate_path(os.path.abspath("/foo/path")) self.assertEqual( [os.path.abspath("/foo/path")], list(store._read_alternate_paths()) ) if sys.platform == "win32": store.add_alternate_path("D:\\bar\\path") else: store.add_alternate_path("/bar/path") if sys.platform == "win32": self.assertEqual( [os.path.abspath("/foo/path"), "D:\\bar\\path"], list(store._read_alternate_paths()), ) else: self.assertEqual( [os.path.abspath("/foo/path"), "/bar/path"], list(store._read_alternate_paths()), ) def test_rel_alternative_path(self) -> None: alternate_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, alternate_dir) alternate_store = DiskObjectStore(alternate_dir) b2 = make_object(Blob, data=b"yummy data") alternate_store.add_object(b2) store = DiskObjectStore(self.store_dir) self.assertRaises(KeyError, store.__getitem__, b2.id) store.add_alternate_path(os.path.relpath(alternate_dir, self.store_dir)) self.assertEqual(list(alternate_store), list(store.alternates[0])) self.assertIn(b2.id, store) self.assertEqual(b2, store[b2.id]) def test_pack_dir(self) -> None: o = DiskObjectStore(self.store_dir) self.assertEqual(os.path.join(self.store_dir, "pack"), o.pack_dir) def test_add_pack(self) -> None: o = DiskObjectStore(self.store_dir) self.addCleanup(o.close) f, commit, abort = o.add_pack() try: b = make_object(Blob, data=b"more yummy data") write_pack_objects(f.write, [(b, None)]) except BaseException: abort() raise else: commit() def test_add_thin_pack(self) -> None: o = DiskObjectStore(self.store_dir) try: blob = make_object(Blob, data=b"yummy data") o.add_object(blob) f = BytesIO() entries = build_pack( f, [ (REF_DELTA, (blob.id, b"more yummy data")), ], store=o, ) with o.add_thin_pack(f.read, None) as pack: packed_blob_sha = sha_to_hex(entries[0][3]) pack.check_length_and_checksum() self.assertEqual(sorted([blob.id, packed_blob_sha]), list(pack)) self.assertTrue(o.contains_packed(packed_blob_sha)) self.assertTrue(o.contains_packed(blob.id)) self.assertEqual( (Blob.type_num, b"more yummy data"), o.get_raw(packed_blob_sha), ) finally: o.close() def test_add_thin_pack_empty(self) -> None: with closing(DiskObjectStore(self.store_dir)) as o: f = BytesIO() entries = build_pack(f, [], store=o) self.assertEqual([], entries) o.add_thin_pack(f.read, None) class TreeLookupPathTests(TestCase): def setUp(self) -> None: TestCase.setUp(self) self.store = MemoryObjectStore() blob_a = make_object(Blob, data=b"a") blob_b = make_object(Blob, data=b"b") blob_c = make_object(Blob, data=b"c") for blob in [blob_a, blob_b, blob_c]: self.store.add_object(blob) blobs = [ (b"a", blob_a.id, 0o100644), (b"ad/b", blob_b.id, 0o100644), (b"ad/bd/c", blob_c.id, 0o100755), (b"ad/c", blob_c.id, 0o100644), (b"c", blob_c.id, 0o100644), (b"d", blob_c.id, S_IFGITLINK), ] self.tree_id = commit_tree(self.store, blobs) def get_object(self, sha): return self.store[sha] def test_lookup_blob(self) -> None: o_id = tree_lookup_path(self.get_object, self.tree_id, b"a")[1] self.assertIsInstance(self.store[o_id], Blob) def test_lookup_tree(self) -> None: o_id = tree_lookup_path(self.get_object, self.tree_id, b"ad")[1] self.assertIsInstance(self.store[o_id], Tree) o_id = tree_lookup_path(self.get_object, self.tree_id, b"ad/bd")[1] self.assertIsInstance(self.store[o_id], Tree) o_id = tree_lookup_path(self.get_object, self.tree_id, b"ad/bd/")[1] self.assertIsInstance(self.store[o_id], Tree) def test_lookup_submodule(self) -> None: tree_lookup_path(self.get_object, self.tree_id, b"d")[1] self.assertRaises( SubmoduleEncountered, tree_lookup_path, self.get_object, self.tree_id, b"d/a", ) def test_lookup_nonexistent(self) -> None: self.assertRaises( KeyError, tree_lookup_path, self.get_object, self.tree_id, b"j" ) def test_lookup_not_tree(self) -> None: self.assertRaises( NotTreeError, tree_lookup_path, self.get_object, self.tree_id, b"ad/b/j", ) class ObjectStoreGraphWalkerTests(TestCase): def get_walker(self, heads, parent_map): new_parent_map = { k * 40: [(p * 40) for p in ps] for (k, ps) in parent_map.items() } return ObjectStoreGraphWalker( [x * 40 for x in heads], new_parent_map.__getitem__ ) def test_ack_invalid_value(self) -> None: gw = self.get_walker([], {}) self.assertRaises(ValueError, gw.ack, "tooshort") def test_empty(self) -> None: gw = self.get_walker([], {}) self.assertIs(None, next(gw)) gw.ack(b"a" * 40) self.assertIs(None, next(gw)) def test_descends(self) -> None: gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": []}) self.assertEqual(b"a" * 40, next(gw)) self.assertEqual(b"b" * 40, next(gw)) def test_present(self) -> None: gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": []}) gw.ack(b"a" * 40) self.assertIs(None, next(gw)) def test_parent_present(self) -> None: gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": []}) self.assertEqual(b"a" * 40, next(gw)) gw.ack(b"a" * 40) self.assertIs(None, next(gw)) def test_child_ack_later(self) -> None: gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": [b"c"], b"c": []}) self.assertEqual(b"a" * 40, next(gw)) self.assertEqual(b"b" * 40, next(gw)) gw.ack(b"a" * 40) self.assertIs(None, next(gw)) def test_only_once(self) -> None: # a b # | | # c d # \ / # e gw = self.get_walker( [b"a", b"b"], { b"a": [b"c"], b"b": [b"d"], b"c": [b"e"], b"d": [b"e"], b"e": [], }, ) walk = [] acked = False walk.append(next(gw)) walk.append(next(gw)) # A branch (a, c) or (b, d) may be done after 2 steps or 3 depending on # the order walked: 3-step walks include (a, b, c) and (b, a, d), etc. if walk == [b"a" * 40, b"c" * 40] or walk == [b"b" * 40, b"d" * 40]: gw.ack(walk[0]) acked = True walk.append(next(gw)) if not acked and walk[2] == b"c" * 40: gw.ack(b"a" * 40) elif not acked and walk[2] == b"d" * 40: gw.ack(b"b" * 40) walk.append(next(gw)) self.assertIs(None, next(gw)) self.assertEqual([b"a" * 40, b"b" * 40, b"c" * 40, b"d" * 40], sorted(walk)) self.assertLess(walk.index(b"a" * 40), walk.index(b"c" * 40)) self.assertLess(walk.index(b"b" * 40), walk.index(b"d" * 40)) class CommitTreeChangesTests(TestCase): def setUp(self) -> None: super().setUp() self.store = MemoryObjectStore() self.blob_a = make_object(Blob, data=b"a") self.blob_b = make_object(Blob, data=b"b") self.blob_c = make_object(Blob, data=b"c") for blob in [self.blob_a, self.blob_b, self.blob_c]: self.store.add_object(blob) blobs = [ (b"a", self.blob_a.id, 0o100644), (b"ad/b", self.blob_b.id, 0o100644), (b"ad/bd/c", self.blob_c.id, 0o100755), (b"ad/c", self.blob_c.id, 0o100644), (b"c", self.blob_c.id, 0o100644), ] self.tree_id = commit_tree(self.store, blobs) def test_no_changes(self) -> None: self.assertEqual( self.store[self.tree_id], commit_tree_changes(self.store, self.store[self.tree_id], []), ) def test_add_blob(self) -> None: blob_d = make_object(Blob, data=b"d") new_tree = commit_tree_changes( self.store, self.store[self.tree_id], [(b"d", 0o100644, blob_d.id)] ) self.assertEqual( new_tree[b"d"], (33188, b"c59d9b6344f1af00e504ba698129f07a34bbed8d"), ) def test_add_blob_in_dir(self) -> None: blob_d = make_object(Blob, data=b"d") new_tree = commit_tree_changes( self.store, self.store[self.tree_id], [(b"e/f/d", 0o100644, blob_d.id)], ) self.assertEqual( new_tree.items(), [ TreeEntry(path=b"a", mode=stat.S_IFREG | 0o100644, sha=self.blob_a.id), TreeEntry( path=b"ad", mode=stat.S_IFDIR, sha=b"0e2ce2cd7725ff4817791be31ccd6e627e801f4a", ), TreeEntry(path=b"c", mode=stat.S_IFREG | 0o100644, sha=self.blob_c.id), TreeEntry( path=b"e", mode=stat.S_IFDIR, sha=b"6ab344e288724ac2fb38704728b8896e367ed108", ), ], ) e_tree = self.store[new_tree[b"e"][1]] self.assertEqual( e_tree.items(), [ TreeEntry( path=b"f", mode=stat.S_IFDIR, sha=b"24d2c94d8af232b15a0978c006bf61ef4479a0a5", ) ], ) f_tree = self.store[e_tree[b"f"][1]] self.assertEqual( f_tree.items(), [TreeEntry(path=b"d", mode=stat.S_IFREG | 0o100644, sha=blob_d.id)], ) def test_delete_blob(self) -> None: new_tree = commit_tree_changes( self.store, self.store[self.tree_id], [(b"ad/bd/c", None, None)] ) self.assertEqual(set(new_tree), {b"a", b"ad", b"c"}) ad_tree = self.store[new_tree[b"ad"][1]] self.assertEqual(set(ad_tree), {b"b", b"c"}) class TestReadPacksFile(TestCase): def test_read_packs(self) -> None: self.assertEqual( ["pack-1.pack"], list( read_packs_file( BytesIO( b"""P pack-1.pack """ ) ) ), ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_objects.py0000644000175100002000000015501114731042555017046 0ustar00runnerdocker# test_objects.py -- tests for objects.py # Copyright (C) 2007 James Westby # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for git base objects.""" # TODO: Round-trip parse-serialize-parse and serialize-parse-serialize tests. import datetime import os import stat from contextlib import contextmanager from io import BytesIO from itertools import permutations from dulwich.errors import ObjectFormatException from dulwich.objects import ( MAX_TIME, Blob, Commit, ShaFile, Tag, Tree, TreeEntry, _parse_tree_py, _sorted_tree_items_py, check_hexsha, check_identity, format_timezone, hex_to_filename, hex_to_sha, key_entry, object_class, parse_timezone, pretty_format_tree_entry, sha_to_hex, ) try: from dulwich.objects import _parse_tree_rs, _sorted_tree_items_rs except ImportError: _sorted_tree_items_rs = _parse_tree_rs = None from dulwich.tests.utils import ( ext_functest_builder, functest_builder, make_commit, make_object, ) from . import TestCase a_sha = b"6f670c0fb53f9463760b7295fbb814e965fb20c8" b_sha = b"2969be3e8ee1c0222396a5611407e4769f14e54b" c_sha = b"954a536f7819d40e6f637f849ee187dd10066349" tree_sha = b"70c190eb48fa8bbb50ddc692a17b44cb781af7f6" tag_sha = b"71033db03a03c6a36721efcf1968dd8f8e0cf023" class TestHexToSha(TestCase): def test_simple(self) -> None: self.assertEqual(b"\xab\xcd" * 10, hex_to_sha(b"abcd" * 10)) def test_reverse(self) -> None: self.assertEqual(b"abcd" * 10, sha_to_hex(b"\xab\xcd" * 10)) class BlobReadTests(TestCase): """Test decompression of blobs.""" def get_sha_file(self, cls, base, sha): dir = os.path.join(os.path.dirname(__file__), "..", "testdata", base) return cls.from_path(hex_to_filename(dir, sha)) def get_blob(self, sha): """Return the blob named sha from the test data dir.""" return self.get_sha_file(Blob, "blobs", sha) def get_tree(self, sha): return self.get_sha_file(Tree, "trees", sha) def get_tag(self, sha): return self.get_sha_file(Tag, "tags", sha) def commit(self, sha): return self.get_sha_file(Commit, "commits", sha) def test_decompress_simple_blob(self) -> None: b = self.get_blob(a_sha) self.assertEqual(b.data, b"test 1\n") self.assertEqual(b.sha().hexdigest().encode("ascii"), a_sha) def test_hash(self) -> None: b = self.get_blob(a_sha) self.assertEqual(hash(b.id), hash(b)) def test_parse_empty_blob_object(self) -> None: sha = b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391" b = self.get_blob(sha) self.assertEqual(b.data, b"") self.assertEqual(b.id, sha) self.assertEqual(b.sha().hexdigest().encode("ascii"), sha) def test_create_blob_from_string(self) -> None: string = b"test 2\n" b = Blob.from_string(string) self.assertEqual(b.data, string) self.assertEqual(b.sha().hexdigest().encode("ascii"), b_sha) def test_legacy_from_file(self) -> None: b1 = Blob.from_string(b"foo") b_raw = b1.as_legacy_object() b2 = b1.from_file(BytesIO(b_raw)) self.assertEqual(b1, b2) def test_legacy_from_file_compression_level(self) -> None: b1 = Blob.from_string(b"foo") b_raw = b1.as_legacy_object(compression_level=6) b2 = b1.from_file(BytesIO(b_raw)) self.assertEqual(b1, b2) def test_chunks(self) -> None: string = b"test 5\n" b = Blob.from_string(string) self.assertEqual([string], b.chunked) def test_splitlines(self) -> None: for case in [ [], [b"foo\nbar\n"], [b"bl\na", b"blie"], [b"bl\na", b"blie", b"bloe\n"], [b"", b"bl\na", b"blie", b"bloe\n"], [b"", b"", b"", b"bla\n"], [b"", b"", b"", b"bla\n", b""], [b"bl", b"", b"a\naaa"], [b"a\naaa", b"a"], ]: b = Blob() b.chunked = case self.assertEqual(b.data.splitlines(True), b.splitlines()) def test_set_chunks(self) -> None: b = Blob() b.chunked = [b"te", b"st", b" 5\n"] self.assertEqual(b"test 5\n", b.data) b.chunked = [b"te", b"st", b" 6\n"] self.assertEqual(b"test 6\n", b.as_raw_string()) self.assertEqual(b"test 6\n", bytes(b)) def test_parse_legacy_blob(self) -> None: string = b"test 3\n" b = self.get_blob(c_sha) self.assertEqual(b.data, string) self.assertEqual(b.sha().hexdigest().encode("ascii"), c_sha) def test_eq(self) -> None: blob1 = self.get_blob(a_sha) blob2 = self.get_blob(a_sha) self.assertEqual(blob1, blob2) def test_read_tree_from_file(self) -> None: t = self.get_tree(tree_sha) self.assertEqual(t.items()[0], (b"a", 33188, a_sha)) self.assertEqual(t.items()[1], (b"b", 33188, b_sha)) def test_read_tree_from_file_parse_count(self) -> None: old_deserialize = Tree._deserialize def reset_deserialize() -> None: Tree._deserialize = old_deserialize self.addCleanup(reset_deserialize) self.deserialize_count = 0 def counting_deserialize(*args, **kwargs): self.deserialize_count += 1 return old_deserialize(*args, **kwargs) Tree._deserialize = counting_deserialize t = self.get_tree(tree_sha) self.assertEqual(t.items()[0], (b"a", 33188, a_sha)) self.assertEqual(t.items()[1], (b"b", 33188, b_sha)) self.assertEqual(self.deserialize_count, 1) def test_read_tag_from_file(self) -> None: t = self.get_tag(tag_sha) self.assertEqual( t.object, (Commit, b"51b668fd5bf7061b7d6fa525f88803e6cfadaa51") ) self.assertEqual(t.name, b"signed") self.assertEqual(t.tagger, b"Ali Sabil ") self.assertEqual(t.tag_time, 1231203091) self.assertEqual(t.message, b"This is a signed tag\n") self.assertEqual( t.signature, b"-----BEGIN PGP SIGNATURE-----\n" b"Version: GnuPG v1.4.9 (GNU/Linux)\n" b"\n" b"iEYEABECAAYFAkliqx8ACgkQqSMmLy9u/" b"kcx5ACfakZ9NnPl02tOyYP6pkBoEkU1\n" b"5EcAn0UFgokaSvS371Ym/4W9iJj6vh3h\n" b"=ql7y\n" b"-----END PGP SIGNATURE-----\n", ) self.assertEqual(t.raw_without_sig() + t.signature, bytes(t)) def test_read_commit_from_file(self) -> None: sha = b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e" c = self.commit(sha) self.assertEqual(c.tree, tree_sha) self.assertEqual(c.parents, [b"0d89f20333fbb1d2f3a94da77f4981373d8f4310"]) self.assertEqual(c.author, b"James Westby ") self.assertEqual(c.committer, b"James Westby ") self.assertEqual(c.commit_time, 1174759230) self.assertEqual(c.commit_timezone, 0) self.assertEqual(c.author_timezone, 0) self.assertEqual(c.message, b"Test commit\n") def test_read_commit_no_parents(self) -> None: sha = b"0d89f20333fbb1d2f3a94da77f4981373d8f4310" c = self.commit(sha) self.assertEqual(c.tree, b"90182552c4a85a45ec2a835cadc3451bebdfe870") self.assertEqual(c.parents, []) self.assertEqual(c.author, b"James Westby ") self.assertEqual(c.committer, b"James Westby ") self.assertEqual(c.commit_time, 1174758034) self.assertEqual(c.commit_timezone, 0) self.assertEqual(c.author_timezone, 0) self.assertEqual(c.message, b"Test commit\n") def test_read_commit_two_parents(self) -> None: sha = b"5dac377bdded4c9aeb8dff595f0faeebcc8498cc" c = self.commit(sha) self.assertEqual(c.tree, b"d80c186a03f423a81b39df39dc87fd269736ca86") self.assertEqual( c.parents, [ b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd", b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6", ], ) self.assertEqual(c.author, b"James Westby ") self.assertEqual(c.committer, b"James Westby ") self.assertEqual(c.commit_time, 1174773719) self.assertEqual(c.commit_timezone, 0) self.assertEqual(c.author_timezone, 0) self.assertEqual(c.message, b"Merge ../b\n") def test_stub_sha(self) -> None: sha = b"5" * 40 c = make_commit(id=sha, message=b"foo") self.assertIsInstance(c, Commit) self.assertEqual(sha, c.id) self.assertNotEqual(sha, c.sha()) class ShaFileCheckTests(TestCase): def assertCheckFails(self, cls, data) -> None: obj = cls() def do_check() -> None: obj.set_raw_string(data) obj.check() self.assertRaises(ObjectFormatException, do_check) def assertCheckSucceeds(self, cls, data) -> None: obj = cls() obj.set_raw_string(data) self.assertEqual(None, obj.check()) small_buffer_zlib_object = ( b"\x48\x89\x15\xcc\x31\x0e\xc2\x30\x0c\x40\x51\xe6" b"\x9c\xc2\x3b\xaa\x64\x37\xc4\xc1\x12\x42\x5c\xc5" b"\x49\xac\x52\xd4\x92\xaa\x78\xe1\xf6\x94\xed\xeb" b"\x0d\xdf\x75\x02\xa2\x7c\xea\xe5\x65\xd5\x81\x8b" b"\x9a\x61\xba\xa0\xa9\x08\x36\xc9\x4c\x1a\xad\x88" b"\x16\xba\x46\xc4\xa8\x99\x6a\x64\xe1\xe0\xdf\xcd" b"\xa0\xf6\x75\x9d\x3d\xf8\xf1\xd0\x77\xdb\xfb\xdc" b"\x86\xa3\x87\xf1\x2f\x93\xed\x00\xb7\xc7\xd2\xab" b"\x2e\xcf\xfe\xf1\x3b\x50\xa4\x91\x53\x12\x24\x38" b"\x23\x21\x86\xf0\x03\x2f\x91\x24\x52" ) class ShaFileTests(TestCase): def test_deflated_smaller_window_buffer(self) -> None: # zlib on some systems uses smaller buffers, # resulting in a different header. # See https://github.com/libgit2/libgit2/pull/464 sf = ShaFile.from_file(BytesIO(small_buffer_zlib_object)) self.assertEqual(sf.type_name, b"tag") self.assertEqual(sf.tagger, b" <@localhost>") class CommitSerializationTests(TestCase): def make_commit(self, **kwargs): attrs = { "tree": b"d80c186a03f423a81b39df39dc87fd269736ca86", "parents": [ b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd", b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6", ], "author": b"James Westby ", "committer": b"James Westby ", "commit_time": 1174773719, "author_time": 1174773719, "commit_timezone": 0, "author_timezone": 0, "message": b"Merge ../b\n", } attrs.update(kwargs) return make_commit(**attrs) def test_encoding(self) -> None: c = self.make_commit(encoding=b"iso8859-1") self.assertIn(b"encoding iso8859-1\n", c.as_raw_string()) def test_short_timestamp(self) -> None: c = self.make_commit(commit_time=30) c1 = Commit() c1.set_raw_string(c.as_raw_string()) self.assertEqual(30, c1.commit_time) def test_full_tree(self) -> None: c = self.make_commit(commit_time=30) t = Tree() t.add(b"data-x", 0o644, Blob().id) c.tree = t c1 = Commit() c1.set_raw_string(c.as_raw_string()) self.assertEqual(t.id, c1.tree) self.assertEqual(c.as_raw_string(), c1.as_raw_string()) def test_raw_length(self) -> None: c = self.make_commit() self.assertEqual(len(c.as_raw_string()), c.raw_length()) def test_simple(self) -> None: c = self.make_commit() self.assertEqual(c.id, b"5dac377bdded4c9aeb8dff595f0faeebcc8498cc") self.assertEqual( b"tree d80c186a03f423a81b39df39dc87fd269736ca86\n" b"parent ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd\n" b"parent 4cffe90e0a41ad3f5190079d7c8f036bde29cbe6\n" b"author James Westby " b"1174773719 +0000\n" b"committer James Westby " b"1174773719 +0000\n" b"\n" b"Merge ../b\n", c.as_raw_string(), ) def test_timezone(self) -> None: c = self.make_commit(commit_timezone=(5 * 60)) self.assertIn(b" +0005\n", c.as_raw_string()) def test_neg_timezone(self) -> None: c = self.make_commit(commit_timezone=(-1 * 3600)) self.assertIn(b" -0100\n", c.as_raw_string()) def test_deserialize(self) -> None: c = self.make_commit() d = Commit() d._deserialize(c.as_raw_chunks()) self.assertEqual(c, d) def test_serialize_gpgsig(self) -> None: gpgsig = b"""-----BEGIN PGP SIGNATURE----- Version: GnuPG v1 iQIcBAABCgAGBQJULCdfAAoJEACAbyvXKaRXuKwP/RyP9PA49uAvu8tQVCC/uBa8 vi975+xvO14R8Pp8k2nps7lSxCdtCd+xVT1VRHs0wNhOZo2YCVoU1HATkPejqSeV NScTHcxnk4/+bxyfk14xvJkNp7FlQ3npmBkA+lbV0Ubr33rvtIE5jiJPyz+SgWAg xdBG2TojV0squj00GoH/euK6aX7GgZtwdtpTv44haCQdSuPGDcI4TORqR6YSqvy3 GPE+3ZqXPFFb+KILtimkxitdwB7CpwmNse2vE3rONSwTvi8nq3ZoQYNY73CQGkUy qoFU0pDtw87U3niFin1ZccDgH0bB6624sLViqrjcbYJeg815Htsu4rmzVaZADEVC XhIO4MThebusdk0AcNGjgpf3HRHk0DPMDDlIjm+Oao0cqovvF6VyYmcb0C+RmhJj dodLXMNmbqErwTk3zEkW0yZvNIYXH7m9SokPCZa4eeIM7be62X6h1mbt0/IU6Th+ v18fS0iTMP/Viug5und+05C/v04kgDo0CPphAbXwWMnkE4B6Tl9sdyUYXtvQsL7x 0+WP1gL27ANqNZiI07Kz/BhbBAQI/+2TFT7oGr0AnFPQ5jHp+3GpUf6OKuT1wT3H ND189UFuRuubxb42vZhpcXRbqJVWnbECTKVUPsGZqat3enQUB63uM4i6/RdONDZA fDeF1m4qYs+cUXKNUZ03 =X6RT -----END PGP SIGNATURE-----""" pre_sig = b"""\ tree d80c186a03f423a81b39df39dc87fd269736ca86 parent ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd parent 4cffe90e0a41ad3f5190079d7c8f036bde29cbe6 author James Westby 1174773719 +0000 committer James Westby 1174773719 +0000 """ git_sig = b"""\ gpgsig -----BEGIN PGP SIGNATURE----- Version: GnuPG v1 iQIcBAABCgAGBQJULCdfAAoJEACAbyvXKaRXuKwP/RyP9PA49uAvu8tQVCC/uBa8 vi975+xvO14R8Pp8k2nps7lSxCdtCd+xVT1VRHs0wNhOZo2YCVoU1HATkPejqSeV NScTHcxnk4/+bxyfk14xvJkNp7FlQ3npmBkA+lbV0Ubr33rvtIE5jiJPyz+SgWAg xdBG2TojV0squj00GoH/euK6aX7GgZtwdtpTv44haCQdSuPGDcI4TORqR6YSqvy3 GPE+3ZqXPFFb+KILtimkxitdwB7CpwmNse2vE3rONSwTvi8nq3ZoQYNY73CQGkUy qoFU0pDtw87U3niFin1ZccDgH0bB6624sLViqrjcbYJeg815Htsu4rmzVaZADEVC XhIO4MThebusdk0AcNGjgpf3HRHk0DPMDDlIjm+Oao0cqovvF6VyYmcb0C+RmhJj dodLXMNmbqErwTk3zEkW0yZvNIYXH7m9SokPCZa4eeIM7be62X6h1mbt0/IU6Th+ v18fS0iTMP/Viug5und+05C/v04kgDo0CPphAbXwWMnkE4B6Tl9sdyUYXtvQsL7x 0+WP1gL27ANqNZiI07Kz/BhbBAQI/+2TFT7oGr0AnFPQ5jHp+3GpUf6OKuT1wT3H ND189UFuRuubxb42vZhpcXRbqJVWnbECTKVUPsGZqat3enQUB63uM4i6/RdONDZA fDeF1m4qYs+cUXKNUZ03 =X6RT -----END PGP SIGNATURE----- """ post_sig = b"""\ Merge ../b """ commit = self.make_commit(gpgsig=gpgsig) self.maxDiff = None self.assertEqual(pre_sig + git_sig + post_sig, commit.as_raw_string()) self.assertEqual(pre_sig + post_sig, commit.raw_without_sig()) self.assertEqual(gpgsig, commit.gpgsig) self.assertEqual(b"Merge ../b\n", commit.message) def test_serialize_mergetag(self) -> None: tag = make_object( Tag, object=(Commit, b"a38d6181ff27824c79fc7df825164a212eff6a3f"), object_type_name=b"commit", name=b"v2.6.22-rc7", tag_time=1183319674, tag_timezone=0, tagger=b"Linus Torvalds ", message=default_message, ) commit = self.make_commit(mergetag=[tag]) self.assertEqual( b"""tree d80c186a03f423a81b39df39dc87fd269736ca86 parent ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd parent 4cffe90e0a41ad3f5190079d7c8f036bde29cbe6 author James Westby 1174773719 +0000 committer James Westby 1174773719 +0000 mergetag object a38d6181ff27824c79fc7df825164a212eff6a3f type commit tag v2.6.22-rc7 tagger Linus Torvalds 1183319674 +0000 Linux 2.6.22-rc7 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql OK2XeQOiEeXtT76rV4t2WR4= =ivrA -----END PGP SIGNATURE----- Merge ../b """, commit.as_raw_string(), ) def test_serialize_mergetags(self) -> None: tag = make_object( Tag, object=(Commit, b"a38d6181ff27824c79fc7df825164a212eff6a3f"), object_type_name=b"commit", name=b"v2.6.22-rc7", tag_time=1183319674, tag_timezone=0, tagger=b"Linus Torvalds ", message=default_message, ) commit = self.make_commit(mergetag=[tag, tag]) self.assertEqual( b"""tree d80c186a03f423a81b39df39dc87fd269736ca86 parent ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd parent 4cffe90e0a41ad3f5190079d7c8f036bde29cbe6 author James Westby 1174773719 +0000 committer James Westby 1174773719 +0000 mergetag object a38d6181ff27824c79fc7df825164a212eff6a3f type commit tag v2.6.22-rc7 tagger Linus Torvalds 1183319674 +0000 Linux 2.6.22-rc7 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql OK2XeQOiEeXtT76rV4t2WR4= =ivrA -----END PGP SIGNATURE----- mergetag object a38d6181ff27824c79fc7df825164a212eff6a3f type commit tag v2.6.22-rc7 tagger Linus Torvalds 1183319674 +0000 Linux 2.6.22-rc7 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql OK2XeQOiEeXtT76rV4t2WR4= =ivrA -----END PGP SIGNATURE----- Merge ../b """, commit.as_raw_string(), ) def test_deserialize_mergetag(self) -> None: tag = make_object( Tag, object=(Commit, b"a38d6181ff27824c79fc7df825164a212eff6a3f"), object_type_name=b"commit", name=b"v2.6.22-rc7", tag_time=1183319674, tag_timezone=0, tagger=b"Linus Torvalds ", message=default_message, ) commit = self.make_commit(mergetag=[tag]) d = Commit() d._deserialize(commit.as_raw_chunks()) self.assertEqual(commit, d) def test_deserialize_mergetags(self) -> None: tag = make_object( Tag, object=(Commit, b"a38d6181ff27824c79fc7df825164a212eff6a3f"), object_type_name=b"commit", name=b"v2.6.22-rc7", tag_time=1183319674, tag_timezone=0, tagger=b"Linus Torvalds ", message=default_message, ) commit = self.make_commit(mergetag=[tag, tag]) d = Commit() d._deserialize(commit.as_raw_chunks()) self.assertEqual(commit, d) default_committer = b"James Westby 1174773719 +0000" class CommitParseTests(ShaFileCheckTests): def make_commit_lines( self, tree=b"d80c186a03f423a81b39df39dc87fd269736ca86", parents=[ b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd", b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6", ], author=default_committer, committer=default_committer, encoding=None, message=b"Merge ../b\n", extra=None, ): lines = [] if tree is not None: lines.append(b"tree " + tree) if parents is not None: lines.extend(b"parent " + p for p in parents) if author is not None: lines.append(b"author " + author) if committer is not None: lines.append(b"committer " + committer) if encoding is not None: lines.append(b"encoding " + encoding) if extra is not None: for name, value in sorted(extra.items()): lines.append(name + b" " + value) lines.append(b"") if message is not None: lines.append(message) return lines def make_commit_text(self, **kwargs): return b"\n".join(self.make_commit_lines(**kwargs)) def test_simple(self) -> None: c = Commit.from_string(self.make_commit_text()) self.assertEqual(b"Merge ../b\n", c.message) self.assertEqual(b"James Westby ", c.author) self.assertEqual(b"James Westby ", c.committer) self.assertEqual(b"d80c186a03f423a81b39df39dc87fd269736ca86", c.tree) self.assertEqual( [ b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd", b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6", ], c.parents, ) expected_time = datetime.datetime(2007, 3, 24, 22, 1, 59) self.assertEqual( expected_time, datetime.datetime.utcfromtimestamp(c.commit_time) ) self.assertEqual(0, c.commit_timezone) self.assertEqual( expected_time, datetime.datetime.utcfromtimestamp(c.author_time) ) self.assertEqual(0, c.author_timezone) self.assertEqual(None, c.encoding) def test_custom(self) -> None: c = Commit.from_string(self.make_commit_text(extra={b"extra-field": b"data"})) self.assertEqual([(b"extra-field", b"data")], c._extra) def test_encoding(self) -> None: c = Commit.from_string(self.make_commit_text(encoding=b"UTF-8")) self.assertEqual(b"UTF-8", c.encoding) def test_check(self) -> None: self.assertCheckSucceeds(Commit, self.make_commit_text()) self.assertCheckSucceeds(Commit, self.make_commit_text(parents=None)) self.assertCheckSucceeds(Commit, self.make_commit_text(encoding=b"UTF-8")) self.assertCheckFails(Commit, self.make_commit_text(tree=b"xxx")) self.assertCheckFails(Commit, self.make_commit_text(parents=[a_sha, b"xxx"])) bad_committer = b"some guy without an email address 1174773719 +0000" self.assertCheckFails(Commit, self.make_commit_text(committer=bad_committer)) self.assertCheckFails(Commit, self.make_commit_text(author=bad_committer)) self.assertCheckFails(Commit, self.make_commit_text(author=None)) self.assertCheckFails(Commit, self.make_commit_text(committer=None)) self.assertCheckFails( Commit, self.make_commit_text(author=None, committer=None) ) def test_check_duplicates(self) -> None: # duplicate each of the header fields for i in range(5): lines = self.make_commit_lines(parents=[a_sha], encoding=b"UTF-8") lines.insert(i, lines[i]) text = b"\n".join(lines) if lines[i].startswith(b"parent"): # duplicate parents are ok for now self.assertCheckSucceeds(Commit, text) else: self.assertCheckFails(Commit, text) def test_check_order(self) -> None: lines = self.make_commit_lines(parents=[a_sha], encoding=b"UTF-8") headers = lines[:5] rest = lines[5:] # of all possible permutations, ensure only the original succeeds for perm in permutations(headers): perm = list(perm) text = b"\n".join(perm + rest) if perm == headers: self.assertCheckSucceeds(Commit, text) else: self.assertCheckFails(Commit, text) def test_check_commit_with_unparseable_time(self) -> None: identity_with_wrong_time = ( b"Igor Sysoev 18446743887488505614+42707004" ) # Those fail at reading time self.assertCheckFails( Commit, self.make_commit_text( author=default_committer, committer=identity_with_wrong_time ), ) self.assertCheckFails( Commit, self.make_commit_text( author=identity_with_wrong_time, committer=default_committer ), ) def test_check_commit_with_overflow_date(self) -> None: """Date with overflow should raise an ObjectFormatException when checked.""" identity_with_wrong_time = ( b"Igor Sysoev 18446743887488505614 +42707004" ) commit0 = Commit.from_string( self.make_commit_text( author=identity_with_wrong_time, committer=default_committer ) ) commit1 = Commit.from_string( self.make_commit_text( author=default_committer, committer=identity_with_wrong_time ) ) # Those fails when triggering the check() method for commit in [commit0, commit1]: with self.assertRaises(ObjectFormatException): commit.check() def test_mangled_author_line(self) -> None: """Mangled author line should successfully parse.""" author_line = ( b'Karl MacMillan <"Karl MacMillan ' b'"> 1197475547 -0500' ) expected_identity = ( b'Karl MacMillan <"Karl MacMillan ' b'">' ) commit = Commit.from_string(self.make_commit_text(author=author_line)) # The commit parses properly self.assertEqual(commit.author, expected_identity) # But the check fails because the author identity is bogus with self.assertRaises(ObjectFormatException): commit.check() def test_parse_gpgsig(self) -> None: pre_sig = b"""tree aaff74984cccd156a469afa7d9ab10e4777beb24 author Jelmer Vernooij 1412179807 +0200 committer Jelmer Vernooij 1412179807 +0200 """ git_sig = b"""\ gpgsig -----BEGIN PGP SIGNATURE----- Version: GnuPG v1 iQIcBAABCgAGBQJULCdfAAoJEACAbyvXKaRXuKwP/RyP9PA49uAvu8tQVCC/uBa8 vi975+xvO14R8Pp8k2nps7lSxCdtCd+xVT1VRHs0wNhOZo2YCVoU1HATkPejqSeV NScTHcxnk4/+bxyfk14xvJkNp7FlQ3npmBkA+lbV0Ubr33rvtIE5jiJPyz+SgWAg xdBG2TojV0squj00GoH/euK6aX7GgZtwdtpTv44haCQdSuPGDcI4TORqR6YSqvy3 GPE+3ZqXPFFb+KILtimkxitdwB7CpwmNse2vE3rONSwTvi8nq3ZoQYNY73CQGkUy qoFU0pDtw87U3niFin1ZccDgH0bB6624sLViqrjcbYJeg815Htsu4rmzVaZADEVC XhIO4MThebusdk0AcNGjgpf3HRHk0DPMDDlIjm+Oao0cqovvF6VyYmcb0C+RmhJj dodLXMNmbqErwTk3zEkW0yZvNIYXH7m9SokPCZa4eeIM7be62X6h1mbt0/IU6Th+ v18fS0iTMP/Viug5und+05C/v04kgDo0CPphAbXwWMnkE4B6Tl9sdyUYXtvQsL7x 0+WP1gL27ANqNZiI07Kz/BhbBAQI/+2TFT7oGr0AnFPQ5jHp+3GpUf6OKuT1wT3H ND189UFuRuubxb42vZhpcXRbqJVWnbECTKVUPsGZqat3enQUB63uM4i6/RdONDZA fDeF1m4qYs+cUXKNUZ03 =X6RT -----END PGP SIGNATURE----- """ post_sig = b"""\ foo """ c = Commit.from_string(pre_sig + git_sig + post_sig) self.assertEqual(pre_sig + post_sig, c.raw_without_sig()) self.assertEqual(pre_sig + git_sig + post_sig, bytes(c)) self.assertEqual(b"foo\n", c.message) self.assertEqual([], c._extra) self.assertEqual( b"""-----BEGIN PGP SIGNATURE----- Version: GnuPG v1 iQIcBAABCgAGBQJULCdfAAoJEACAbyvXKaRXuKwP/RyP9PA49uAvu8tQVCC/uBa8 vi975+xvO14R8Pp8k2nps7lSxCdtCd+xVT1VRHs0wNhOZo2YCVoU1HATkPejqSeV NScTHcxnk4/+bxyfk14xvJkNp7FlQ3npmBkA+lbV0Ubr33rvtIE5jiJPyz+SgWAg xdBG2TojV0squj00GoH/euK6aX7GgZtwdtpTv44haCQdSuPGDcI4TORqR6YSqvy3 GPE+3ZqXPFFb+KILtimkxitdwB7CpwmNse2vE3rONSwTvi8nq3ZoQYNY73CQGkUy qoFU0pDtw87U3niFin1ZccDgH0bB6624sLViqrjcbYJeg815Htsu4rmzVaZADEVC XhIO4MThebusdk0AcNGjgpf3HRHk0DPMDDlIjm+Oao0cqovvF6VyYmcb0C+RmhJj dodLXMNmbqErwTk3zEkW0yZvNIYXH7m9SokPCZa4eeIM7be62X6h1mbt0/IU6Th+ v18fS0iTMP/Viug5und+05C/v04kgDo0CPphAbXwWMnkE4B6Tl9sdyUYXtvQsL7x 0+WP1gL27ANqNZiI07Kz/BhbBAQI/+2TFT7oGr0AnFPQ5jHp+3GpUf6OKuT1wT3H ND189UFuRuubxb42vZhpcXRbqJVWnbECTKVUPsGZqat3enQUB63uM4i6/RdONDZA fDeF1m4qYs+cUXKNUZ03 =X6RT -----END PGP SIGNATURE-----""", c.gpgsig, ) def test_parse_header_trailing_newline(self) -> None: pre_sig = b"""\ tree a7d6277f78d3ecd0230a1a5df6db00b1d9c521ac parent c09b6dec7a73760fbdb478383a3c926b18db8bbe author Neil Matatall 1461964057 -1000 committer Neil Matatall 1461964057 -1000 """ git_sig = b"""\ gpgsig -----BEGIN PGP SIGNATURE----- wsBcBAABCAAQBQJXI80ZCRA6pcNDcVZ70gAAarcIABs72xRX3FWeox349nh6ucJK CtwmBTusez2Zwmq895fQEbZK7jpaGO5TRO4OvjFxlRo0E08UFx3pxZHSpj6bsFeL hHsDXnCaotphLkbgKKRdGZo7tDqM84wuEDlh4MwNe7qlFC7bYLDyysc81ZX5lpMm 2MFF1TvjLAzSvkT7H1LPkuR3hSvfCYhikbPOUNnKOo0sYjeJeAJ/JdAVQ4mdJIM0 gl3REp9+A+qBEpNQI7z94Pg5Bc5xenwuDh3SJgHvJV6zBWupWcdB3fAkVd4TPnEZ nHxksHfeNln9RKseIDcy4b2ATjhDNIJZARHNfr6oy4u3XPW4svRqtBsLoMiIeuI= =ms6q -----END PGP SIGNATURE----- """ post_sig = b"""\ 3.3.0 version bump and docs """ gpgsig = b"""\ -----BEGIN PGP SIGNATURE----- wsBcBAABCAAQBQJXI80ZCRA6pcNDcVZ70gAAarcIABs72xRX3FWeox349nh6ucJK CtwmBTusez2Zwmq895fQEbZK7jpaGO5TRO4OvjFxlRo0E08UFx3pxZHSpj6bsFeL hHsDXnCaotphLkbgKKRdGZo7tDqM84wuEDlh4MwNe7qlFC7bYLDyysc81ZX5lpMm 2MFF1TvjLAzSvkT7H1LPkuR3hSvfCYhikbPOUNnKOo0sYjeJeAJ/JdAVQ4mdJIM0 gl3REp9+A+qBEpNQI7z94Pg5Bc5xenwuDh3SJgHvJV6zBWupWcdB3fAkVd4TPnEZ nHxksHfeNln9RKseIDcy4b2ATjhDNIJZARHNfr6oy4u3XPW4svRqtBsLoMiIeuI= =ms6q -----END PGP SIGNATURE-----\n""" c = Commit.from_string(pre_sig + git_sig + post_sig) self.assertEqual([], c._extra) self.assertEqual(pre_sig + git_sig + post_sig, c.as_raw_string()) self.assertEqual(pre_sig + post_sig, c.raw_without_sig()) self.assertEqual(gpgsig, c.gpgsig) self.assertEqual(b"3.3.0 version bump and docs\n", c.message) _TREE_ITEMS = { b"a-c": (0o100755, b"d80c186a03f423a81b39df39dc87fd269736ca86"), b"a.c": (0o100755, b"d80c186a03f423a81b39df39dc87fd269736ca86"), b"aoc": (0o100755, b"d80c186a03f423a81b39df39dc87fd269736ca86"), b"a": (stat.S_IFDIR, b"d80c186a03f423a81b39df39dc87fd269736ca86"), b"a/c": (stat.S_IFDIR, b"d80c186a03f423a81b39df39dc87fd269736ca86"), } _SORTED_TREE_ITEMS = [ TreeEntry(b"a-c", 0o100755, b"d80c186a03f423a81b39df39dc87fd269736ca86"), TreeEntry(b"a.c", 0o100755, b"d80c186a03f423a81b39df39dc87fd269736ca86"), TreeEntry(b"a", stat.S_IFDIR, b"d80c186a03f423a81b39df39dc87fd269736ca86"), TreeEntry(b"a/c", stat.S_IFDIR, b"d80c186a03f423a81b39df39dc87fd269736ca86"), TreeEntry(b"aoc", 0o100755, b"d80c186a03f423a81b39df39dc87fd269736ca86"), ] _TREE_ITEMS_BUG_1325 = { b"dir": (stat.S_IFDIR | 0o644, b"5944b31ff85b415573d1a43eb942e2dea30ab8be"), b"dira": (0o100644, b"cf7a729ca69bfabd0995fc9b083e86a18215bd91"), } _SORTED_TREE_ITEMS_BUG_1325 = [ TreeEntry( path=b"dir", mode=stat.S_IFDIR | 0o644, sha=b"5944b31ff85b415573d1a43eb942e2dea30ab8be", ), TreeEntry( path=b"dira", mode=0o100644, sha=b"cf7a729ca69bfabd0995fc9b083e86a18215bd91" ), ] class TreeTests(ShaFileCheckTests): def test_add(self) -> None: myhexsha = b"d80c186a03f423a81b39df39dc87fd269736ca86" x = Tree() x.add(b"myname", 0o100755, myhexsha) self.assertEqual(x[b"myname"], (0o100755, myhexsha)) self.assertEqual(b"100755 myname\0" + hex_to_sha(myhexsha), x.as_raw_string()) def test_simple(self) -> None: myhexsha = b"d80c186a03f423a81b39df39dc87fd269736ca86" x = Tree() x[b"myname"] = (0o100755, myhexsha) self.assertEqual(b"100755 myname\0" + hex_to_sha(myhexsha), x.as_raw_string()) self.assertEqual(b"100755 myname\0" + hex_to_sha(myhexsha), bytes(x)) def test_tree_update_id(self) -> None: x = Tree() x[b"a.c"] = (0o100755, b"d80c186a03f423a81b39df39dc87fd269736ca86") self.assertEqual(b"0c5c6bc2c081accfbc250331b19e43b904ab9cdd", x.id) x[b"a.b"] = (stat.S_IFDIR, b"d80c186a03f423a81b39df39dc87fd269736ca86") self.assertEqual(b"07bfcb5f3ada15bbebdfa3bbb8fd858a363925c8", x.id) def test_tree_iteritems_dir_sort(self) -> None: x = Tree() for name, item in _TREE_ITEMS.items(): x[name] = item self.assertEqual(_SORTED_TREE_ITEMS, x.items()) def test_tree_items_dir_sort(self) -> None: x = Tree() for name, item in _TREE_ITEMS.items(): x[name] = item self.assertEqual(_SORTED_TREE_ITEMS, x.items()) def _do_test_parse_tree(self, parse_tree) -> None: dir = os.path.join(os.path.dirname(__file__), "..", "testdata", "trees") o = Tree.from_path(hex_to_filename(dir, tree_sha)) self.assertEqual( [(b"a", 0o100644, a_sha), (b"b", 0o100644, b_sha)], list(parse_tree(o.as_raw_string())), ) # test a broken tree that has a leading 0 on the file mode broken_tree = b"0100644 foo\0" + hex_to_sha(a_sha) def eval_parse_tree(*args, **kwargs): return list(parse_tree(*args, **kwargs)) self.assertEqual([(b"foo", 0o100644, a_sha)], eval_parse_tree(broken_tree)) self.assertRaises( ObjectFormatException, eval_parse_tree, broken_tree, strict=True ) test_parse_tree = functest_builder(_do_test_parse_tree, _parse_tree_py) test_parse_tree_extension = ext_functest_builder( _do_test_parse_tree, _parse_tree_rs ) def _do_test_sorted_tree_items(self, sorted_tree_items) -> None: def do_sort(entries, name_order): return list(sorted_tree_items(entries, name_order)) actual = do_sort(_TREE_ITEMS, False) self.assertEqual(_SORTED_TREE_ITEMS, actual) self.assertIsInstance(actual[0], TreeEntry) actual = do_sort(_TREE_ITEMS_BUG_1325, False) self.assertEqual( key_entry((b"a", (0o40644, b"cf7a729ca69bfabd0995fc9b083e86a18215bd91"))), b"a/", ) self.assertEqual(_SORTED_TREE_ITEMS_BUG_1325, actual) self.assertIsInstance(actual[0], TreeEntry) # C/Python implementations may differ in specific error types, but # should all error on invalid inputs. # For example, the Rust implementation has stricter type checks, so may # raise TypeError where the Python implementation raises # AttributeError. errors = (TypeError, ValueError, AttributeError) self.assertRaises(errors, do_sort, b"foo", False) self.assertRaises(errors, do_sort, {b"foo": (1, 2, 3)}, False) myhexsha = b"d80c186a03f423a81b39df39dc87fd269736ca86" self.assertRaises(errors, do_sort, {b"foo": (b"xxx", myhexsha)}, False) self.assertRaises(errors, do_sort, {b"foo": (0o100755, 12345)}, False) test_sorted_tree_items = functest_builder( _do_test_sorted_tree_items, _sorted_tree_items_py ) if _sorted_tree_items_rs is not None: assert _sorted_tree_items_rs != _sorted_tree_items_py test_sorted_tree_items_extension = ext_functest_builder( _do_test_sorted_tree_items, _sorted_tree_items_rs ) def _do_test_sorted_tree_items_name_order(self, sorted_tree_items) -> None: self.assertEqual( [ TreeEntry( b"a", stat.S_IFDIR, b"d80c186a03f423a81b39df39dc87fd269736ca86", ), TreeEntry( b"a-c", 0o100755, b"d80c186a03f423a81b39df39dc87fd269736ca86", ), TreeEntry( b"a.c", 0o100755, b"d80c186a03f423a81b39df39dc87fd269736ca86", ), TreeEntry( b"a/c", stat.S_IFDIR, b"d80c186a03f423a81b39df39dc87fd269736ca86", ), TreeEntry( b"aoc", 0o100755, b"d80c186a03f423a81b39df39dc87fd269736ca86", ), ], list(sorted_tree_items(_TREE_ITEMS, True)), ) test_sorted_tree_items_name_order = functest_builder( _do_test_sorted_tree_items_name_order, _sorted_tree_items_py ) if _sorted_tree_items_rs is not None: test_sorted_tree_items_name_order_extension = ext_functest_builder( _do_test_sorted_tree_items_name_order, _sorted_tree_items_rs ) def test_check(self) -> None: t = Tree sha = hex_to_sha(a_sha) # filenames self.assertCheckSucceeds(t, b"100644 .a\0" + sha) self.assertCheckFails(t, b"100644 \0" + sha) self.assertCheckFails(t, b"100644 .\0" + sha) self.assertCheckFails(t, b"100644 a/a\0" + sha) self.assertCheckFails(t, b"100644 ..\0" + sha) self.assertCheckFails(t, b"100644 .git\0" + sha) # modes self.assertCheckSucceeds(t, b"100644 a\0" + sha) self.assertCheckSucceeds(t, b"100755 a\0" + sha) self.assertCheckSucceeds(t, b"160000 a\0" + sha) # TODO more whitelisted modes self.assertCheckFails(t, b"123456 a\0" + sha) self.assertCheckFails(t, b"123abc a\0" + sha) # should fail check, but parses ok self.assertCheckFails(t, b"0100644 foo\0" + sha) # shas self.assertCheckFails(t, b"100644 a\0" + (b"x" * 5)) self.assertCheckFails(t, b"100644 a\0" + (b"x" * 18) + b"\0") self.assertCheckFails(t, b"100644 a\0" + (b"x" * 21) + b"\n100644 b\0" + sha) # ordering sha2 = hex_to_sha(b_sha) self.assertCheckSucceeds(t, b"100644 a\0" + sha + b"100644 b\0" + sha) self.assertCheckSucceeds(t, b"100644 a\0" + sha + b"100644 b\0" + sha2) self.assertCheckFails(t, b"100644 a\0" + sha + b"100755 a\0" + sha2) self.assertCheckFails(t, b"100644 b\0" + sha2 + b"100644 a\0" + sha) def test_iter(self) -> None: t = Tree() t[b"foo"] = (0o100644, a_sha) self.assertEqual({b"foo"}, set(t)) class TagSerializeTests(TestCase): def test_serialize_simple(self) -> None: x = make_object( Tag, tagger=b"Jelmer Vernooij ", name=b"0.1", message=b"Tag 0.1", object=(Blob, b"d80c186a03f423a81b39df39dc87fd269736ca86"), tag_time=423423423, tag_timezone=0, ) self.assertEqual( ( b"object d80c186a03f423a81b39df39dc87fd269736ca86\n" b"type blob\n" b"tag 0.1\n" b"tagger Jelmer Vernooij " b"423423423 +0000\n" b"\n" b"Tag 0.1" ), x.as_raw_string(), ) def test_serialize_none_message(self) -> None: x = make_object( Tag, tagger=b"Jelmer Vernooij ", name=b"0.1", message=None, object=(Blob, b"d80c186a03f423a81b39df39dc87fd269736ca86"), tag_time=423423423, tag_timezone=0, ) self.assertEqual( ( b"object d80c186a03f423a81b39df39dc87fd269736ca86\n" b"type blob\n" b"tag 0.1\n" b"tagger Jelmer Vernooij " b"423423423 +0000\n\n" ), x.as_raw_string(), ) default_tagger = ( b"Linus Torvalds " b"1183319674 -0700" ) default_message = b"""Linux 2.6.22-rc7 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql OK2XeQOiEeXtT76rV4t2WR4= =ivrA -----END PGP SIGNATURE----- """ class TagParseTests(ShaFileCheckTests): def make_tag_lines( self, object_sha=b"a38d6181ff27824c79fc7df825164a212eff6a3f", object_type_name=b"commit", name=b"v2.6.22-rc7", tagger=default_tagger, message=default_message, ): lines = [] if object_sha is not None: lines.append(b"object " + object_sha) if object_type_name is not None: lines.append(b"type " + object_type_name) if name is not None: lines.append(b"tag " + name) if tagger is not None: lines.append(b"tagger " + tagger) if message is not None: lines.append(b"") lines.append(message) return lines def make_tag_text(self, **kwargs): return b"\n".join(self.make_tag_lines(**kwargs)) def test_parse(self) -> None: x = Tag() x.set_raw_string(self.make_tag_text()) self.assertEqual( b"Linus Torvalds ", x.tagger ) self.assertEqual(b"v2.6.22-rc7", x.name) object_type, object_sha = x.object self.assertEqual(b"a38d6181ff27824c79fc7df825164a212eff6a3f", object_sha) self.assertEqual(Commit, object_type) self.assertEqual( datetime.datetime.utcfromtimestamp(x.tag_time), datetime.datetime(2007, 7, 1, 19, 54, 34), ) self.assertEqual(-25200, x.tag_timezone) def test_parse_no_tagger(self) -> None: x = Tag() x.set_raw_string(self.make_tag_text(tagger=None)) self.assertEqual(None, x.tagger) self.assertEqual(b"v2.6.22-rc7", x.name) self.assertEqual(None, x.tag_time) def test_parse_no_message(self) -> None: x = Tag() x.set_raw_string(self.make_tag_text(message=None)) self.assertEqual(None, x.message) self.assertEqual( b"Linus Torvalds ", x.tagger ) self.assertEqual( datetime.datetime.utcfromtimestamp(x.tag_time), datetime.datetime(2007, 7, 1, 19, 54, 34), ) self.assertEqual(-25200, x.tag_timezone) self.assertEqual(b"v2.6.22-rc7", x.name) def test_check(self) -> None: self.assertCheckSucceeds(Tag, self.make_tag_text()) self.assertCheckFails(Tag, self.make_tag_text(object_sha=None)) self.assertCheckFails(Tag, self.make_tag_text(object_type_name=None)) self.assertCheckFails(Tag, self.make_tag_text(name=None)) self.assertCheckFails(Tag, self.make_tag_text(name=b"")) self.assertCheckFails(Tag, self.make_tag_text(object_type_name=b"foobar")) self.assertCheckFails( Tag, self.make_tag_text( tagger=b"some guy without an email address 1183319674 -0700" ), ) self.assertCheckFails( Tag, self.make_tag_text( tagger=( b"Linus Torvalds " b"Sun 7 Jul 2007 12:54:34 +0700" ) ), ) self.assertCheckFails(Tag, self.make_tag_text(object_sha=b"xxx")) def test_check_tag_with_unparseable_field(self) -> None: self.assertCheckFails( Tag, self.make_tag_text( tagger=( b"Linus Torvalds " b"423423+0000" ) ), ) def test_check_tag_with_overflow_time(self) -> None: """Date with overflow should raise an ObjectFormatException when checked.""" author = f"Some Dude {MAX_TIME + 1} +0000" tag = Tag.from_string(self.make_tag_text(tagger=(author.encode()))) with self.assertRaises(ObjectFormatException): tag.check() def test_check_duplicates(self) -> None: # duplicate each of the header fields for i in range(4): lines = self.make_tag_lines() lines.insert(i, lines[i]) self.assertCheckFails(Tag, b"\n".join(lines)) def test_check_order(self) -> None: lines = self.make_tag_lines() headers = lines[:4] rest = lines[4:] # of all possible permutations, ensure only the original succeeds for perm in permutations(headers): perm = list(perm) text = b"\n".join(perm + rest) if perm == headers: self.assertCheckSucceeds(Tag, text) else: self.assertCheckFails(Tag, text) def test_tree_copy_after_update(self) -> None: """Check Tree.id is correctly updated when the tree is copied after updated.""" shas = [] tree = Tree() shas.append(tree.id) tree.add(b"data", 0o644, Blob().id) copied = tree.copy() shas.append(tree.id) shas.append(copied.id) self.assertNotIn(shas[0], shas[1:]) self.assertEqual(shas[1], shas[2]) def test_tag_withough_sig(self) -> None: x = Tag() x.set_raw_string(self.make_tag_text()) self.assertEqual(bytes(x), x.raw_without_sig() + x.signature) self.assertEqual( b"""\ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQBGiAaAF3YsRnbiHLsRAitMAKCiLboJkQECM/jpYsY3WPfvUgLXkACgg3ql OK2XeQOiEeXtT76rV4t2WR4= =ivrA -----END PGP SIGNATURE----- """, x.signature, ) class CheckTests(TestCase): def test_check_hexsha(self) -> None: check_hexsha(a_sha, "failed to check good sha") self.assertRaises( ObjectFormatException, check_hexsha, b"1" * 39, "sha too short" ) self.assertRaises( ObjectFormatException, check_hexsha, b"1" * 41, "sha too long" ) self.assertRaises( ObjectFormatException, check_hexsha, b"x" * 40, "invalid characters", ) def test_check_identity(self) -> None: check_identity( b"Dave Borowitz ", "failed to check good identity", ) check_identity(b" ", "failed to check good identity") self.assertRaises( ObjectFormatException, check_identity, b"", "no space before email", ) self.assertRaises( ObjectFormatException, check_identity, b"Dave Borowitz", "no email" ) self.assertRaises( ObjectFormatException, check_identity, b"Dave Borowitz ", "incomplete email", ) self.assertRaises( ObjectFormatException, check_identity, b"Dave Borowitz <", "typo", ) self.assertRaises( ObjectFormatException, check_identity, b"Dave Borowitz >", "typo", ) self.assertRaises( ObjectFormatException, check_identity, b"Dave Borowitz xxx", "trailing characters", ) self.assertRaises( ObjectFormatException, check_identity, b"Dave Borowitz xxx", "trailing characters", ) self.assertRaises( ObjectFormatException, check_identity, b"Dave", "reserved byte in name", ) self.assertRaises( ObjectFormatException, check_identity, b"Dave>Borowitz ", "reserved byte in name", ) self.assertRaises( ObjectFormatException, check_identity, b"Dave\0Borowitz ", "null byte", ) self.assertRaises( ObjectFormatException, check_identity, b"Dave\nBorowitz ", "newline byte", ) class TimezoneTests(TestCase): def test_parse_timezone_utc(self) -> None: self.assertEqual((0, False), parse_timezone(b"+0000")) def test_parse_timezone_utc_negative(self) -> None: self.assertEqual((0, True), parse_timezone(b"-0000")) def test_generate_timezone_utc(self) -> None: self.assertEqual(b"+0000", format_timezone(0)) def test_generate_timezone_utc_negative(self) -> None: self.assertEqual(b"-0000", format_timezone(0, True)) def test_parse_timezone_cet(self) -> None: self.assertEqual((60 * 60, False), parse_timezone(b"+0100")) def test_format_timezone_cet(self) -> None: self.assertEqual(b"+0100", format_timezone(60 * 60)) def test_format_timezone_pdt(self) -> None: self.assertEqual(b"-0400", format_timezone(-4 * 60 * 60)) def test_parse_timezone_pdt(self) -> None: self.assertEqual((-4 * 60 * 60, False), parse_timezone(b"-0400")) def test_format_timezone_pdt_half(self) -> None: self.assertEqual(b"-0440", format_timezone(int(((-4 * 60) - 40) * 60))) def test_format_timezone_double_negative(self) -> None: self.assertEqual(b"--700", format_timezone(int((7 * 60) * 60), True)) def test_parse_timezone_pdt_half(self) -> None: self.assertEqual((((-4 * 60) - 40) * 60, False), parse_timezone(b"-0440")) def test_parse_timezone_double_negative(self) -> None: self.assertEqual((int((7 * 60) * 60), False), parse_timezone(b"+700")) self.assertEqual((int((7 * 60) * 60), True), parse_timezone(b"--700")) class ShaFileCopyTests(TestCase): def assert_copy(self, orig) -> None: oclass = object_class(orig.type_num) copy = orig.copy() self.assertIsInstance(copy, oclass) self.assertEqual(copy, orig) self.assertIsNot(copy, orig) def test_commit_copy(self) -> None: attrs = { "tree": b"d80c186a03f423a81b39df39dc87fd269736ca86", "parents": [ b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd", b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6", ], "author": b"James Westby ", "committer": b"James Westby ", "commit_time": 1174773719, "author_time": 1174773719, "commit_timezone": 0, "author_timezone": 0, "message": b"Merge ../b\n", } commit = make_commit(**attrs) self.assert_copy(commit) def test_blob_copy(self) -> None: blob = make_object(Blob, data=b"i am a blob") self.assert_copy(blob) def test_tree_copy(self) -> None: blob = make_object(Blob, data=b"i am a blob") tree = Tree() tree[b"blob"] = (stat.S_IFREG, blob.id) self.assert_copy(tree) def test_tag_copy(self) -> None: tag = make_object( Tag, name=b"tag", message=b"", tagger=b"Tagger ", tag_time=12345, tag_timezone=0, object=(Commit, b"0" * 40), ) self.assert_copy(tag) class ShaFileSerializeTests(TestCase): """`ShaFile` objects only gets serialized once if they haven't changed.""" @contextmanager def assert_serialization_on_change( self, obj, needs_serialization_after_change=True ): old_id = obj.id self.assertFalse(obj._needs_serialization) yield obj if needs_serialization_after_change: self.assertTrue(obj._needs_serialization) else: self.assertFalse(obj._needs_serialization) new_id = obj.id self.assertFalse(obj._needs_serialization) self.assertNotEqual(old_id, new_id) def test_commit_serialize(self) -> None: attrs = { "tree": b"d80c186a03f423a81b39df39dc87fd269736ca86", "parents": [ b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd", b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6", ], "author": b"James Westby ", "committer": b"James Westby ", "commit_time": 1174773719, "author_time": 1174773719, "commit_timezone": 0, "author_timezone": 0, "message": b"Merge ../b\n", } commit = make_commit(**attrs) with self.assert_serialization_on_change(commit): commit.parents = [b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd"] def test_blob_serialize(self) -> None: blob = make_object(Blob, data=b"i am a blob") with self.assert_serialization_on_change( blob, needs_serialization_after_change=False ): blob.data = b"i am another blob" def test_tree_serialize(self) -> None: blob = make_object(Blob, data=b"i am a blob") tree = Tree() tree[b"blob"] = (stat.S_IFREG, blob.id) with self.assert_serialization_on_change(tree): tree[b"blob2"] = (stat.S_IFREG, blob.id) def test_tag_serialize(self) -> None: tag = make_object( Tag, name=b"tag", message=b"", tagger=b"Tagger ", tag_time=12345, tag_timezone=0, object=(Commit, b"0" * 40), ) with self.assert_serialization_on_change(tag): tag.message = b"new message" def test_tag_serialize_time_error(self) -> None: with self.assertRaises(ObjectFormatException): tag = make_object( Tag, name=b"tag", message=b"some message", tagger=b"Tagger 1174773719+0000", object=(Commit, b"0" * 40), ) tag._deserialize(tag._serialize()) class PrettyFormatTreeEntryTests(TestCase): def test_format(self) -> None: self.assertEqual( "40000 tree 40820c38cfb182ce6c8b261555410d8382a5918b\tfoo\n", pretty_format_tree_entry( b"foo", 0o40000, b"40820c38cfb182ce6c8b261555410d8382a5918b" ), ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_objectspec.py0000644000175100002000000002116014731042555017533 0ustar00runnerdocker# test_objectspec.py -- tests for objectspec.py # Copyright (C) 2014 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for revision spec parsing.""" # TODO: Round-trip parse-serialize-parse and serialize-parse-serialize tests. from dulwich.objects import Blob from dulwich.objectspec import ( parse_commit, parse_commit_range, parse_object, parse_ref, parse_refs, parse_reftuple, parse_reftuples, parse_tree, ) from dulwich.repo import MemoryRepo from dulwich.tests.utils import build_commit_graph from . import TestCase class ParseObjectTests(TestCase): """Test parse_object.""" def test_nonexistent(self) -> None: r = MemoryRepo() self.assertRaises(KeyError, parse_object, r, "thisdoesnotexist") def test_blob_by_sha(self) -> None: r = MemoryRepo() b = Blob.from_string(b"Blah") r.object_store.add_object(b) self.assertEqual(b, parse_object(r, b.id)) class ParseCommitRangeTests(TestCase): """Test parse_commit_range.""" def test_nonexistent(self) -> None: r = MemoryRepo() self.assertRaises(KeyError, parse_commit_range, r, "thisdoesnotexist") def test_commit_by_sha(self) -> None: r = MemoryRepo() c1, c2, c3 = build_commit_graph(r.object_store, [[1], [2, 1], [3, 1, 2]]) self.assertEqual([c1], list(parse_commit_range(r, c1.id))) class ParseCommitTests(TestCase): """Test parse_commit.""" def test_nonexistent(self) -> None: r = MemoryRepo() self.assertRaises(KeyError, parse_commit, r, "thisdoesnotexist") def test_commit_by_sha(self) -> None: r = MemoryRepo() [c1] = build_commit_graph(r.object_store, [[1]]) self.assertEqual(c1, parse_commit(r, c1.id)) def test_commit_by_short_sha(self) -> None: r = MemoryRepo() [c1] = build_commit_graph(r.object_store, [[1]]) self.assertEqual(c1, parse_commit(r, c1.id[:10])) class ParseRefTests(TestCase): def test_nonexistent(self) -> None: r = {} self.assertRaises(KeyError, parse_ref, r, b"thisdoesnotexist") def test_ambiguous_ref(self) -> None: r = { b"ambig1": "bla", b"refs/ambig1": "bla", b"refs/tags/ambig1": "bla", b"refs/heads/ambig1": "bla", b"refs/remotes/ambig1": "bla", b"refs/remotes/ambig1/HEAD": "bla", } self.assertEqual(b"ambig1", parse_ref(r, b"ambig1")) def test_ambiguous_ref2(self) -> None: r = { b"refs/ambig2": "bla", b"refs/tags/ambig2": "bla", b"refs/heads/ambig2": "bla", b"refs/remotes/ambig2": "bla", b"refs/remotes/ambig2/HEAD": "bla", } self.assertEqual(b"refs/ambig2", parse_ref(r, b"ambig2")) def test_ambiguous_tag(self) -> None: r = { b"refs/tags/ambig3": "bla", b"refs/heads/ambig3": "bla", b"refs/remotes/ambig3": "bla", b"refs/remotes/ambig3/HEAD": "bla", } self.assertEqual(b"refs/tags/ambig3", parse_ref(r, b"ambig3")) def test_ambiguous_head(self) -> None: r = { b"refs/heads/ambig4": "bla", b"refs/remotes/ambig4": "bla", b"refs/remotes/ambig4/HEAD": "bla", } self.assertEqual(b"refs/heads/ambig4", parse_ref(r, b"ambig4")) def test_ambiguous_remote(self) -> None: r = {b"refs/remotes/ambig5": "bla", b"refs/remotes/ambig5/HEAD": "bla"} self.assertEqual(b"refs/remotes/ambig5", parse_ref(r, b"ambig5")) def test_ambiguous_remote_head(self) -> None: r = {b"refs/remotes/ambig6/HEAD": "bla"} self.assertEqual(b"refs/remotes/ambig6/HEAD", parse_ref(r, b"ambig6")) def test_heads_full(self) -> None: r = {b"refs/heads/foo": "bla"} self.assertEqual(b"refs/heads/foo", parse_ref(r, b"refs/heads/foo")) def test_heads_partial(self) -> None: r = {b"refs/heads/foo": "bla"} self.assertEqual(b"refs/heads/foo", parse_ref(r, b"heads/foo")) def test_tags_partial(self) -> None: r = {b"refs/tags/foo": "bla"} self.assertEqual(b"refs/tags/foo", parse_ref(r, b"tags/foo")) class ParseRefsTests(TestCase): def test_nonexistent(self) -> None: r = {} self.assertRaises(KeyError, parse_refs, r, [b"thisdoesnotexist"]) def test_head(self) -> None: r = {b"refs/heads/foo": "bla"} self.assertEqual([b"refs/heads/foo"], parse_refs(r, [b"foo"])) def test_full(self) -> None: r = {b"refs/heads/foo": "bla"} self.assertEqual([b"refs/heads/foo"], parse_refs(r, b"refs/heads/foo")) class ParseReftupleTests(TestCase): def test_nonexistent(self) -> None: r = {} self.assertRaises(KeyError, parse_reftuple, r, r, b"thisdoesnotexist") def test_head(self) -> None: r = {b"refs/heads/foo": "bla"} self.assertEqual( (b"refs/heads/foo", b"refs/heads/foo", False), parse_reftuple(r, r, b"foo"), ) self.assertEqual( (b"refs/heads/foo", b"refs/heads/foo", True), parse_reftuple(r, r, b"+foo"), ) self.assertEqual( (b"refs/heads/foo", b"refs/heads/foo", True), parse_reftuple(r, {}, b"+foo"), ) self.assertEqual( (b"refs/heads/foo", b"refs/heads/foo", True), parse_reftuple(r, {}, b"foo", True), ) def test_full(self) -> None: r = {b"refs/heads/foo": "bla"} self.assertEqual( (b"refs/heads/foo", b"refs/heads/foo", False), parse_reftuple(r, r, b"refs/heads/foo"), ) def test_no_left_ref(self) -> None: r = {b"refs/heads/foo": "bla"} self.assertEqual( (None, b"refs/heads/foo", False), parse_reftuple(r, r, b":refs/heads/foo"), ) def test_no_right_ref(self) -> None: r = {b"refs/heads/foo": "bla"} self.assertEqual( (b"refs/heads/foo", None, False), parse_reftuple(r, r, b"refs/heads/foo:"), ) def test_default_with_string(self) -> None: r = {b"refs/heads/foo": "bla"} self.assertEqual( (b"refs/heads/foo", b"refs/heads/foo", False), parse_reftuple(r, r, "foo"), ) class ParseReftuplesTests(TestCase): def test_nonexistent(self) -> None: r = {} self.assertRaises(KeyError, parse_reftuples, r, r, [b"thisdoesnotexist"]) def test_head(self) -> None: r = {b"refs/heads/foo": "bla"} self.assertEqual( [(b"refs/heads/foo", b"refs/heads/foo", False)], parse_reftuples(r, r, [b"foo"]), ) def test_full(self) -> None: r = {b"refs/heads/foo": "bla"} self.assertEqual( [(b"refs/heads/foo", b"refs/heads/foo", False)], parse_reftuples(r, r, b"refs/heads/foo"), ) r = {b"refs/heads/foo": "bla"} self.assertEqual( [(b"refs/heads/foo", b"refs/heads/foo", True)], parse_reftuples(r, r, b"refs/heads/foo", True), ) class ParseTreeTests(TestCase): """Test parse_tree.""" def test_nonexistent(self) -> None: r = MemoryRepo() self.assertRaises(KeyError, parse_tree, r, "thisdoesnotexist") def test_from_commit(self) -> None: r = MemoryRepo() c1, c2, c3 = build_commit_graph(r.object_store, [[1], [2, 1], [3, 1, 2]]) self.assertEqual(r[c1.tree], parse_tree(r, c1.id)) self.assertEqual(r[c1.tree], parse_tree(r, c1.tree)) def test_from_ref(self) -> None: r = MemoryRepo() c1, c2, c3 = build_commit_graph(r.object_store, [[1], [2, 1], [3, 1, 2]]) r.refs[b"refs/heads/foo"] = c1.id self.assertEqual(r[c1.tree], parse_tree(r, b"foo")) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_pack.py0000644000175100002000000014014514731042555016335 0ustar00runnerdocker# test_pack.py -- Tests for the handling of git packs. # Copyright (C) 2007 James Westby # Copyright (C) 2008 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for Dulwich packs.""" import os import shutil import sys import tempfile import zlib from hashlib import sha1 from io import BytesIO from typing import NoReturn from dulwich.errors import ApplyDeltaError, ChecksumMismatch from dulwich.file import GitFile from dulwich.object_store import MemoryObjectStore from dulwich.objects import Blob, Commit, Tree, hex_to_sha, sha_to_hex from dulwich.pack import ( OFS_DELTA, REF_DELTA, DeltaChainIterator, MemoryPackIndex, Pack, PackData, PackStreamReader, UnpackedObject, UnresolvedDeltas, _delta_encode_size, _encode_copy_operation, apply_delta, compute_file_sha, create_delta, deltify_pack_objects, load_pack_index, read_zlib_chunks, unpack_object, write_pack, write_pack_header, write_pack_index_v1, write_pack_index_v2, write_pack_object, ) from dulwich.tests.utils import build_pack, make_object from . import TestCase pack1_sha = b"bc63ddad95e7321ee734ea11a7a62d314e0d7481" a_sha = b"6f670c0fb53f9463760b7295fbb814e965fb20c8" tree_sha = b"b2a2766a2879c209ab1176e7e778b81ae422eeaa" commit_sha = b"f18faa16531ac570a3fdc8c7ca16682548dafd12" indexmode = "0o100644" if sys.platform != "win32" else "0o100666" class PackTests(TestCase): """Base class for testing packs.""" def setUp(self) -> None: super().setUp() self.tempdir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.tempdir) datadir = os.path.abspath( os.path.join(os.path.dirname(__file__), "../testdata/packs") ) def get_pack_index(self, sha): """Returns a PackIndex from the datadir with the given sha.""" return load_pack_index( os.path.join(self.datadir, "pack-{}.idx".format(sha.decode("ascii"))) ) def get_pack_data(self, sha): """Returns a PackData object from the datadir with the given sha.""" return PackData( os.path.join(self.datadir, "pack-{}.pack".format(sha.decode("ascii"))) ) def get_pack(self, sha): return Pack(os.path.join(self.datadir, "pack-{}".format(sha.decode("ascii")))) def assertSucceeds(self, func, *args, **kwargs) -> None: try: func(*args, **kwargs) except ChecksumMismatch as e: self.fail(e) class PackIndexTests(PackTests): """Class that tests the index of packfiles.""" def test_object_offset(self) -> None: """Tests that the correct object offset is returned from the index.""" p = self.get_pack_index(pack1_sha) self.assertRaises(KeyError, p.object_offset, pack1_sha) self.assertEqual(p.object_offset(a_sha), 178) self.assertEqual(p.object_offset(tree_sha), 138) self.assertEqual(p.object_offset(commit_sha), 12) def test_object_sha1(self) -> None: """Tests that the correct object offset is returned from the index.""" p = self.get_pack_index(pack1_sha) self.assertRaises(KeyError, p.object_sha1, 876) self.assertEqual(p.object_sha1(178), hex_to_sha(a_sha)) self.assertEqual(p.object_sha1(138), hex_to_sha(tree_sha)) self.assertEqual(p.object_sha1(12), hex_to_sha(commit_sha)) def test_iter_prefix(self) -> None: p = self.get_pack_index(pack1_sha) self.assertEqual([p.object_sha1(178)], list(p.iter_prefix(hex_to_sha(a_sha)))) self.assertEqual( [p.object_sha1(178)], list(p.iter_prefix(hex_to_sha(a_sha)[:5])) ) self.assertEqual( [p.object_sha1(178)], list(p.iter_prefix(hex_to_sha(a_sha)[:2])) ) def test_index_len(self) -> None: p = self.get_pack_index(pack1_sha) self.assertEqual(3, len(p)) def test_get_stored_checksum(self) -> None: p = self.get_pack_index(pack1_sha) self.assertEqual( b"f2848e2ad16f329ae1c92e3b95e91888daa5bd01", sha_to_hex(p.get_stored_checksum()), ) self.assertEqual( b"721980e866af9a5f93ad674144e1459b8ba3e7b7", sha_to_hex(p.get_pack_checksum()), ) def test_index_check(self) -> None: p = self.get_pack_index(pack1_sha) self.assertSucceeds(p.check) def test_iterentries(self) -> None: p = self.get_pack_index(pack1_sha) entries = [(sha_to_hex(s), o, c) for s, o, c in p.iterentries()] self.assertEqual( [ (b"6f670c0fb53f9463760b7295fbb814e965fb20c8", 178, None), (b"b2a2766a2879c209ab1176e7e778b81ae422eeaa", 138, None), (b"f18faa16531ac570a3fdc8c7ca16682548dafd12", 12, None), ], entries, ) def test_iter(self) -> None: p = self.get_pack_index(pack1_sha) self.assertEqual({tree_sha, commit_sha, a_sha}, set(p)) class TestPackDeltas(TestCase): test_string1 = b"The answer was flailing in the wind" test_string2 = b"The answer was falling down the pipe" test_string3 = b"zzzzz" test_string_empty = b"" test_string_big = b"Z" * 8192 test_string_huge = b"Z" * 100000 def _test_roundtrip(self, base, target) -> None: self.assertEqual( target, b"".join(apply_delta(base, list(create_delta(base, target)))) ) def test_nochange(self) -> None: self._test_roundtrip(self.test_string1, self.test_string1) def test_nochange_huge(self) -> None: self._test_roundtrip(self.test_string_huge, self.test_string_huge) def test_change(self) -> None: self._test_roundtrip(self.test_string1, self.test_string2) def test_rewrite(self) -> None: self._test_roundtrip(self.test_string1, self.test_string3) def test_empty_to_big(self) -> None: self._test_roundtrip(self.test_string_empty, self.test_string_big) def test_empty_to_huge(self) -> None: self._test_roundtrip(self.test_string_empty, self.test_string_huge) def test_huge_copy(self) -> None: self._test_roundtrip( self.test_string_huge + self.test_string1, self.test_string_huge + self.test_string2, ) def test_dest_overflow(self) -> None: self.assertRaises( ApplyDeltaError, apply_delta, b"a" * 0x10000, b"\x80\x80\x04\x80\x80\x04\x80" + b"a" * 0x10000, ) self.assertRaises( ApplyDeltaError, apply_delta, b"", b"\x00\x80\x02\xb0\x11\x11" ) def test_pypy_issue(self) -> None: # Test for https://github.com/jelmer/dulwich/issues/509 / # https://bitbucket.org/pypy/pypy/issues/2499/cpyext-pystring_asstring-doesnt-work chunks = [ b"tree 03207ccf58880a748188836155ceed72f03d65d6\n" b"parent 408fbab530fd4abe49249a636a10f10f44d07a21\n" b"author Victor Stinner " b"1421355207 +0100\n" b"committer Victor Stinner " b"1421355207 +0100\n" b"\n" b"Backout changeset 3a06020af8cf\n" b"\nStreamWriter: close() now clears the reference to the " b"transport\n" b"\nStreamWriter now raises an exception if it is closed: " b"write(), writelines(),\n" b"write_eof(), can_write_eof(), get_extra_info(), drain().\n" ] delta = [ b"\xcd\x03\xad\x03]tree ff3c181a393d5a7270cddc01ea863818a8621ca8\n" b"parent 20a103cc90135494162e819f98d0edfc1f1fba6b\x91]7\x0510738" b"\x91\x99@\x0b10738 +0100\x93\x04\x01\xc9" ] res = apply_delta(chunks, delta) expected = [ b"tree ff3c181a393d5a7270cddc01ea863818a8621ca8\n" b"parent 20a103cc90135494162e819f98d0edfc1f1fba6b", b"\nauthor Victor Stinner 14213", b"10738", b" +0100\ncommitter Victor Stinner " b"14213", b"10738 +0100", b"\n\nStreamWriter: close() now clears the reference to the " b"transport\n\n" b"StreamWriter now raises an exception if it is closed: " b"write(), writelines(),\n" b"write_eof(), can_write_eof(), get_extra_info(), drain().\n", ] self.assertEqual(b"".join(expected), b"".join(res)) class TestPackData(PackTests): """Tests getting the data from the packfile.""" def test_create_pack(self) -> None: self.get_pack_data(pack1_sha).close() def test_from_file(self) -> None: path = os.path.join( self.datadir, "pack-{}.pack".format(pack1_sha.decode("ascii")) ) with open(path, "rb") as f: PackData.from_file(f, os.path.getsize(path)) def test_pack_len(self) -> None: with self.get_pack_data(pack1_sha) as p: self.assertEqual(3, len(p)) def test_index_check(self) -> None: with self.get_pack_data(pack1_sha) as p: self.assertSucceeds(p.check) def test_iter_unpacked(self) -> None: with self.get_pack_data(pack1_sha) as p: commit_data = ( b"tree b2a2766a2879c209ab1176e7e778b81ae422eeaa\n" b"author James Westby " b"1174945067 +0100\n" b"committer James Westby " b"1174945067 +0100\n" b"\n" b"Test commit\n" ) blob_sha = b"6f670c0fb53f9463760b7295fbb814e965fb20c8" tree_data = b"100644 a\0" + hex_to_sha(blob_sha) actual = list(p.iter_unpacked()) self.assertEqual( [ UnpackedObject( offset=12, pack_type_num=1, decomp_chunks=[commit_data], crc32=None, ), UnpackedObject( offset=138, pack_type_num=2, decomp_chunks=[tree_data], crc32=None, ), UnpackedObject( offset=178, pack_type_num=3, decomp_chunks=[b"test 1\n"], crc32=None, ), ], actual, ) def test_iterentries(self) -> None: with self.get_pack_data(pack1_sha) as p: entries = {(sha_to_hex(s), o, c) for s, o, c in p.iterentries()} self.assertEqual( { ( b"6f670c0fb53f9463760b7295fbb814e965fb20c8", 178, 1373561701, ), ( b"b2a2766a2879c209ab1176e7e778b81ae422eeaa", 138, 912998690, ), ( b"f18faa16531ac570a3fdc8c7ca16682548dafd12", 12, 3775879613, ), }, entries, ) def test_create_index_v1(self) -> None: with self.get_pack_data(pack1_sha) as p: filename = os.path.join(self.tempdir, "v1test.idx") p.create_index_v1(filename) idx1 = load_pack_index(filename) idx2 = self.get_pack_index(pack1_sha) self.assertEqual(oct(os.stat(filename).st_mode), indexmode) self.assertEqual(idx1, idx2) def test_create_index_v2(self) -> None: with self.get_pack_data(pack1_sha) as p: filename = os.path.join(self.tempdir, "v2test.idx") p.create_index_v2(filename) idx1 = load_pack_index(filename) idx2 = self.get_pack_index(pack1_sha) self.assertEqual(oct(os.stat(filename).st_mode), indexmode) self.assertEqual(idx1, idx2) def test_compute_file_sha(self) -> None: f = BytesIO(b"abcd1234wxyz") self.assertEqual( sha1(b"abcd1234wxyz").hexdigest(), compute_file_sha(f).hexdigest() ) self.assertEqual( sha1(b"abcd1234wxyz").hexdigest(), compute_file_sha(f, buffer_size=5).hexdigest(), ) self.assertEqual( sha1(b"abcd1234").hexdigest(), compute_file_sha(f, end_ofs=-4).hexdigest(), ) self.assertEqual( sha1(b"1234wxyz").hexdigest(), compute_file_sha(f, start_ofs=4).hexdigest(), ) self.assertEqual( sha1(b"1234").hexdigest(), compute_file_sha(f, start_ofs=4, end_ofs=-4).hexdigest(), ) def test_compute_file_sha_short_file(self) -> None: f = BytesIO(b"abcd1234wxyz") self.assertRaises(AssertionError, compute_file_sha, f, end_ofs=-20) self.assertRaises(AssertionError, compute_file_sha, f, end_ofs=20) self.assertRaises( AssertionError, compute_file_sha, f, start_ofs=10, end_ofs=-12 ) class TestPack(PackTests): def test_len(self) -> None: with self.get_pack(pack1_sha) as p: self.assertEqual(3, len(p)) def test_contains(self) -> None: with self.get_pack(pack1_sha) as p: self.assertIn(tree_sha, p) def test_get(self) -> None: with self.get_pack(pack1_sha) as p: self.assertEqual(type(p[tree_sha]), Tree) def test_iter(self) -> None: with self.get_pack(pack1_sha) as p: self.assertEqual({tree_sha, commit_sha, a_sha}, set(p)) def test_iterobjects(self) -> None: with self.get_pack(pack1_sha) as p: expected = {p[s] for s in [commit_sha, tree_sha, a_sha]} self.assertEqual(expected, set(list(p.iterobjects()))) def test_pack_tuples(self) -> None: with self.get_pack(pack1_sha) as p: tuples = p.pack_tuples() expected = {(p[s], None) for s in [commit_sha, tree_sha, a_sha]} self.assertEqual(expected, set(list(tuples))) self.assertEqual(expected, set(list(tuples))) self.assertEqual(3, len(tuples)) def test_get_object_at(self) -> None: """Tests random access for non-delta objects.""" with self.get_pack(pack1_sha) as p: obj = p[a_sha] self.assertEqual(obj.type_name, b"blob") self.assertEqual(obj.sha().hexdigest().encode("ascii"), a_sha) obj = p[tree_sha] self.assertEqual(obj.type_name, b"tree") self.assertEqual(obj.sha().hexdigest().encode("ascii"), tree_sha) obj = p[commit_sha] self.assertEqual(obj.type_name, b"commit") self.assertEqual(obj.sha().hexdigest().encode("ascii"), commit_sha) def test_copy(self) -> None: with self.get_pack(pack1_sha) as origpack: self.assertSucceeds(origpack.index.check) basename = os.path.join(self.tempdir, "Elch") write_pack(basename, origpack.pack_tuples()) with Pack(basename) as newpack: self.assertEqual(origpack, newpack) self.assertSucceeds(newpack.index.check) self.assertEqual(origpack.name(), newpack.name()) self.assertEqual( origpack.index.get_pack_checksum(), newpack.index.get_pack_checksum(), ) wrong_version = origpack.index.version != newpack.index.version orig_checksum = origpack.index.get_stored_checksum() new_checksum = newpack.index.get_stored_checksum() self.assertTrue(wrong_version or orig_checksum == new_checksum) def test_commit_obj(self) -> None: with self.get_pack(pack1_sha) as p: commit = p[commit_sha] self.assertEqual(b"James Westby ", commit.author) self.assertEqual([], commit.parents) def _copy_pack(self, origpack): basename = os.path.join(self.tempdir, "somepack") write_pack(basename, origpack.pack_tuples()) return Pack(basename) def test_keep_no_message(self) -> None: with self.get_pack(pack1_sha) as p: p = self._copy_pack(p) with p: keepfile_name = p.keep() # file should exist self.assertTrue(os.path.exists(keepfile_name)) with open(keepfile_name) as f: buf = f.read() self.assertEqual("", buf) def test_keep_message(self) -> None: with self.get_pack(pack1_sha) as p: p = self._copy_pack(p) msg = b"some message" with p: keepfile_name = p.keep(msg) # file should exist self.assertTrue(os.path.exists(keepfile_name)) # and contain the right message, with a linefeed with open(keepfile_name, "rb") as f: buf = f.read() self.assertEqual(msg + b"\n", buf) def test_name(self) -> None: with self.get_pack(pack1_sha) as p: self.assertEqual(pack1_sha, p.name()) def test_length_mismatch(self) -> None: with self.get_pack_data(pack1_sha) as data: index = self.get_pack_index(pack1_sha) Pack.from_objects(data, index).check_length_and_checksum() data._file.seek(12) bad_file = BytesIO() write_pack_header(bad_file.write, 9999) bad_file.write(data._file.read()) bad_file = BytesIO(bad_file.getvalue()) bad_data = PackData("", file=bad_file) bad_pack = Pack.from_lazy_objects(lambda: bad_data, lambda: index) self.assertRaises(AssertionError, lambda: bad_pack.data) self.assertRaises(AssertionError, bad_pack.check_length_and_checksum) def test_checksum_mismatch(self) -> None: with self.get_pack_data(pack1_sha) as data: index = self.get_pack_index(pack1_sha) Pack.from_objects(data, index).check_length_and_checksum() data._file.seek(0) bad_file = BytesIO(data._file.read()[:-20] + (b"\xff" * 20)) bad_data = PackData("", file=bad_file) bad_pack = Pack.from_lazy_objects(lambda: bad_data, lambda: index) self.assertRaises(ChecksumMismatch, lambda: bad_pack.data) self.assertRaises(ChecksumMismatch, bad_pack.check_length_and_checksum) def test_iterobjects_2(self) -> None: with self.get_pack(pack1_sha) as p: objs = {o.id: o for o in p.iterobjects()} self.assertEqual(3, len(objs)) self.assertEqual(sorted(objs), sorted(p.index)) self.assertIsInstance(objs[a_sha], Blob) self.assertIsInstance(objs[tree_sha], Tree) self.assertIsInstance(objs[commit_sha], Commit) def test_iterobjects_subset(self) -> None: with self.get_pack(pack1_sha) as p: objs = {o.id: o for o in p.iterobjects_subset([commit_sha])} self.assertEqual(1, len(objs)) self.assertIsInstance(objs[commit_sha], Commit) class TestThinPack(PackTests): def setUp(self) -> None: super().setUp() self.store = MemoryObjectStore() self.blobs = {} for blob in (b"foo", b"bar", b"foo1234", b"bar2468"): self.blobs[blob] = make_object(Blob, data=blob) self.store.add_object(self.blobs[b"foo"]) self.store.add_object(self.blobs[b"bar"]) # Build a thin pack. 'foo' is as an external reference, 'bar' an # internal reference. self.pack_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.pack_dir) self.pack_prefix = os.path.join(self.pack_dir, "pack") with open(self.pack_prefix + ".pack", "wb") as f: build_pack( f, [ (REF_DELTA, (self.blobs[b"foo"].id, b"foo1234")), (Blob.type_num, b"bar"), (REF_DELTA, (self.blobs[b"bar"].id, b"bar2468")), ], store=self.store, ) # Index the new pack. with self.make_pack(True) as pack: with PackData(pack._data_path) as data: data.create_index( self.pack_prefix + ".idx", resolve_ext_ref=pack.resolve_ext_ref ) del self.store[self.blobs[b"bar"].id] def make_pack(self, resolve_ext_ref): return Pack( self.pack_prefix, resolve_ext_ref=self.store.get_raw if resolve_ext_ref else None, ) def test_get_raw(self) -> None: with self.make_pack(False) as p: self.assertRaises(KeyError, p.get_raw, self.blobs[b"foo1234"].id) with self.make_pack(True) as p: self.assertEqual((3, b"foo1234"), p.get_raw(self.blobs[b"foo1234"].id)) def test_get_unpacked_object(self) -> None: self.maxDiff = None with self.make_pack(False) as p: expected = UnpackedObject( 7, delta_base=b"\x19\x10(\x15f=#\xf8\xb7ZG\xe7\xa0\x19e\xdc\xdc\x96F\x8c", decomp_chunks=[b"\x03\x07\x90\x03\x041234"], ) expected.offset = 12 got = p.get_unpacked_object(self.blobs[b"foo1234"].id) self.assertEqual(expected, got) with self.make_pack(True) as p: expected = UnpackedObject( 7, delta_base=b"\x19\x10(\x15f=#\xf8\xb7ZG\xe7\xa0\x19e\xdc\xdc\x96F\x8c", decomp_chunks=[b"\x03\x07\x90\x03\x041234"], ) expected.offset = 12 got = p.get_unpacked_object(self.blobs[b"foo1234"].id) self.assertEqual( expected, got, ) def test_iterobjects(self) -> None: with self.make_pack(False) as p: self.assertRaises(UnresolvedDeltas, list, p.iterobjects()) with self.make_pack(True) as p: self.assertEqual( sorted( [ self.blobs[b"foo1234"].id, self.blobs[b"bar"].id, self.blobs[b"bar2468"].id, ] ), sorted(o.id for o in p.iterobjects()), ) class WritePackTests(TestCase): def test_write_pack_header(self) -> None: f = BytesIO() write_pack_header(f.write, 42) self.assertEqual(b"PACK\x00\x00\x00\x02\x00\x00\x00*", f.getvalue()) def test_write_pack_object(self) -> None: f = BytesIO() f.write(b"header") offset = f.tell() crc32 = write_pack_object(f.write, Blob.type_num, b"blob") self.assertEqual(crc32, zlib.crc32(f.getvalue()[6:]) & 0xFFFFFFFF) f.write(b"x") # unpack_object needs extra trailing data. f.seek(offset) unpacked, unused = unpack_object(f.read, compute_crc32=True) self.assertEqual(Blob.type_num, unpacked.pack_type_num) self.assertEqual(Blob.type_num, unpacked.obj_type_num) self.assertEqual([b"blob"], unpacked.decomp_chunks) self.assertEqual(crc32, unpacked.crc32) self.assertEqual(b"x", unused) def test_write_pack_object_sha(self) -> None: f = BytesIO() f.write(b"header") offset = f.tell() sha_a = sha1(b"foo") sha_b = sha_a.copy() write_pack_object(f.write, Blob.type_num, b"blob", sha=sha_a) self.assertNotEqual(sha_a.digest(), sha_b.digest()) sha_b.update(f.getvalue()[offset:]) self.assertEqual(sha_a.digest(), sha_b.digest()) def test_write_pack_object_compression_level(self) -> None: f = BytesIO() f.write(b"header") offset = f.tell() sha_a = sha1(b"foo") sha_b = sha_a.copy() write_pack_object( f.write, Blob.type_num, b"blob", sha=sha_a, compression_level=6 ) self.assertNotEqual(sha_a.digest(), sha_b.digest()) sha_b.update(f.getvalue()[offset:]) self.assertEqual(sha_a.digest(), sha_b.digest()) pack_checksum = hex_to_sha("721980e866af9a5f93ad674144e1459b8ba3e7b7") class BaseTestPackIndexWriting: def assertSucceeds(self, func, *args, **kwargs) -> None: try: func(*args, **kwargs) except ChecksumMismatch as e: self.fail(e) def index(self, filename, entries, pack_checksum) -> NoReturn: raise NotImplementedError(self.index) def test_empty(self) -> None: idx = self.index("empty.idx", [], pack_checksum) self.assertEqual(idx.get_pack_checksum(), pack_checksum) self.assertEqual(0, len(idx)) def test_large(self) -> None: entry1_sha = hex_to_sha("4e6388232ec39792661e2e75db8fb117fc869ce6") entry2_sha = hex_to_sha("e98f071751bd77f59967bfa671cd2caebdccc9a2") entries = [ (entry1_sha, 0xF2972D0830529B87, 24), (entry2_sha, (~0xF2972D0830529B87) & (2**64 - 1), 92), ] if not self._supports_large: self.assertRaises( TypeError, self.index, "single.idx", entries, pack_checksum ) return idx = self.index("single.idx", entries, pack_checksum) self.assertEqual(idx.get_pack_checksum(), pack_checksum) self.assertEqual(2, len(idx)) actual_entries = list(idx.iterentries()) self.assertEqual(len(entries), len(actual_entries)) for mine, actual in zip(entries, actual_entries): my_sha, my_offset, my_crc = mine actual_sha, actual_offset, actual_crc = actual self.assertEqual(my_sha, actual_sha) self.assertEqual(my_offset, actual_offset) if self._has_crc32_checksum: self.assertEqual(my_crc, actual_crc) else: self.assertIsNone(actual_crc) def test_single(self) -> None: entry_sha = hex_to_sha("6f670c0fb53f9463760b7295fbb814e965fb20c8") my_entries = [(entry_sha, 178, 42)] idx = self.index("single.idx", my_entries, pack_checksum) self.assertEqual(idx.get_pack_checksum(), pack_checksum) self.assertEqual(1, len(idx)) actual_entries = list(idx.iterentries()) self.assertEqual(len(my_entries), len(actual_entries)) for mine, actual in zip(my_entries, actual_entries): my_sha, my_offset, my_crc = mine actual_sha, actual_offset, actual_crc = actual self.assertEqual(my_sha, actual_sha) self.assertEqual(my_offset, actual_offset) if self._has_crc32_checksum: self.assertEqual(my_crc, actual_crc) else: self.assertIsNone(actual_crc) class BaseTestFilePackIndexWriting(BaseTestPackIndexWriting): def setUp(self) -> None: self.tempdir = tempfile.mkdtemp() def tearDown(self) -> None: shutil.rmtree(self.tempdir) def index(self, filename, entries, pack_checksum): path = os.path.join(self.tempdir, filename) self.writeIndex(path, entries, pack_checksum) idx = load_pack_index(path) self.assertSucceeds(idx.check) self.assertEqual(idx.version, self._expected_version) return idx def writeIndex(self, filename, entries, pack_checksum) -> None: # FIXME: Write to BytesIO instead rather than hitting disk ? with GitFile(filename, "wb") as f: self._write_fn(f, entries, pack_checksum) class TestMemoryIndexWriting(TestCase, BaseTestPackIndexWriting): def setUp(self) -> None: TestCase.setUp(self) self._has_crc32_checksum = True self._supports_large = True def index(self, filename, entries, pack_checksum): return MemoryPackIndex(entries, pack_checksum) def tearDown(self) -> None: TestCase.tearDown(self) class TestPackIndexWritingv1(TestCase, BaseTestFilePackIndexWriting): def setUp(self) -> None: TestCase.setUp(self) BaseTestFilePackIndexWriting.setUp(self) self._has_crc32_checksum = False self._expected_version = 1 self._supports_large = False self._write_fn = write_pack_index_v1 def tearDown(self) -> None: TestCase.tearDown(self) BaseTestFilePackIndexWriting.tearDown(self) class TestPackIndexWritingv2(TestCase, BaseTestFilePackIndexWriting): def setUp(self) -> None: TestCase.setUp(self) BaseTestFilePackIndexWriting.setUp(self) self._has_crc32_checksum = True self._supports_large = True self._expected_version = 2 self._write_fn = write_pack_index_v2 def tearDown(self) -> None: TestCase.tearDown(self) BaseTestFilePackIndexWriting.tearDown(self) class ReadZlibTests(TestCase): decomp = ( b"tree 4ada885c9196b6b6fa08744b5862bf92896fc002\n" b"parent None\n" b"author Jelmer Vernooij 1228980214 +0000\n" b"committer Jelmer Vernooij 1228980214 +0000\n" b"\n" b"Provide replacement for mmap()'s offset argument." ) comp = zlib.compress(decomp) extra = b"nextobject" def setUp(self) -> None: super().setUp() self.read = BytesIO(self.comp + self.extra).read self.unpacked = UnpackedObject( Tree.type_num, decomp_len=len(self.decomp), crc32=0 ) def test_decompress_size(self) -> None: good_decomp_len = len(self.decomp) self.unpacked.decomp_len = -1 self.assertRaises(ValueError, read_zlib_chunks, self.read, self.unpacked) self.unpacked.decomp_len = good_decomp_len - 1 self.assertRaises(zlib.error, read_zlib_chunks, self.read, self.unpacked) self.unpacked.decomp_len = good_decomp_len + 1 self.assertRaises(zlib.error, read_zlib_chunks, self.read, self.unpacked) def test_decompress_truncated(self) -> None: read = BytesIO(self.comp[:10]).read self.assertRaises(zlib.error, read_zlib_chunks, read, self.unpacked) read = BytesIO(self.comp).read self.assertRaises(zlib.error, read_zlib_chunks, read, self.unpacked) def test_decompress_empty(self) -> None: unpacked = UnpackedObject(Tree.type_num, decomp_len=0) comp = zlib.compress(b"") read = BytesIO(comp + self.extra).read unused = read_zlib_chunks(read, unpacked) self.assertEqual(b"", b"".join(unpacked.decomp_chunks)) self.assertNotEqual(b"", unused) self.assertEqual(self.extra, unused + read()) def test_decompress_no_crc32(self) -> None: self.unpacked.crc32 = None read_zlib_chunks(self.read, self.unpacked) self.assertEqual(None, self.unpacked.crc32) def _do_decompress_test(self, buffer_size, **kwargs) -> None: unused = read_zlib_chunks( self.read, self.unpacked, buffer_size=buffer_size, **kwargs ) self.assertEqual(self.decomp, b"".join(self.unpacked.decomp_chunks)) self.assertEqual(zlib.crc32(self.comp), self.unpacked.crc32) self.assertNotEqual(b"", unused) self.assertEqual(self.extra, unused + self.read()) def test_simple_decompress(self) -> None: self._do_decompress_test(4096) self.assertEqual(None, self.unpacked.comp_chunks) # These buffer sizes are not intended to be realistic, but rather simulate # larger buffer sizes that may end at various places. def test_decompress_buffer_size_1(self) -> None: self._do_decompress_test(1) def test_decompress_buffer_size_2(self) -> None: self._do_decompress_test(2) def test_decompress_buffer_size_3(self) -> None: self._do_decompress_test(3) def test_decompress_buffer_size_4(self) -> None: self._do_decompress_test(4) def test_decompress_include_comp(self) -> None: self._do_decompress_test(4096, include_comp=True) self.assertEqual(self.comp, b"".join(self.unpacked.comp_chunks)) class DeltifyTests(TestCase): def test_empty(self) -> None: self.assertEqual([], list(deltify_pack_objects([]))) def test_single(self) -> None: b = Blob.from_string(b"foo") self.assertEqual( [ UnpackedObject( b.type_num, sha=b.sha().digest(), delta_base=None, decomp_chunks=b.as_raw_chunks(), ) ], list(deltify_pack_objects([(b, b"")])), ) def test_simple_delta(self) -> None: b1 = Blob.from_string(b"a" * 101) b2 = Blob.from_string(b"a" * 100) delta = list(create_delta(b1.as_raw_chunks(), b2.as_raw_chunks())) self.assertEqual( [ UnpackedObject( b1.type_num, sha=b1.sha().digest(), delta_base=None, decomp_chunks=b1.as_raw_chunks(), ), UnpackedObject( b2.type_num, sha=b2.sha().digest(), delta_base=b1.sha().digest(), decomp_chunks=delta, ), ], list(deltify_pack_objects([(b1, b""), (b2, b"")])), ) class TestPackStreamReader(TestCase): def test_read_objects_emtpy(self) -> None: f = BytesIO() build_pack(f, []) reader = PackStreamReader(f.read) self.assertEqual(0, len(list(reader.read_objects()))) def test_read_objects(self) -> None: f = BytesIO() entries = build_pack( f, [ (Blob.type_num, b"blob"), (OFS_DELTA, (0, b"blob1")), ], ) reader = PackStreamReader(f.read) objects = list(reader.read_objects(compute_crc32=True)) self.assertEqual(2, len(objects)) unpacked_blob, unpacked_delta = objects self.assertEqual(entries[0][0], unpacked_blob.offset) self.assertEqual(Blob.type_num, unpacked_blob.pack_type_num) self.assertEqual(Blob.type_num, unpacked_blob.obj_type_num) self.assertEqual(None, unpacked_blob.delta_base) self.assertEqual(b"blob", b"".join(unpacked_blob.decomp_chunks)) self.assertEqual(entries[0][4], unpacked_blob.crc32) self.assertEqual(entries[1][0], unpacked_delta.offset) self.assertEqual(OFS_DELTA, unpacked_delta.pack_type_num) self.assertEqual(None, unpacked_delta.obj_type_num) self.assertEqual( unpacked_delta.offset - unpacked_blob.offset, unpacked_delta.delta_base, ) delta = create_delta(b"blob", b"blob1") self.assertEqual(b"".join(delta), b"".join(unpacked_delta.decomp_chunks)) self.assertEqual(entries[1][4], unpacked_delta.crc32) def test_read_objects_buffered(self) -> None: f = BytesIO() build_pack( f, [ (Blob.type_num, b"blob"), (OFS_DELTA, (0, b"blob1")), ], ) reader = PackStreamReader(f.read, zlib_bufsize=4) self.assertEqual(2, len(list(reader.read_objects()))) def test_read_objects_empty(self) -> None: reader = PackStreamReader(BytesIO().read) self.assertRaises(AssertionError, list, reader.read_objects()) class TestPackIterator(DeltaChainIterator): _compute_crc32 = True def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._unpacked_offsets: set[int] = set() def _result(self, unpacked): """Return entries in the same format as build_pack.""" return ( unpacked.offset, unpacked.obj_type_num, b"".join(unpacked.obj_chunks), unpacked.sha(), unpacked.crc32, ) def _resolve_object(self, offset, pack_type_num, base_chunks): assert ( offset not in self._unpacked_offsets ), f"Attempted to re-inflate offset {offset}" self._unpacked_offsets.add(offset) return super()._resolve_object(offset, pack_type_num, base_chunks) class DeltaChainIteratorTests(TestCase): def setUp(self) -> None: super().setUp() self.store = MemoryObjectStore() self.fetched = set() def store_blobs(self, blobs_data): blobs = [] for data in blobs_data: blob = make_object(Blob, data=data) blobs.append(blob) self.store.add_object(blob) return blobs def get_raw_no_repeat(self, bin_sha): """Wrapper around store.get_raw that doesn't allow repeat lookups.""" hex_sha = sha_to_hex(bin_sha) self.assertNotIn( hex_sha, self.fetched, f"Attempted to re-fetch object {hex_sha}" ) self.fetched.add(hex_sha) return self.store.get_raw(hex_sha) def make_pack_iter(self, f, thin=None): if thin is None: thin = bool(list(self.store)) resolve_ext_ref = (thin and self.get_raw_no_repeat) or None data = PackData("test.pack", file=f) return TestPackIterator.for_pack_data(data, resolve_ext_ref=resolve_ext_ref) def make_pack_iter_subset(self, f, subset, thin=None): if thin is None: thin = bool(list(self.store)) resolve_ext_ref = (thin and self.get_raw_no_repeat) or None data = PackData("test.pack", file=f) assert data index = MemoryPackIndex.for_pack(data) pack = Pack.from_objects(data, index) return TestPackIterator.for_pack_subset( pack, subset, resolve_ext_ref=resolve_ext_ref ) def assertEntriesMatch(self, expected_indexes, entries, pack_iter) -> None: expected = [entries[i] for i in expected_indexes] self.assertEqual(expected, list(pack_iter._walk_all_chains())) def test_no_deltas(self) -> None: f = BytesIO() entries = build_pack( f, [ (Commit.type_num, b"commit"), (Blob.type_num, b"blob"), (Tree.type_num, b"tree"), ], ) self.assertEntriesMatch([0, 1, 2], entries, self.make_pack_iter(f)) f.seek(0) self.assertEntriesMatch([], entries, self.make_pack_iter_subset(f, [])) f.seek(0) self.assertEntriesMatch( [1, 0], entries, self.make_pack_iter_subset(f, [entries[0][3], entries[1][3]]), ) f.seek(0) self.assertEntriesMatch( [1, 0], entries, self.make_pack_iter_subset( f, [sha_to_hex(entries[0][3]), sha_to_hex(entries[1][3])] ), ) def test_ofs_deltas(self) -> None: f = BytesIO() entries = build_pack( f, [ (Blob.type_num, b"blob"), (OFS_DELTA, (0, b"blob1")), (OFS_DELTA, (0, b"blob2")), ], ) # Delta resolution changed to DFS self.assertEntriesMatch([0, 2, 1], entries, self.make_pack_iter(f)) f.seek(0) self.assertEntriesMatch( [0, 2, 1], entries, self.make_pack_iter_subset(f, [entries[1][3], entries[2][3]]), ) def test_ofs_deltas_chain(self) -> None: f = BytesIO() entries = build_pack( f, [ (Blob.type_num, b"blob"), (OFS_DELTA, (0, b"blob1")), (OFS_DELTA, (1, b"blob2")), ], ) self.assertEntriesMatch([0, 1, 2], entries, self.make_pack_iter(f)) def test_ref_deltas(self) -> None: f = BytesIO() entries = build_pack( f, [ (REF_DELTA, (1, b"blob1")), (Blob.type_num, (b"blob")), (REF_DELTA, (1, b"blob2")), ], ) # Delta resolution changed to DFS self.assertEntriesMatch([1, 2, 0], entries, self.make_pack_iter(f)) def test_ref_deltas_chain(self) -> None: f = BytesIO() entries = build_pack( f, [ (REF_DELTA, (2, b"blob1")), (Blob.type_num, (b"blob")), (REF_DELTA, (1, b"blob2")), ], ) self.assertEntriesMatch([1, 2, 0], entries, self.make_pack_iter(f)) def test_ofs_and_ref_deltas(self) -> None: # Deltas pending on this offset are popped before deltas depending on # this ref. f = BytesIO() entries = build_pack( f, [ (REF_DELTA, (1, b"blob1")), (Blob.type_num, (b"blob")), (OFS_DELTA, (1, b"blob2")), ], ) # Delta resolution changed to DFS self.assertEntriesMatch([1, 0, 2], entries, self.make_pack_iter(f)) def test_mixed_chain(self) -> None: f = BytesIO() entries = build_pack( f, [ (Blob.type_num, b"blob"), (REF_DELTA, (2, b"blob2")), (OFS_DELTA, (0, b"blob1")), (OFS_DELTA, (1, b"blob3")), (OFS_DELTA, (0, b"bob")), ], ) # Delta resolution changed to DFS self.assertEntriesMatch([0, 4, 2, 1, 3], entries, self.make_pack_iter(f)) def test_long_chain(self) -> None: n = 100 objects_spec = [(Blob.type_num, b"blob")] for i in range(n): objects_spec.append((OFS_DELTA, (i, b"blob" + str(i).encode("ascii")))) f = BytesIO() entries = build_pack(f, objects_spec) self.assertEntriesMatch(range(n + 1), entries, self.make_pack_iter(f)) def test_branchy_chain(self) -> None: n = 100 objects_spec = [(Blob.type_num, b"blob")] for i in range(n): objects_spec.append((OFS_DELTA, (0, b"blob" + str(i).encode("ascii")))) f = BytesIO() entries = build_pack(f, objects_spec) # Delta resolution changed to DFS indices = [0, *list(range(100, 0, -1))] self.assertEntriesMatch(indices, entries, self.make_pack_iter(f)) def test_ext_ref(self) -> None: (blob,) = self.store_blobs([b"blob"]) f = BytesIO() entries = build_pack(f, [(REF_DELTA, (blob.id, b"blob1"))], store=self.store) pack_iter = self.make_pack_iter(f) self.assertEntriesMatch([0], entries, pack_iter) self.assertEqual([hex_to_sha(blob.id)], pack_iter.ext_refs()) def test_ext_ref_chain(self) -> None: (blob,) = self.store_blobs([b"blob"]) f = BytesIO() entries = build_pack( f, [ (REF_DELTA, (1, b"blob2")), (REF_DELTA, (blob.id, b"blob1")), ], store=self.store, ) pack_iter = self.make_pack_iter(f) self.assertEntriesMatch([1, 0], entries, pack_iter) self.assertEqual([hex_to_sha(blob.id)], pack_iter.ext_refs()) def test_ext_ref_chain_degenerate(self) -> None: # Test a degenerate case where the sender is sending a REF_DELTA # object that expands to an object already in the repository. (blob,) = self.store_blobs([b"blob"]) (blob2,) = self.store_blobs([b"blob2"]) assert blob.id < blob2.id f = BytesIO() entries = build_pack( f, [ (REF_DELTA, (blob.id, b"blob2")), (REF_DELTA, (0, b"blob3")), ], store=self.store, ) pack_iter = self.make_pack_iter(f) self.assertEntriesMatch([0, 1], entries, pack_iter) self.assertEqual([hex_to_sha(blob.id)], pack_iter.ext_refs()) def test_ext_ref_multiple_times(self) -> None: (blob,) = self.store_blobs([b"blob"]) f = BytesIO() entries = build_pack( f, [ (REF_DELTA, (blob.id, b"blob1")), (REF_DELTA, (blob.id, b"blob2")), ], store=self.store, ) pack_iter = self.make_pack_iter(f) self.assertEntriesMatch([0, 1], entries, pack_iter) self.assertEqual([hex_to_sha(blob.id)], pack_iter.ext_refs()) def test_multiple_ext_refs(self) -> None: b1, b2 = self.store_blobs([b"foo", b"bar"]) f = BytesIO() entries = build_pack( f, [ (REF_DELTA, (b1.id, b"foo1")), (REF_DELTA, (b2.id, b"bar2")), ], store=self.store, ) pack_iter = self.make_pack_iter(f) self.assertEntriesMatch([0, 1], entries, pack_iter) self.assertEqual([hex_to_sha(b1.id), hex_to_sha(b2.id)], pack_iter.ext_refs()) def test_bad_ext_ref_non_thin_pack(self) -> None: (blob,) = self.store_blobs([b"blob"]) f = BytesIO() build_pack(f, [(REF_DELTA, (blob.id, b"blob1"))], store=self.store) pack_iter = self.make_pack_iter(f, thin=False) try: list(pack_iter._walk_all_chains()) self.fail() except UnresolvedDeltas as e: self.assertEqual([blob.id], e.shas) def test_bad_ext_ref_thin_pack(self) -> None: b1, b2, b3 = self.store_blobs([b"foo", b"bar", b"baz"]) f = BytesIO() build_pack( f, [ (REF_DELTA, (1, b"foo99")), (REF_DELTA, (b1.id, b"foo1")), (REF_DELTA, (b2.id, b"bar2")), (REF_DELTA, (b3.id, b"baz3")), ], store=self.store, ) del self.store[b2.id] del self.store[b3.id] pack_iter = self.make_pack_iter(f) try: list(pack_iter._walk_all_chains()) self.fail() except UnresolvedDeltas as e: self.assertEqual((sorted([b2.id, b3.id]),), (sorted(e.shas),)) def test_ext_ref_deltified_object_based_on_itself(self) -> None: b1_content = b"foo" (b1,) = self.store_blobs([b1_content]) f = BytesIO() build_pack( f, [ # b1's content refers to bl1's object ID as delta base (REF_DELTA, (b1.id, b1_content)), ], store=self.store, ) fsize = f.tell() f.seek(0) packdata = PackData.from_file(f, fsize) td = tempfile.mkdtemp() idx_path = os.path.join(td, "test.idx") self.addCleanup(shutil.rmtree, td) packdata.create_index( idx_path, version=2, resolve_ext_ref=self.get_raw_no_repeat, ) packindex = load_pack_index(idx_path) pack = Pack.from_objects(packdata, packindex) try: # Attempting to open this REF_DELTA object would loop forever pack[b1.id] except UnresolvedDeltas as e: self.assertEqual((b1.id), e.shas) class DeltaEncodeSizeTests(TestCase): def test_basic(self) -> None: self.assertEqual(b"\x00", _delta_encode_size(0)) self.assertEqual(b"\x01", _delta_encode_size(1)) self.assertEqual(b"\xfa\x01", _delta_encode_size(250)) self.assertEqual(b"\xe8\x07", _delta_encode_size(1000)) self.assertEqual(b"\xa0\x8d\x06", _delta_encode_size(100000)) class EncodeCopyOperationTests(TestCase): def test_basic(self) -> None: self.assertEqual(b"\x80", _encode_copy_operation(0, 0)) self.assertEqual(b"\x91\x01\x0a", _encode_copy_operation(1, 10)) self.assertEqual(b"\xb1\x64\xe8\x03", _encode_copy_operation(100, 1000)) self.assertEqual(b"\x93\xe8\x03\x01", _encode_copy_operation(1000, 1)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_patch.py0000644000175100002000000005213614731042555016520 0ustar00runnerdocker# test_patch.py -- tests for patch.py # Copyright (C) 2010 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for patch.py.""" from io import BytesIO, StringIO from typing import NoReturn from dulwich.object_store import MemoryObjectStore from dulwich.objects import S_IFGITLINK, Blob, Commit, Tree from dulwich.patch import ( get_summary, git_am_patch_split, write_blob_diff, write_commit_patch, write_object_diff, write_tree_diff, ) from . import SkipTest, TestCase class WriteCommitPatchTests(TestCase): def test_simple_bytesio(self) -> None: f = BytesIO() c = Commit() c.committer = c.author = b"Jelmer " c.commit_time = c.author_time = 1271350201 c.commit_timezone = c.author_timezone = 0 c.message = b"This is the first line\nAnd this is the second line.\n" c.tree = Tree().id write_commit_patch(f, c, b"CONTENTS", (1, 1), version="custom") f.seek(0) lines = f.readlines() self.assertTrue( lines[0].startswith(b"From 0b0d34d1b5b596c928adc9a727a4b9e03d025298") ) self.assertEqual(lines[1], b"From: Jelmer \n") self.assertTrue(lines[2].startswith(b"Date: ")) self.assertEqual( [ b"Subject: [PATCH 1/1] This is the first line\n", b"And this is the second line.\n", b"\n", b"\n", b"---\n", ], lines[3:8], ) self.assertEqual([b"CONTENTS-- \n", b"custom\n"], lines[-2:]) if len(lines) >= 12: # diffstat may not be present self.assertEqual(lines[8], b" 0 files changed\n") class ReadGitAmPatch(TestCase): def test_extract_string(self) -> None: text = b"""\ From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [PATCH 1/2] Remove executable bit from prey.ico (triggers a warning). --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ c, diff, version = git_am_patch_split(StringIO(text.decode("utf-8")), "utf-8") self.assertEqual(b"Jelmer Vernooij ", c.committer) self.assertEqual(b"Jelmer Vernooij ", c.author) self.assertEqual( b"Remove executable bit from prey.ico " b"(triggers a warning).\n", c.message, ) self.assertEqual( b""" pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico """, diff, ) self.assertEqual(b"1.7.0.4", version) def test_extract_bytes(self) -> None: text = b"""\ From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [PATCH 1/2] Remove executable bit from prey.ico (triggers a warning). --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ c, diff, version = git_am_patch_split(BytesIO(text)) self.assertEqual(b"Jelmer Vernooij ", c.committer) self.assertEqual(b"Jelmer Vernooij ", c.author) self.assertEqual( b"Remove executable bit from prey.ico " b"(triggers a warning).\n", c.message, ) self.assertEqual( b""" pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico """, diff, ) self.assertEqual(b"1.7.0.4", version) def test_extract_spaces(self) -> None: text = b"""From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [Dulwich-users] [PATCH] Added unit tests for dulwich.object_store.tree_lookup_path. * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ c, diff, version = git_am_patch_split(BytesIO(text), "utf-8") self.assertEqual( b"""\ Added unit tests for dulwich.object_store.tree_lookup_path. * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. """, c.message, ) def test_extract_pseudo_from_header(self) -> None: text = b"""From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [Dulwich-users] [PATCH] Added unit tests for dulwich.object_store.tree_lookup_path. From: Jelmer Vernooij * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico -- 1.7.0.4 """ c, diff, version = git_am_patch_split(BytesIO(text), "utf-8") self.assertEqual(b"Jelmer Vernooij ", c.author) self.assertEqual( b"""\ Added unit tests for dulwich.object_store.tree_lookup_path. * dulwich/tests/test_object_store.py (TreeLookupPathTests): This test case contains a few tests that ensure the tree_lookup_path function works as expected. """, c.message, ) def test_extract_no_version_tail(self) -> None: text = b"""\ From ff643aae102d8870cac88e8f007e70f58f3a7363 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Thu, 15 Apr 2010 15:40:28 +0200 Subject: [Dulwich-users] [PATCH] Added unit tests for dulwich.object_store.tree_lookup_path. From: Jelmer Vernooij --- pixmaps/prey.ico | Bin 9662 -> 9662 bytes 1 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pixmaps/prey.ico """ c, diff, version = git_am_patch_split(BytesIO(text), "utf-8") self.assertEqual(None, version) def test_extract_mercurial(self) -> NoReturn: raise SkipTest( "git_am_patch_split doesn't handle Mercurial patches " "properly yet" ) expected_diff = """\ diff --git a/dulwich/tests/test_patch.py b/dulwich/tests/test_patch.py --- a/dulwich/tests/test_patch.py +++ b/dulwich/tests/test_patch.py @@ -158,7 +158,7 @@ ''' c, diff, version = git_am_patch_split(BytesIO(text)) - self.assertIs(None, version) + self.assertEqual(None, version) class DiffTests(TestCase): """ text = f"""\ From dulwich-users-bounces+jelmer=samba.org@lists.launchpad.net \ Mon Nov 29 00:58:18 2010 Date: Sun, 28 Nov 2010 17:57:27 -0600 From: Augie Fackler To: dulwich-users Subject: [Dulwich-users] [PATCH] test_patch: fix tests on Python 2.6 Content-Transfer-Encoding: 8bit Change-Id: I5e51313d4ae3a65c3f00c665002a7489121bb0d6 {expected_diff} _______________________________________________ Mailing list: https://launchpad.net/~dulwich-users Post to : dulwich-users@lists.launchpad.net Unsubscribe : https://launchpad.net/~dulwich-users More help : https://help.launchpad.net/ListHelp """ c, diff, version = git_am_patch_split(BytesIO(text)) self.assertEqual(expected_diff, diff) self.assertEqual(None, version) class DiffTests(TestCase): """Tests for write_blob_diff and write_tree_diff.""" def test_blob_diff(self) -> None: f = BytesIO() write_blob_diff( f, (b"foo.txt", 0o644, Blob.from_string(b"old\nsame\n")), (b"bar.txt", 0o644, Blob.from_string(b"new\nsame\n")), ) self.assertEqual( [ b"diff --git a/foo.txt b/bar.txt", b"index 3b0f961..a116b51 644", b"--- a/foo.txt", b"+++ b/bar.txt", b"@@ -1,2 +1,2 @@", b"-old", b"+new", b" same", ], f.getvalue().splitlines(), ) def test_blob_add(self) -> None: f = BytesIO() write_blob_diff( f, (None, None, None), (b"bar.txt", 0o644, Blob.from_string(b"new\nsame\n")), ) self.assertEqual( [ b"diff --git a/bar.txt b/bar.txt", b"new file mode 644", b"index 0000000..a116b51", b"--- /dev/null", b"+++ b/bar.txt", b"@@ -0,0 +1,2 @@", b"+new", b"+same", ], f.getvalue().splitlines(), ) def test_blob_remove(self) -> None: f = BytesIO() write_blob_diff( f, (b"bar.txt", 0o644, Blob.from_string(b"new\nsame\n")), (None, None, None), ) self.assertEqual( [ b"diff --git a/bar.txt b/bar.txt", b"deleted file mode 644", b"index a116b51..0000000", b"--- a/bar.txt", b"+++ /dev/null", b"@@ -1,2 +0,0 @@", b"-new", b"-same", ], f.getvalue().splitlines(), ) def test_tree_diff(self) -> None: f = BytesIO() store = MemoryObjectStore() added = Blob.from_string(b"add\n") removed = Blob.from_string(b"removed\n") changed1 = Blob.from_string(b"unchanged\nremoved\n") changed2 = Blob.from_string(b"unchanged\nadded\n") unchanged = Blob.from_string(b"unchanged\n") tree1 = Tree() tree1.add(b"removed.txt", 0o644, removed.id) tree1.add(b"changed.txt", 0o644, changed1.id) tree1.add(b"unchanged.txt", 0o644, changed1.id) tree2 = Tree() tree2.add(b"added.txt", 0o644, added.id) tree2.add(b"changed.txt", 0o644, changed2.id) tree2.add(b"unchanged.txt", 0o644, changed1.id) store.add_objects( [ (o, None) for o in [ tree1, tree2, added, removed, changed1, changed2, unchanged, ] ] ) write_tree_diff(f, store, tree1.id, tree2.id) self.assertEqual( [ b"diff --git a/added.txt b/added.txt", b"new file mode 644", b"index 0000000..76d4bb8", b"--- /dev/null", b"+++ b/added.txt", b"@@ -0,0 +1 @@", b"+add", b"diff --git a/changed.txt b/changed.txt", b"index bf84e48..1be2436 644", b"--- a/changed.txt", b"+++ b/changed.txt", b"@@ -1,2 +1,2 @@", b" unchanged", b"-removed", b"+added", b"diff --git a/removed.txt b/removed.txt", b"deleted file mode 644", b"index 2c3f0b3..0000000", b"--- a/removed.txt", b"+++ /dev/null", b"@@ -1 +0,0 @@", b"-removed", ], f.getvalue().splitlines(), ) def test_tree_diff_submodule(self) -> None: f = BytesIO() store = MemoryObjectStore() tree1 = Tree() tree1.add( b"asubmodule", S_IFGITLINK, b"06d0bdd9e2e20377b3180e4986b14c8549b393e4", ) tree2 = Tree() tree2.add( b"asubmodule", S_IFGITLINK, b"cc975646af69f279396d4d5e1379ac6af80ee637", ) store.add_objects([(o, None) for o in [tree1, tree2]]) write_tree_diff(f, store, tree1.id, tree2.id) self.assertEqual( [ b"diff --git a/asubmodule b/asubmodule", b"index 06d0bdd..cc97564 160000", b"--- a/asubmodule", b"+++ b/asubmodule", b"@@ -1 +1 @@", b"-Subproject commit 06d0bdd9e2e20377b3180e4986b14c8549b393e4", b"+Subproject commit cc975646af69f279396d4d5e1379ac6af80ee637", ], f.getvalue().splitlines(), ) def test_object_diff_blob(self) -> None: f = BytesIO() b1 = Blob.from_string(b"old\nsame\n") b2 = Blob.from_string(b"new\nsame\n") store = MemoryObjectStore() store.add_objects([(b1, None), (b2, None)]) write_object_diff( f, store, (b"foo.txt", 0o644, b1.id), (b"bar.txt", 0o644, b2.id) ) self.assertEqual( [ b"diff --git a/foo.txt b/bar.txt", b"index 3b0f961..a116b51 644", b"--- a/foo.txt", b"+++ b/bar.txt", b"@@ -1,2 +1,2 @@", b"-old", b"+new", b" same", ], f.getvalue().splitlines(), ) def test_object_diff_add_blob(self) -> None: f = BytesIO() store = MemoryObjectStore() b2 = Blob.from_string(b"new\nsame\n") store.add_object(b2) write_object_diff(f, store, (None, None, None), (b"bar.txt", 0o644, b2.id)) self.assertEqual( [ b"diff --git a/bar.txt b/bar.txt", b"new file mode 644", b"index 0000000..a116b51", b"--- /dev/null", b"+++ b/bar.txt", b"@@ -0,0 +1,2 @@", b"+new", b"+same", ], f.getvalue().splitlines(), ) def test_object_diff_remove_blob(self) -> None: f = BytesIO() b1 = Blob.from_string(b"new\nsame\n") store = MemoryObjectStore() store.add_object(b1) write_object_diff(f, store, (b"bar.txt", 0o644, b1.id), (None, None, None)) self.assertEqual( [ b"diff --git a/bar.txt b/bar.txt", b"deleted file mode 644", b"index a116b51..0000000", b"--- a/bar.txt", b"+++ /dev/null", b"@@ -1,2 +0,0 @@", b"-new", b"-same", ], f.getvalue().splitlines(), ) def test_object_diff_bin_blob_force(self) -> None: f = BytesIO() # Prepare two slightly different PNG headers b1 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x04\x00\x00\x00\x05\x04\x8b" ) b2 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x03\x00\x00\x00\x98\xd3\xb3" ) store = MemoryObjectStore() store.add_objects([(b1, None), (b2, None)]) write_object_diff( f, store, (b"foo.png", 0o644, b1.id), (b"bar.png", 0o644, b2.id), diff_binary=True, ) self.assertEqual( [ b"diff --git a/foo.png b/bar.png", b"index f73e47d..06364b7 644", b"--- a/foo.png", b"+++ b/bar.png", b"@@ -1,4 +1,4 @@", b" \x89PNG", b" \x1a", b" \x00\x00\x00", b"-IHDR\x00\x00\x01\xd5\x00\x00\x00" b"\x9f\x08\x04\x00\x00\x00\x05\x04\x8b", b"\\ No newline at end of file", b"+IHDR\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x03\x00\x00\x00\x98\xd3\xb3", b"\\ No newline at end of file", ], f.getvalue().splitlines(), ) def test_object_diff_bin_blob(self) -> None: f = BytesIO() # Prepare two slightly different PNG headers b1 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x04\x00\x00\x00\x05\x04\x8b" ) b2 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x03\x00\x00\x00\x98\xd3\xb3" ) store = MemoryObjectStore() store.add_objects([(b1, None), (b2, None)]) write_object_diff( f, store, (b"foo.png", 0o644, b1.id), (b"bar.png", 0o644, b2.id) ) self.assertEqual( [ b"diff --git a/foo.png b/bar.png", b"index f73e47d..06364b7 644", b"Binary files a/foo.png and b/bar.png differ", ], f.getvalue().splitlines(), ) def test_object_diff_add_bin_blob(self) -> None: f = BytesIO() b2 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x03\x00\x00\x00\x98\xd3\xb3" ) store = MemoryObjectStore() store.add_object(b2) write_object_diff(f, store, (None, None, None), (b"bar.png", 0o644, b2.id)) self.assertEqual( [ b"diff --git a/bar.png b/bar.png", b"new file mode 644", b"index 0000000..06364b7", b"Binary files /dev/null and b/bar.png differ", ], f.getvalue().splitlines(), ) def test_object_diff_remove_bin_blob(self) -> None: f = BytesIO() b1 = Blob.from_string( b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" b"\x00\x00\x00\x0d\x49\x48\x44\x52" b"\x00\x00\x01\xd5\x00\x00\x00\x9f" b"\x08\x04\x00\x00\x00\x05\x04\x8b" ) store = MemoryObjectStore() store.add_object(b1) write_object_diff(f, store, (b"foo.png", 0o644, b1.id), (None, None, None)) self.assertEqual( [ b"diff --git a/foo.png b/foo.png", b"deleted file mode 644", b"index f73e47d..0000000", b"Binary files a/foo.png and /dev/null differ", ], f.getvalue().splitlines(), ) def test_object_diff_kind_change(self) -> None: f = BytesIO() b1 = Blob.from_string(b"new\nsame\n") store = MemoryObjectStore() store.add_object(b1) write_object_diff( f, store, (b"bar.txt", 0o644, b1.id), ( b"bar.txt", 0o160000, b"06d0bdd9e2e20377b3180e4986b14c8549b393e4", ), ) self.assertEqual( [ b"diff --git a/bar.txt b/bar.txt", b"old file mode 644", b"new file mode 160000", b"index a116b51..06d0bdd 160000", b"--- a/bar.txt", b"+++ b/bar.txt", b"@@ -1,2 +1 @@", b"-new", b"-same", b"+Subproject commit 06d0bdd9e2e20377b3180e4986b14c8549b393e4", ], f.getvalue().splitlines(), ) class GetSummaryTests(TestCase): def test_simple(self) -> None: c = Commit() c.committer = c.author = b"Jelmer " c.commit_time = c.author_time = 1271350201 c.commit_timezone = c.author_timezone = 0 c.message = b"This is the first line\nAnd this is the second line.\n" c.tree = Tree().id self.assertEqual("This-is-the-first-line", get_summary(c)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_porcelain.py0000644000175100002000000040341414731042555017374 0ustar00runnerdocker# test_porcelain.py -- porcelain tests # Copyright (C) 2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for dulwich.porcelain.""" import contextlib import os import platform import re import shutil import stat import subprocess import sys import tarfile import tempfile import threading import time from io import BytesIO, StringIO from unittest import skipIf from dulwich import porcelain from dulwich.diff_tree import tree_changes from dulwich.errors import CommitError from dulwich.objects import ZERO_SHA, Blob, Tag, Tree from dulwich.porcelain import CheckoutError from dulwich.repo import NoIndexPresent, Repo from dulwich.server import DictBackend from dulwich.tests.utils import build_commit_graph, make_commit, make_object from dulwich.web import make_server, make_wsgi_chain from . import TestCase try: import gpg except ImportError: gpg = None def flat_walk_dir(dir_to_walk): for dirpath, _, filenames in os.walk(dir_to_walk): rel_dirpath = os.path.relpath(dirpath, dir_to_walk) if not dirpath == dir_to_walk: yield rel_dirpath for filename in filenames: if dirpath == dir_to_walk: yield filename else: yield os.path.join(rel_dirpath, filename) class PorcelainTestCase(TestCase): def setUp(self) -> None: super().setUp() self.test_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.test_dir) self.repo_path = os.path.join(self.test_dir, "repo") self.repo = Repo.init(self.repo_path, mkdir=True) self.addCleanup(self.repo.close) def assertRecentTimestamp(self, ts) -> None: # On some slow CIs it does actually take more than 5 seconds to go from # creating the tag to here. self.assertLess(time.time() - ts, 50) @skipIf(gpg is None, "gpg is not available") class PorcelainGpgTestCase(PorcelainTestCase): DEFAULT_KEY = """ -----BEGIN PGP PRIVATE KEY BLOCK----- lQVYBGBjIyIBDADAwydvMPQqeEiK54FG1DHwT5sQejAaJOb+PsOhVa4fLcKsrO3F g5CxO+/9BHCXAr8xQAtp/gOhDN05fyK3MFyGlL9s+Cd8xf34S3R4rN/qbF0oZmaa FW0MuGnniq54HINs8KshadVn1Dhi/GYSJ588qNFRl/qxFTYAk+zaGsgX/QgFfy0f djWXJLypZXu9D6DlyJ0cPSzUlfBkI2Ytx6grzIquRjY0FbkjK3l+iGsQ+ebRMdcP Sqd5iTN9XuzIUVoBFAZBRjibKV3N2wxlnCbfLlzCyDp7rktzSThzjJ2pVDuLrMAx 6/L9hIhwmFwdtY4FBFGvMR0b0Ugh3kCsRWr8sgj9I7dUoLHid6ObYhJFhnD3GzRc U+xX1uy3iTCqJDsG334aQIhC5Giuxln4SUZna2MNbq65ksh38N1aM/t3+Dc/TKVB rb5KWicRPCQ4DIQkHMDCSPyj+dvRLCPzIaPvHD7IrCfHYHOWuvvPGCpwjo0As3iP IecoMeguPLVaqgcAEQEAAQAL/i5/pQaUd4G7LDydpbixPS6r9UrfPrU/y5zvBP/p DCynPDutJ1oq539pZvXQ2VwEJJy7x0UVKkjyMndJLNWly9wHC7o8jkHx/NalVP47 LXR+GWbCdOOcYYbdAWcCNB3zOtzPnWhdAEagkc2G9xRQDIB0dLHLCIUpCbLP/CWM qlHnDsVMrVTWjgzcpsnyGgw8NeLYJtYGB8dsN+XgCCjo7a9LEvUBKNgdmWBbf14/ iBw7PCugazFcH9QYfZwzhsi3nqRRagTXHbxFRG0LD9Ro9qCEutHYGP2PJ59Nj8+M zaVkJj/OxWxVOGvn2q16mQBCjKpbWfqXZVVl+G5DGOmiSTZqXy+3j6JCKdOMy6Qd JBHOHhFZXYmWYaaPzoc33T/C3QhMfY5sOtUDLJmV05Wi4dyBeNBEslYgUuTk/jXb 5ZAie25eDdrsoqkcnSs2ZguMF7AXhe6il2zVhUUMs/6UZgd6I7I4Is0HXT/pnxEp uiTRFu4v8E+u+5a8O3pffe5boQYA3TsIxceen20qY+kRaTOkURHMZLn/y6KLW8bZ rNJyXWS9hBAcbbSGhfOwYfzbDCM17yPQO3E2zo8lcGdRklUdIIaCxQwtu36N5dfx OLCCQc5LmYdl/EAm91iAhrr7dNntZ18MU09gdzUu+ONZwu4CP3cJT83+qYZULso8 4Fvd/X8IEfGZ7kM+ylrdqBwtlrn8yYXtom+ows2M2UuNR53B+BUOd73kVLTkTCjE JH63+nE8BqG7tDLCMws+23SAA3xxBgDfDrr0x7zCozQKVQEqBzQr9Uoo/c/ZjAfi syzNSrDz+g5gqJYtuL9XpPJVWf6V1GXVyJlSbxR9CjTkBxmlPxpvV25IsbVSsh0o aqkf2eWpbCL6Qb2E0jd1rvf8sGeTTohzYfiSVVsC2t9ngRO/CmetizwQBvRzLGMZ 4mtAPiy7ZEDc2dFrPp7zlKISYmJZUx/DJVuZWuOrVMpBP+bSgJXoMTlICxZUqUnE 2VKVStb/L+Tl8XCwIWdrZb9BaDnHqfcGAM2B4HNPxP88Yj1tEDly/vqeb3vVMhj+ S1lunnLdgxp46YyuTMYAzj88eCGurRtzBsdxxlGAsioEnZGebEqAHQbieKq/DO6I MOMZHMSVBDqyyIx3assGlxSX8BSFW0lhKyT7i0XqnAgCJ9f/5oq0SbFGq+01VQb7 jIx9PbcYJORxsE0JG/CXXPv27bRtQXsudkWGSYvC0NLOgk4z8+kQpQtyFh16lujq WRwMeriu0qNDjCa1/eHIKDovhAZ3GyO5/9m1tBlUZXN0IFVzZXIgPHRlc3RAdGVz dC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAFiEEjrR8 MQ4fJK44PYMvfN2AClLmXiYFAmDcEZEACgkQfN2AClLmXibZzgv/ZfeTpTuqQE1W C1jT5KpQExnt0BizTX0U7BvSn8Fr6VXTyol6kYc3u71GLUuJyawCLtIzOXqOXJvz bjcZqymcMADuftKcfMy513FhbF6MhdVd6QoeBP6+7/xXOFJCi+QVYF7SQ2h7K1Qm +yXOiAMgSxhCZQGPBNJLlDUOd47nSIMANvlumFtmLY/1FD7RpG7WQWjeX1mnxNTw hUU+Yv7GuFc/JprXCIYqHbhWfvXyVtae2ZK4xuVi5eqwA2RfggOVM7drb+CgPhG0 +9aEDDLOZqVi65wK7J73Puo3rFTbPQMljxw5s27rWqF+vB6hhVdJOPNomWy3naPi k5MW0mhsacASz1WYndpZz+XaQTq/wJF5HUyyeUWJ0vlOEdwx021PHcqSTyfNnkjD KncrE21t2sxWRsgGDETxIwkd2b2HNGAvveUD0ffFK/oJHGSXjAERFGc3wuiDj3mQ BvKm4wt4QF9ZMrCdhMAA6ax5kfEUqQR4ntmrJk/khp/mV7TILaI4nQVYBGBjIyIB DADghIo9wXnRxzfdDTvwnP8dHpLAIaPokgdpyLswqUCixJWiW2xcV6weUjEWwH6n eN/t1uZYVehbrotxVPla+MPvzhxp6/cmG+2lhzEBOp6zRwnL1wIB6HoKJfpREhyM c8rLR0zMso1L1bJTyydvnu07a7BWo3VWKjilb0rEZZUSD/2hidx5HxMOJSoidLWe d/PPuv6yht3NtA4UThlcfldm9G6PbqCdm1kMEKAkq0wVJvhPJ6gEFRNJimgygfUw MDFXEIhQtxjgdV5Uoz3O5452VLoRsDlgpi3E0WDGj7WXDaO5uSU0T5aJgVgHCP/f xZhHuQFk2YYIl5nCBpOZyWWI0IKmscTuEwzpkhICQDQFvcMZ5ibsl7wA2P7YTrQf FDMjjzuaK80GYPfxDFlyKUyLqFt8w/QzsZLDLX7+jxIEpbRAaMw/JsWqm5BMxxbS 3CIQiS5S3oSKDsNINelqWFfwvLhvlQra8gIxyNTlek25OdgG66BiiX+seH8A/ql+ F+MAEQEAAQAL/1jrNSLjMt9pwo6qFKClVQZP2vf7+sH7v7LeHIDXr3EnYUnVYnOq B1FU5PspTp/+J9W25DB9CZLx7Gj8qeslFdiuLSOoIBB4RCToB3kAoeTH0DHqW/Gs hFTrmJkuDp9zpo/ek6SIXJx5rHAyR9KVw0fizQprH2f6PcgLbTWeM61dJuqowmg3 7eCOyIKv7VQvFqEhYokLD+JNmrvg+Htg0DXGvdjRjAwPf/NezEXpj67a6cHTp1/C hwp7pevG+3fTxaCJFesl5/TxxtnaBLE8m2uo/S6Hxgn9l0edonroe1QlTjEqGLy2 7qi2z5Rem+v6GWNDRgvAWur13v8FNdyduHlioG/NgRsU9mE2MYeFsfi3cfNpJQp/ wC9PSCIXrb/45mkS8KyjZpCrIPB9RV/m0MREq01TPom7rstZc4A1pD0Ot7AtUYS3 e95zLyEmeLziPJ9fV4fgPmEudDr1uItnmV0LOskKlpg5sc0hhdrwYoobfkKt2dx6 DqfMlcM1ZkUbLQYA4jwfpFJG4HmYvjL2xCJxM0ycjvMbqFN+4UjgYWVlRfOrm1V4 Op86FjbRbV6OOCNhznotAg7mul4xtzrrTkK8o3YLBeJseDgl4AWuzXtNa9hE0XpK 9gJoEHUuBOOsamVh2HpXESFyE5CclOV7JSh541TlZKfnqfZYCg4JSbp0UijkawCL 5bJJUiGGMD9rZUxIAKQO1DvUEzptS7Jl6S3y5sbIIhilp4KfYWbSk3PPu9CnZD5b LhEQp0elxnb/IL8PBgD+DpTeC8unkGKXUpbe9x0ISI6V1D6FmJq/FxNg7fMa3QCh fGiAyoTm80ZETynj+blRaDO3gY4lTLa3Opubof1EqK2QmwXmpyvXEZNYcQfQ2CCS GOWUCK8jEQamUPf1PWndZXJUmROI1WukhlL71V/ir6zQeVCv1wcwPwclJPnAe87u pEklnCYpvsEldwHUX9u0BWzoULIEsi+ddtHmT0KTeF/DHRy0W15jIHbjFqhqckj1 /6fmr7l7kIi/kN4vWe0F/0Q8IXX+cVMgbl3aIuaGcvENLGcoAsAtPGx88SfRgmfu HK64Y7hx1m+Bo215rxJzZRjqHTBPp0BmCi+JKkaavIBrYRbsx20gveI4dzhLcUhB kiT4Q7oz0/VbGHS1CEf9KFeS/YOGj57s4yHauSVI0XdP9kBRTWmXvBkzsooB2cKH hwhUN7iiT1k717CiTNUT6Q/pcPFCyNuMoBBGQTU206JEgIjQvI3f8xMUMGmGVVQz 9/k716ycnhb2JZ/Q/AyQIeHJiQG2BBgBCAAgAhsMFiEEjrR8MQ4fJK44PYMvfN2A ClLmXiYFAmDcEa4ACgkQfN2AClLmXiZxxQv/XaMN0hPCygtrQMbCsTNb34JbvJzh hngPuUAfTbRHrR3YeATyQofNbL0DD3fvfzeFF8qESqvzCSZxS6dYsXPd4MCJTzlp zYBZ2X0sOrgDqZvqCZKN72RKgdk0KvthdzAxsIm2dfcQOxxowXMxhJEXZmsFpusx jKJxOcrfVRjXJnh9isY0NpCoqMQ+3k3wDJ3VGEHV7G+A+vFkWfbLJF5huQ96uaH9 Uc+jUsREUH9G82ZBqpoioEN8Ith4VXpYnKdTMonK/+ZcyeraJZhXrvbjnEomKdzU 0pu4bt1HlLR3dcnpjN7b009MBf2xLgEfQk2nPZ4zzY+tDkxygtPllaB4dldFjBpT j7Q+t49sWMjmlJUbLlHfuJ7nUUK5+cGjBsWVObAEcyfemHWCTVFnEa2BJslGC08X rFcjRRcMEr9ct4551QFBHsv3O/Wp3/wqczYgE9itSnGT05w+4vLt4smG+dnEHjRJ brMb2upTHa+kjktjdO96/BgSnKYqmNmPB/qB =ivA/ -----END PGP PRIVATE KEY BLOCK----- """ DEFAULT_KEY_ID = "8EB47C310E1F24AE383D832F7CDD800A52E65E26" NON_DEFAULT_KEY = """ -----BEGIN PGP PRIVATE KEY BLOCK----- lQVYBGBjI0ABDADGWBRp+t02emfzUlhrc1psqIhhecFm6Em0Kv33cfDpnfoMF1tK Yy/4eLYIR7FmpdbFPcDThFNHbXJzBi00L1mp0XQE2l50h/2bDAAgREdZ+NVo5a7/ RSZjauNU1PxW6pnXMehEh1tyIQmV78jAukaakwaicrpIenMiFUN3fAKHnLuFffA6 t0f3LqJvTDhUw/o2vPgw5e6UDQhA1C+KTv1KXVrhJNo88a3hZqCZ76z3drKR411Q zYgT4DUb8lfnbN+z2wfqT9oM5cegh2k86/mxAA3BYOeQrhmQo/7uhezcgbxtdGZr YlbuaNDTSBrn10ZoaxLPo2dJe2zWxgD6MpvsGU1w3tcRW508qo/+xoWp2/pDzmok +uhOh1NAj9zB05VWBz1r7oBgCOIKpkD/LD4VKq59etsZ/UnrYDwKdXWZp7uhshkU M7N35lUJcR76a852dlMdrgpmY18+BP7+o7M+5ElHTiqQbMuE1nHTg8RgVpdV+tUx dg6GWY/XHf5asm8AEQEAAQAL/A85epOp+GnymmEQfI3+5D178D//Lwu9n86vECB6 xAHCqQtdjZnXpDp/1YUsL59P8nzgYRk7SoMskQDoQ/cB/XFuDOhEdMSgHaTVlnrj ktCCq6rqGnUosyolbb64vIfVaSqd/5SnCStpAsnaBoBYrAu4ZmV4xfjDQWwn0q5s u+r56mD0SkjPgbwk/b3qTVagVmf2OFzUgWwm1e/X+bA1oPag1NV8VS4hZPXswT4f qhiyqUFOgP6vUBcqehkjkIDIl/54xII7/P5tp3LIZawvIXqHKNTqYPCqaCqCj+SL vMYDIb6acjescfZoM71eAeHAANeFZzr/rwfBT+dEP6qKmPXNcvgE11X44ZCr04nT zOV/uDUifEvKT5qgtyJpSFEVr7EXubJPKoNNhoYqq9z1pYU7IedX5BloiVXKOKTY 0pk7JkLqf3g5fYtXh/wol1owemITJy5V5PgaqZvk491LkI6S+kWC7ANYUg+TDPIW afxW3E5N1CYV6XDAl0ZihbLcoQYAy0Ky/p/wayWKePyuPBLwx9O89GSONK2pQljZ yaAgxPQ5/i1vx6LIMg7k/722bXR9W3zOjWOin4eatPM3d2hkG96HFvnBqXSmXOPV 03Xqy1/B5Tj8E9naLKUHE/OBQEc363DgLLG9db5HfPlpAngeppYPdyWkhzXyzkgS PylaE5eW3zkdjEbYJ6RBTecTZEgBaMvJNPdWbn//frpP7kGvyiCg5Es+WjLInUZ6 0sdifcNTCewzLXK80v/y5mVOdJhPBgD5zs9cYdyiQJayqAuOr+He1eMHMVUbm9as qBmPrst398eBW9ZYF7eBfTSlUf6B+WnvyLKEGsUf/7IK0EWDlzoBuWzWiHjUAY1g m9eTV2MnvCCCefqCErWwfFo2nWOasAZA9sKD+ICIBY4tbtvSl4yfLBzTMwSvs9ZS K1ocPSYUnhm2miSWZ8RLZPH7roHQasNHpyq/AX7DahFf2S/bJ+46ZGZ8Pigr7hA+ MjmpQ4qVdb5SaViPmZhAKO+PjuCHm+EF/2H0Y3Sl4eXgxZWoQVOUeXdWg9eMfYrj XDtUMIFppV/QxbeztZKvJdfk64vt/crvLsOp0hOky9cKwY89r4QaHfexU3qR+qDq UlMvR1rHk7dS5HZAtw0xKsFJNkuDxvBkMqv8Los8zp3nUl+U99dfZOArzNkW38wx FPa0ixkC9za2BkDrWEA8vTnxw0A2upIFegDUhwOByrSyfPPnG3tKGeqt3Izb/kDk Q9vmo+HgxBOguMIvlzbBfQZwtbd/gXzlvPqCtCJBbm90aGVyIFRlc3QgVXNlciA8 dGVzdDJAdGVzdC5jb20+iQHOBBMBCAA4AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4B AheAFiEEapM5P1DF5qzT1vtFuTYhLttOFMAFAmDcEeEACgkQuTYhLttOFMDe0Qv/ Qx/bzXztJ3BCc+CYAVDx7Kr37S68etwwLgcWzhG+CDeMB5F/QE+upKgxy2iaqQFR mxfOMgf/TIQkUfkbaASzK1LpnesYO85pk7XYjoN1bYEHiXTkeW+bgB6aJIxrRmO2 SrWasdBC/DsI3Mrya8YMt/TiHC6VpRJVxCe5vv7/kZC4CXrgTBnZocXx/YXimbke poPMVdbvhYh6N0aGeS38jRKgyN10KXmhDTAQDwseVFavBWAjVfx3DEwjtK2Z2GbA aL8JvAwRtqiPFkDMIKPL4UwxtXFws8SpMt6juroUkNyf6+BxNWYqmwXHPy8zCJAb xkxIJMlEc+s7qQsP3fILOo8Xn+dVzJ5sa5AoARoXm1GMjsdqaKAzq99Dic/dHnaQ Civev1PQsdwlYW2C2wNXNeIrxMndbDMFfNuZ6BnGHWJ/wjcp/pFs4YkyyZN8JH7L hP2FO4Jgham3AuP13kC3Ivea7V6hR8QNcDZRwFPOMIX4tXwQv1T72+7DZGaA25O7 nQVXBGBjI0ABDADJMBYIcG0Yil9YxFs7aYzNbd7alUAr89VbY8eIGPHP3INFPM1w lBQCu+4j6xdEbhMpppLBZ9A5TEylP4C6qLtPa+oLtPeuSw8gHDE10XE4lbgPs376 rL60XdImSOHhiduACUefYjqpcmFH9Bim1CC+koArYrSQJQx1Jri+OpnTaL/8UID0 KzD/kEgMVGlHIVj9oJmb4+j9pW8I/g0wDSnIaEKFMxqu6SIVJ1GWj+MUMvZigjLC sNCZd7PnbOC5VeU3SsXj6he74Jx0AmGMPWIHi9M0DjHO5d1cCbXTnud8xxM1bOh4 7aCTnMK5cVyIr+adihgJpVVhrndSM8aklBPRgtozrGNCgF2CkYU2P1blxfloNr/8 UZpM83o+s1aObBszzRNLxnpNORqoLqjfPtLEPQnagxE+4EapCq0NZ/x6yO5VTwwp NljdFAEk40uGuKyn1QA3uNMHy5DlpLl+tU7t1KEovdZ+OVYsYKZhVzw0MTpKogk9 JI7AN0q62ronPskAEQEAAQAL+O8BUSt1ZCVjPSIXIsrR+ZOSkszZwgJ1CWIoh0IH YD2vmcMHGIhFYgBdgerpvhptKhaw7GcXDScEnYkyh5s4GE2hxclik1tbj/x1gYCN 8BNoyeDdPFxQG73qN12D99QYEctpOsz9xPLIDwmL0j1ehAfhwqHIAPm9Ca+i8JYM x/F+35S/jnKDXRI+NVlwbiEyXKXxxIqNlpy9i8sDBGexO5H5Sg0zSN/B1duLekGD biDw6gLc6bCgnS+0JOUpU07Z2fccMOY9ncjKGD2uIb/ePPUaek92GCQyq0eorCIV brcQsRc5sSsNtnRKQTQtxioROeDg7kf2oWySeHTswlXW/219ihrSXgteHJd+rPm7 DYLEeGLRny8bRKv8rQdAtApHaJE4dAATXeY4RYo4NlXHYaztGYtU6kiM/3zCfWAe 9Nn+Wh9jMTZrjefUCagS5r6ZqAh7veNo/vgIGaCLh0a1Ypa0Yk9KFrn3LYEM3zgk 3m3bn+7qgy5cUYXoJ3DGJJEhBgDPonpW0WElqLs5ZMem1ha85SC38F0IkAaSuzuz v3eORiKWuyJGF32Q2XHa1RHQs1JtUKd8rxFer3b8Oq71zLz6JtVc9dmRudvgcJYX 0PC11F6WGjZFSSp39dajFp0A5DKUs39F3w7J1yuDM56TDIN810ywufGAHARY1pZb UJAy/dTqjFnCbNjpAakor3hVzqxcmUG+7Y2X9c2AGncT1MqAQC3M8JZcuZvkK8A9 cMk8B914ryYE7VsZMdMhyTwHmykGAPgNLLa3RDETeGeGCKWI+ZPOoU0ib5JtJZ1d P3tNwfZKuZBZXKW9gqYqyBa/qhMip84SP30pr/TvulcdAFC759HK8sQZyJ6Vw24P c+5ssRxrQUEw1rvJPWhmQCmCOZHBMQl5T6eaTOpR5u3aUKTMlxPKhK9eC1dCSTnI /nyL8An3VKnLy+K/LI42YGphBVLLJmBewuTVDIJviWRdntiG8dElyEJMOywUltk3 2CEmqgsD9tPO8rXZjnMrMn3gfsiaoQYA6/6/e2utkHr7gAoWBgrBBdqVHsvqh5Ro 2DjLAOpZItO/EdCJfDAmbTYOa04535sBDP2tcH/vipPOPpbr1Y9Y/mNsKCulNxed yqAmEkKOcerLUP5UHju0AB6VBjHJFdU2mqT+UjPyBk7WeKXgFomyoYMv3KpNOFWR xi0Xji4kKHbttA6Hy3UcGPr9acyUAlDYeKmxbSUYIPhw32bbGrX9+F5YriTufRsG 3jftQVo9zqdcQSD/5pUTMn3EYbEcohYB2YWJAbYEGAEIACACGwwWIQRqkzk/UMXm rNPW+0W5NiEu204UwAUCYNwR6wAKCRC5NiEu204UwOPnC/92PgB1c3h9FBXH1maz g29fndHIHH65VLgqMiQ7HAMojwRlT5Xnj5tdkCBmszRkv5vMvdJRa3ZY8Ed/Inqr hxBFNzpjqX4oj/RYIQLKXWWfkTKYVLJFZFPCSo00jesw2gieu3Ke/Yy4gwhtNodA v+s6QNMvffTW/K3XNrWDB0E7/LXbdidzhm+MBu8ov2tuC3tp9liLICiE1jv/2xT4 CNSO6yphmk1/1zEYHS/mN9qJ2csBmte2cdmGyOcuVEHk3pyINNMDOamaURBJGRwF XB5V7gTKUFU4jCp3chywKrBHJHxGGDUmPBmZtDtfWAOgL32drK7/KUyzZL/WO7Fj akOI0hRDFOcqTYWL20H7+hAiX3oHMP7eou3L5C7wJ9+JMcACklN/WMjG9a536DFJ 4UgZ6HyKPP+wy837Hbe8b25kNMBwFgiaLR0lcgzxj7NyQWjVCMOEN+M55tRCjvL6 ya6JVZCRbMXfdCy8lVPgtNQ6VlHaj8Wvnn2FLbWWO2n2r3s= =9zU5 -----END PGP PRIVATE KEY BLOCK----- """ NON_DEFAULT_KEY_ID = "6A93393F50C5E6ACD3D6FB45B936212EDB4E14C0" def setUp(self) -> None: super().setUp() self.gpg_dir = os.path.join(self.test_dir, "gpg") os.mkdir(self.gpg_dir, mode=0o700) # Ignore errors when deleting GNUPGHOME, because of race conditions # (e.g. the gpg-agent socket having been deleted). See # https://github.com/jelmer/dulwich/issues/1000 self.addCleanup(shutil.rmtree, self.gpg_dir, ignore_errors=True) self.overrideEnv("GNUPGHOME", self.gpg_dir) def import_default_key(self) -> None: subprocess.run( ["gpg", "--import"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, input=PorcelainGpgTestCase.DEFAULT_KEY, text=True, ) def import_non_default_key(self) -> None: subprocess.run( ["gpg", "--import"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, input=PorcelainGpgTestCase.NON_DEFAULT_KEY, text=True, ) class ArchiveTests(PorcelainTestCase): """Tests for the archive command.""" def test_simple(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"refs/heads/master"] = c3.id out = BytesIO() err = BytesIO() porcelain.archive( self.repo.path, b"refs/heads/master", outstream=out, errstream=err ) self.assertEqual(b"", err.getvalue()) tf = tarfile.TarFile(fileobj=out) self.addCleanup(tf.close) self.assertEqual([], tf.getnames()) class UpdateServerInfoTests(PorcelainTestCase): def test_simple(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"refs/heads/foo"] = c3.id porcelain.update_server_info(self.repo.path) self.assertTrue( os.path.exists(os.path.join(self.repo.controldir(), "info", "refs")) ) class CommitTests(PorcelainTestCase): def test_custom_author(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"refs/heads/foo"] = c3.id sha = porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ", ) self.assertIsInstance(sha, bytes) self.assertEqual(len(sha), 40) def test_unicode(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"refs/heads/foo"] = c3.id sha = porcelain.commit( self.repo.path, message="Some message", author="Joe ", committer="Bob ", ) self.assertIsInstance(sha, bytes) self.assertEqual(len(sha), 40) def test_no_verify(self) -> None: if os.name != "posix": self.skipTest("shell hook tests requires POSIX shell") self.assertTrue(os.path.exists("/bin/sh")) hooks_dir = os.path.join(self.repo.controldir(), "hooks") os.makedirs(hooks_dir, exist_ok=True) self.addCleanup(shutil.rmtree, hooks_dir) c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) hook_fail = "#!/bin/sh\nexit 1" # hooks are executed in pre-commit, commit-msg order # test commit-msg failure first, then pre-commit failure, then # no_verify to skip both hooks commit_msg = os.path.join(hooks_dir, "commit-msg") with open(commit_msg, "w") as f: f.write(hook_fail) os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) with self.assertRaises(CommitError): porcelain.commit( self.repo.path, message="Some message", author="Joe ", committer="Bob ", ) pre_commit = os.path.join(hooks_dir, "pre-commit") with open(pre_commit, "w") as f: f.write(hook_fail) os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) with self.assertRaises(CommitError): porcelain.commit( self.repo.path, message="Some message", author="Joe ", committer="Bob ", ) sha = porcelain.commit( self.repo.path, message="Some message", author="Joe ", committer="Bob ", no_verify=True, ) self.assertIsInstance(sha, bytes) self.assertEqual(len(sha), 40) def test_timezone(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"refs/heads/foo"] = c3.id sha = porcelain.commit( self.repo.path, message="Some message", author="Joe ", author_timezone=18000, committer="Bob ", commit_timezone=18000, ) self.assertIsInstance(sha, bytes) self.assertEqual(len(sha), 40) commit = self.repo.get_object(sha) self.assertEqual(commit._author_timezone, 18000) self.assertEqual(commit._commit_timezone, 18000) self.overrideEnv("GIT_AUTHOR_DATE", "1995-11-20T19:12:08-0501") self.overrideEnv("GIT_COMMITTER_DATE", "1995-11-20T19:12:08-0501") sha = porcelain.commit( self.repo.path, message="Some message", author="Joe ", committer="Bob ", ) self.assertIsInstance(sha, bytes) self.assertEqual(len(sha), 40) commit = self.repo.get_object(sha) self.assertEqual(commit._author_timezone, -18060) self.assertEqual(commit._commit_timezone, -18060) self.overrideEnv("GIT_AUTHOR_DATE", None) self.overrideEnv("GIT_COMMITTER_DATE", None) local_timezone = time.localtime().tm_gmtoff sha = porcelain.commit( self.repo.path, message="Some message", author="Joe ", committer="Bob ", ) self.assertIsInstance(sha, bytes) self.assertEqual(len(sha), 40) commit = self.repo.get_object(sha) self.assertEqual(commit._author_timezone, local_timezone) self.assertEqual(commit._commit_timezone, local_timezone) @skipIf( platform.python_implementation() == "PyPy" or sys.platform == "win32", "gpgme not easily available or supported on Windows and PyPy", ) class CommitSignTests(PorcelainGpgTestCase): def test_default_key(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id cfg = self.repo.get_config() cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID) self.import_default_key() sha = porcelain.commit( self.repo.path, message="Some message", author="Joe ", committer="Bob ", signoff=True, ) self.assertIsInstance(sha, bytes) self.assertEqual(len(sha), 40) commit = self.repo.get_object(sha) # GPG Signatures aren't deterministic, so we can't do a static assertion. commit.verify() commit.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]) self.import_non_default_key() self.assertRaises( gpg.errors.MissingSignatures, commit.verify, keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID], ) commit.committer = b"Alice " self.assertRaises( gpg.errors.BadSignatures, commit.verify, ) def test_non_default_key(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id cfg = self.repo.get_config() cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID) self.import_non_default_key() sha = porcelain.commit( self.repo.path, message="Some message", author="Joe ", committer="Bob ", signoff=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID, ) self.assertIsInstance(sha, bytes) self.assertEqual(len(sha), 40) commit = self.repo.get_object(sha) # GPG Signatures aren't deterministic, so we can't do a static assertion. commit.verify() class TimezoneTests(PorcelainTestCase): def put_envs(self, value) -> None: self.overrideEnv("GIT_AUTHOR_DATE", value) self.overrideEnv("GIT_COMMITTER_DATE", value) def fallback(self, value) -> None: self.put_envs(value) self.assertRaises(porcelain.TimezoneFormatError, porcelain.get_user_timezones) def test_internal_format(self) -> None: self.put_envs("0 +0500") self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones()) def test_rfc_2822(self) -> None: self.put_envs("Mon, 20 Nov 1995 19:12:08 -0500") self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones()) self.put_envs("Mon, 20 Nov 1995 19:12:08") self.assertTupleEqual((0, 0), porcelain.get_user_timezones()) def test_iso8601(self) -> None: self.put_envs("1995-11-20T19:12:08-0501") self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones()) self.put_envs("1995-11-20T19:12:08+0501") self.assertTupleEqual((18060, 18060), porcelain.get_user_timezones()) self.put_envs("1995-11-20T19:12:08-05:01") self.assertTupleEqual((-18060, -18060), porcelain.get_user_timezones()) self.put_envs("1995-11-20 19:12:08-05") self.assertTupleEqual((-18000, -18000), porcelain.get_user_timezones()) # https://github.com/git/git/blob/96b2d4fa927c5055adc5b1d08f10a5d7352e2989/t/t6300-for-each-ref.sh#L128 self.put_envs("2006-07-03 17:18:44 +0200") self.assertTupleEqual((7200, 7200), porcelain.get_user_timezones()) def test_missing_or_malformed(self) -> None: # TODO: add more here self.fallback("0 + 0500") self.fallback("a +0500") self.fallback("1995-11-20T19:12:08") self.fallback("1995-11-20T19:12:08-05:") self.fallback("1995.11.20") self.fallback("11/20/1995") self.fallback("20.11.1995") def test_different_envs(self) -> None: self.overrideEnv("GIT_AUTHOR_DATE", "0 +0500") self.overrideEnv("GIT_COMMITTER_DATE", "0 +0501") self.assertTupleEqual((18000, 18060), porcelain.get_user_timezones()) def test_no_envs(self) -> None: local_timezone = time.localtime().tm_gmtoff self.put_envs("0 +0500") self.assertTupleEqual((18000, 18000), porcelain.get_user_timezones()) self.overrideEnv("GIT_COMMITTER_DATE", None) self.assertTupleEqual((18000, local_timezone), porcelain.get_user_timezones()) self.put_envs("0 +0500") self.overrideEnv("GIT_AUTHOR_DATE", None) self.assertTupleEqual((local_timezone, 18000), porcelain.get_user_timezones()) self.put_envs("0 +0500") self.overrideEnv("GIT_AUTHOR_DATE", None) self.overrideEnv("GIT_COMMITTER_DATE", None) self.assertTupleEqual( (local_timezone, local_timezone), porcelain.get_user_timezones() ) class CleanTests(PorcelainTestCase): def put_files(self, tracked, ignored, untracked, empty_dirs) -> None: """Put the described files in the wd.""" all_files = tracked | ignored | untracked for file_path in all_files: abs_path = os.path.join(self.repo.path, file_path) # File may need to be written in a dir that doesn't exist yet, so # create the parent dir(s) as necessary parent_dir = os.path.dirname(abs_path) try: os.makedirs(parent_dir) except FileExistsError: pass with open(abs_path, "w") as f: f.write("") with open(os.path.join(self.repo.path, ".gitignore"), "w") as f: f.writelines(ignored) for dir_path in empty_dirs: os.mkdir(os.path.join(self.repo.path, "empty_dir")) files_to_add = [os.path.join(self.repo.path, t) for t in tracked] porcelain.add(repo=self.repo.path, paths=files_to_add) porcelain.commit(repo=self.repo.path, message="init commit") def assert_wd(self, expected_paths) -> None: """Assert paths of files and dirs in wd are same as expected_paths.""" control_dir_rel = os.path.relpath(self.repo._controldir, self.repo.path) # normalize paths to simplify comparison across platforms found_paths = { os.path.normpath(p) for p in flat_walk_dir(self.repo.path) if not p.split(os.sep)[0] == control_dir_rel } norm_expected_paths = {os.path.normpath(p) for p in expected_paths} self.assertEqual(found_paths, norm_expected_paths) def test_from_root(self) -> None: self.put_files( tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"}, ignored={"ignored_file"}, untracked={ "untracked_file", "tracked_dir/untracked_dir/untracked_file", "untracked_dir/untracked_dir/untracked_file", }, empty_dirs={"empty_dir"}, ) porcelain.clean(repo=self.repo.path, target_dir=self.repo.path) self.assert_wd( { "tracked_file", "tracked_dir/tracked_file", ".gitignore", "ignored_file", "tracked_dir", } ) def test_from_subdir(self) -> None: self.put_files( tracked={"tracked_file", "tracked_dir/tracked_file", ".gitignore"}, ignored={"ignored_file"}, untracked={ "untracked_file", "tracked_dir/untracked_dir/untracked_file", "untracked_dir/untracked_dir/untracked_file", }, empty_dirs={"empty_dir"}, ) porcelain.clean( repo=self.repo, target_dir=os.path.join(self.repo.path, "untracked_dir"), ) self.assert_wd( { "tracked_file", "tracked_dir/tracked_file", ".gitignore", "ignored_file", "untracked_file", "tracked_dir/untracked_dir/untracked_file", "empty_dir", "untracked_dir", "tracked_dir", "tracked_dir/untracked_dir", } ) class CloneTests(PorcelainTestCase): def test_simple_local(self) -> None: f1_1 = make_object(Blob, data=b"f1") commit_spec = [[1], [2, 1], [3, 1, 2]] trees = { 1: [(b"f1", f1_1), (b"f2", f1_1)], 2: [(b"f1", f1_1), (b"f2", f1_1)], 3: [(b"f1", f1_1), (b"f2", f1_1)], } c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c3.id self.repo.refs[b"refs/tags/foo"] = c3.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) r = porcelain.clone( self.repo.path, target_path, checkout=False, errstream=errstream ) self.addCleanup(r.close) self.assertEqual(r.path, target_path) target_repo = Repo(target_path) self.assertEqual(0, len(target_repo.open_index())) self.assertEqual(c3.id, target_repo.refs[b"refs/tags/foo"]) self.assertNotIn(b"f1", os.listdir(target_path)) self.assertNotIn(b"f2", os.listdir(target_path)) c = r.get_config() encoded_path = self.repo.path if not isinstance(encoded_path, bytes): encoded_path = encoded_path.encode("utf-8") self.assertEqual(encoded_path, c.get((b"remote", b"origin"), b"url")) self.assertEqual( b"+refs/heads/*:refs/remotes/origin/*", c.get((b"remote", b"origin"), b"fetch"), ) def test_simple_local_with_checkout(self) -> None: f1_1 = make_object(Blob, data=b"f1") commit_spec = [[1], [2, 1], [3, 1, 2]] trees = { 1: [(b"f1", f1_1), (b"f2", f1_1)], 2: [(b"f1", f1_1), (b"f2", f1_1)], 3: [(b"f1", f1_1), (b"f2", f1_1)], } c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c3.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) with porcelain.clone( self.repo.path, target_path, checkout=True, errstream=errstream ) as r: self.assertEqual(r.path, target_path) with Repo(target_path) as r: self.assertEqual(r.head(), c3.id) self.assertIn("f1", os.listdir(target_path)) self.assertIn("f2", os.listdir(target_path)) def test_bare_local_with_checkout(self) -> None: f1_1 = make_object(Blob, data=b"f1") commit_spec = [[1], [2, 1], [3, 1, 2]] trees = { 1: [(b"f1", f1_1), (b"f2", f1_1)], 2: [(b"f1", f1_1), (b"f2", f1_1)], 3: [(b"f1", f1_1), (b"f2", f1_1)], } c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c3.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) with porcelain.clone( self.repo.path, target_path, bare=True, errstream=errstream ) as r: self.assertEqual(r.path, target_path) with Repo(target_path) as r: r.head() self.assertRaises(NoIndexPresent, r.open_index) self.assertNotIn(b"f1", os.listdir(target_path)) self.assertNotIn(b"f2", os.listdir(target_path)) def test_no_checkout_with_bare(self) -> None: f1_1 = make_object(Blob, data=b"f1") commit_spec = [[1]] trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]} (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c1.id self.repo.refs[b"HEAD"] = c1.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) self.assertRaises( porcelain.Error, porcelain.clone, self.repo.path, target_path, checkout=True, bare=True, errstream=errstream, ) def test_no_head_no_checkout(self) -> None: f1_1 = make_object(Blob, data=b"f1") commit_spec = [[1]] trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]} (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c1.id target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) errstream = BytesIO() r = porcelain.clone( self.repo.path, target_path, checkout=True, errstream=errstream ) r.close() def test_no_head_no_checkout_outstream_errstream_autofallback(self) -> None: f1_1 = make_object(Blob, data=b"f1") commit_spec = [[1]] trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]} (c1,) = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c1.id target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) errstream = porcelain.NoneStream() r = porcelain.clone( self.repo.path, target_path, checkout=True, errstream=errstream ) r.close() def test_source_broken(self) -> None: with tempfile.TemporaryDirectory() as parent: target_path = os.path.join(parent, "target") self.assertRaises( Exception, porcelain.clone, "/nonexistent/repo", target_path ) self.assertFalse(os.path.exists(target_path)) def test_fetch_symref(self) -> None: f1_1 = make_object(Blob, data=b"f1") trees = {1: [(b"f1", f1_1), (b"f2", f1_1)]} [c1] = build_commit_graph(self.repo.object_store, [[1]], trees) self.repo.refs.set_symbolic_ref(b"HEAD", b"refs/heads/else") self.repo.refs[b"refs/heads/else"] = c1.id target_path = tempfile.mkdtemp() errstream = BytesIO() self.addCleanup(shutil.rmtree, target_path) r = porcelain.clone( self.repo.path, target_path, checkout=False, errstream=errstream ) self.addCleanup(r.close) self.assertEqual(r.path, target_path) target_repo = Repo(target_path) self.assertEqual(0, len(target_repo.open_index())) self.assertEqual(c1.id, target_repo.refs[b"refs/heads/else"]) self.assertEqual(c1.id, target_repo.refs[b"HEAD"]) self.assertEqual( { b"HEAD": b"refs/heads/else", b"refs/remotes/origin/HEAD": b"refs/remotes/origin/else", }, target_repo.refs.get_symrefs(), ) def test_detached_head(self) -> None: f1_1 = make_object(Blob, data=b"f1") commit_spec = [[1], [2, 1], [3, 1, 2]] trees = { 1: [(b"f1", f1_1), (b"f2", f1_1)], 2: [(b"f1", f1_1), (b"f2", f1_1)], 3: [(b"f1", f1_1), (b"f2", f1_1)], } c1, c2, c3 = build_commit_graph(self.repo.object_store, commit_spec, trees) self.repo.refs[b"refs/heads/master"] = c2.id self.repo.refs.remove_if_equals(b"HEAD", None) self.repo.refs[b"HEAD"] = c3.id target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) errstream = porcelain.NoneStream() with porcelain.clone( self.repo.path, target_path, checkout=True, errstream=errstream ) as r: self.assertEqual(c3.id, r.refs[b"HEAD"]) class InitTests(TestCase): def test_non_bare(self) -> None: repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) porcelain.init(repo_dir) def test_bare(self) -> None: repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) porcelain.init(repo_dir, bare=True) class AddTests(PorcelainTestCase): def test_add_default_paths(self) -> None: # create a file for initial commit fullpath = os.path.join(self.repo.path, "blah") with open(fullpath, "w") as f: f.write("\n") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit( repo=self.repo.path, message=b"test", author=b"test ", committer=b"test ", ) # Add a second test file and a file in a directory with open(os.path.join(self.repo.path, "foo"), "w") as f: f.write("\n") os.mkdir(os.path.join(self.repo.path, "adir")) with open(os.path.join(self.repo.path, "adir", "afile"), "w") as f: f.write("\n") cwd = os.getcwd() try: os.chdir(self.repo.path) self.assertEqual({"foo", "blah", "adir", ".git"}, set(os.listdir("."))) self.assertEqual( (["foo", os.path.join("adir", "afile")], set()), porcelain.add(self.repo.path), ) finally: os.chdir(cwd) # Check that foo was added and nothing in .git was modified index = self.repo.open_index() self.assertEqual(sorted(index), [b"adir/afile", b"blah", b"foo"]) def test_add_default_paths_subdir(self) -> None: os.mkdir(os.path.join(self.repo.path, "foo")) with open(os.path.join(self.repo.path, "blah"), "w") as f: f.write("\n") with open(os.path.join(self.repo.path, "foo", "blie"), "w") as f: f.write("\n") cwd = os.getcwd() try: os.chdir(os.path.join(self.repo.path, "foo")) porcelain.add(repo=self.repo.path) porcelain.commit( repo=self.repo.path, message=b"test", author=b"test ", committer=b"test ", ) finally: os.chdir(cwd) index = self.repo.open_index() self.assertEqual(sorted(index), [b"foo/blie"]) def test_add_file(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(self.repo.path, paths=[fullpath]) self.assertIn(b"foo", self.repo.open_index()) def test_add_ignored(self) -> None: with open(os.path.join(self.repo.path, ".gitignore"), "w") as f: f.write("foo\nsubdir/") with open(os.path.join(self.repo.path, "foo"), "w") as f: f.write("BAR") with open(os.path.join(self.repo.path, "bar"), "w") as f: f.write("BAR") os.mkdir(os.path.join(self.repo.path, "subdir")) with open(os.path.join(self.repo.path, "subdir", "baz"), "w") as f: f.write("BAZ") (added, ignored) = porcelain.add( self.repo.path, paths=[ os.path.join(self.repo.path, "foo"), os.path.join(self.repo.path, "bar"), os.path.join(self.repo.path, "subdir"), ], ) self.assertIn(b"bar", self.repo.open_index()) self.assertEqual({"bar"}, set(added)) self.assertEqual({"foo", os.path.join("subdir", "")}, ignored) def test_add_file_absolute_path(self) -> None: # Absolute paths are (not yet) supported with open(os.path.join(self.repo.path, "foo"), "w") as f: f.write("BAR") porcelain.add(self.repo, paths=[os.path.join(self.repo.path, "foo")]) self.assertIn(b"foo", self.repo.open_index()) def test_add_not_in_repo(self) -> None: with open(os.path.join(self.test_dir, "foo"), "w") as f: f.write("BAR") self.assertRaises( ValueError, porcelain.add, self.repo, paths=[os.path.join(self.test_dir, "foo")], ) self.assertRaises( (ValueError, FileNotFoundError), porcelain.add, self.repo, paths=["../foo"], ) self.assertEqual([], list(self.repo.open_index())) def test_add_file_clrf_conversion(self) -> None: # Set the right configuration to the repo c = self.repo.get_config() c.set("core", "autocrlf", "input") c.write_to_path() # Add a file with CRLF line-ending fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "wb") as f: f.write(b"line1\r\nline2") porcelain.add(self.repo.path, paths=[fullpath]) # The line-endings should have been converted to LF index = self.repo.open_index() self.assertIn(b"foo", index) entry = index[b"foo"] blob = self.repo[entry.sha] self.assertEqual(blob.data, b"line1\nline2") class RemoveTests(PorcelainTestCase): def test_remove_file(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(self.repo.path, paths=[fullpath]) porcelain.commit( repo=self.repo, message=b"test", author=b"test ", committer=b"test ", ) self.assertTrue(os.path.exists(os.path.join(self.repo.path, "foo"))) cwd = os.getcwd() try: os.chdir(self.repo.path) porcelain.remove(self.repo.path, paths=["foo"]) finally: os.chdir(cwd) self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo"))) def test_remove_file_staged(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") cwd = os.getcwd() try: os.chdir(self.repo.path) porcelain.add(self.repo.path, paths=[fullpath]) self.assertRaises(Exception, porcelain.rm, self.repo.path, paths=["foo"]) finally: os.chdir(cwd) def test_remove_file_removed_on_disk(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(self.repo.path, paths=[fullpath]) cwd = os.getcwd() try: os.chdir(self.repo.path) os.remove(fullpath) porcelain.remove(self.repo.path, paths=["foo"]) finally: os.chdir(cwd) self.assertFalse(os.path.exists(os.path.join(self.repo.path, "foo"))) class LogTests(PorcelainTestCase): def test_simple(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.log(self.repo.path, outstream=outstream) self.assertEqual(3, outstream.getvalue().count("-" * 50)) def test_max_entries(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.log(self.repo.path, outstream=outstream, max_entries=1) self.assertEqual(1, outstream.getvalue().count("-" * 50)) class ShowTests(PorcelainTestCase): def test_nolist(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.show(self.repo.path, objects=c3.id, outstream=outstream) self.assertTrue(outstream.getvalue().startswith("-" * 50)) def test_simple(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id outstream = StringIO() porcelain.show(self.repo.path, objects=[c3.id], outstream=outstream) self.assertTrue(outstream.getvalue().startswith("-" * 50)) def test_blob(self) -> None: b = Blob.from_string(b"The Foo\n") self.repo.object_store.add_object(b) outstream = StringIO() porcelain.show(self.repo.path, objects=[b.id], outstream=outstream) self.assertEqual(outstream.getvalue(), "The Foo\n") def test_commit_no_parent(self) -> None: a = Blob.from_string(b"The Foo\n") ta = Tree() ta.add(b"somename", 0o100644, a.id) ca = make_commit(tree=ta.id) self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)]) outstream = StringIO() porcelain.show(self.repo.path, objects=[ca.id], outstream=outstream) self.assertMultiLineEqual( outstream.getvalue(), """\ -------------------------------------------------- commit: 344da06c1bb85901270b3e8875c988a027ec087d Author: Test Author Committer: Test Committer Date: Fri Jan 01 2010 00:00:00 +0000 Test message. diff --git a/somename b/somename new file mode 100644 index 0000000..ea5c7bf --- /dev/null +++ b/somename @@ -0,0 +1 @@ +The Foo """, ) def test_tag(self) -> None: a = Blob.from_string(b"The Foo\n") ta = Tree() ta.add(b"somename", 0o100644, a.id) ca = make_commit(tree=ta.id) self.repo.object_store.add_objects([(a, None), (ta, None), (ca, None)]) porcelain.tag_create( self.repo.path, b"tryme", b"foo ", b"bar", annotated=True, objectish=ca.id, tag_time=1552854211, tag_timezone=0, ) outstream = StringIO() porcelain.show(self.repo, objects=[b"refs/tags/tryme"], outstream=outstream) self.maxDiff = None self.assertMultiLineEqual( outstream.getvalue(), """\ Tagger: foo Date: Sun Mar 17 2019 20:23:31 +0000 bar -------------------------------------------------- commit: 344da06c1bb85901270b3e8875c988a027ec087d Author: Test Author Committer: Test Committer Date: Fri Jan 01 2010 00:00:00 +0000 Test message. diff --git a/somename b/somename new file mode 100644 index 0000000..ea5c7bf --- /dev/null +++ b/somename @@ -0,0 +1 @@ +The Foo """, ) def test_commit_with_change(self) -> None: a = Blob.from_string(b"The Foo\n") ta = Tree() ta.add(b"somename", 0o100644, a.id) ca = make_commit(tree=ta.id) b = Blob.from_string(b"The Bar\n") tb = Tree() tb.add(b"somename", 0o100644, b.id) cb = make_commit(tree=tb.id, parents=[ca.id]) self.repo.object_store.add_objects( [ (a, None), (b, None), (ta, None), (tb, None), (ca, None), (cb, None), ] ) outstream = StringIO() porcelain.show(self.repo.path, objects=[cb.id], outstream=outstream) self.assertMultiLineEqual( outstream.getvalue(), """\ -------------------------------------------------- commit: 2c6b6c9cb72c130956657e1fdae58e5b103744fa Author: Test Author Committer: Test Committer Date: Fri Jan 01 2010 00:00:00 +0000 Test message. diff --git a/somename b/somename index ea5c7bf..fd38bcb 100644 --- a/somename +++ b/somename @@ -1 +1 @@ -The Foo +The Bar """, ) class SymbolicRefTests(PorcelainTestCase): def test_set_wrong_symbolic_ref(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id self.assertRaises( porcelain.Error, porcelain.symbolic_ref, self.repo.path, b"foobar" ) def test_set_force_wrong_symbolic_ref(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id porcelain.symbolic_ref(self.repo.path, b"force_foobar", force=True) # test if we actually changed the file with self.repo.get_named_file("HEAD") as f: new_ref = f.read() self.assertEqual(new_ref, b"ref: refs/heads/force_foobar\n") def test_set_symbolic_ref(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id porcelain.symbolic_ref(self.repo.path, b"master") def test_set_symbolic_ref_other_than_master(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]], attrs=dict(refs="develop"), ) self.repo.refs[b"HEAD"] = c3.id self.repo.refs[b"refs/heads/develop"] = c3.id porcelain.symbolic_ref(self.repo.path, b"develop") # test if we actually changed the file with self.repo.get_named_file("HEAD") as f: new_ref = f.read() self.assertEqual(new_ref, b"ref: refs/heads/develop\n") class DiffTreeTests(PorcelainTestCase): def test_empty(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id outstream = BytesIO() porcelain.diff_tree(self.repo.path, c2.tree, c3.tree, outstream=outstream) self.assertEqual(outstream.getvalue(), b"") class CommitTreeTests(PorcelainTestCase): def test_simple(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) b = Blob() b.data = b"foo the bar" t = Tree() t.add(b"somename", 0o100644, b.id) self.repo.object_store.add_object(t) self.repo.object_store.add_object(b) sha = porcelain.commit_tree( self.repo.path, t.id, message=b"Withcommit.", author=b"Joe ", committer=b"Jane ", ) self.assertIsInstance(sha, bytes) self.assertEqual(len(sha), 40) class RevListTests(PorcelainTestCase): def test_simple(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) outstream = BytesIO() porcelain.rev_list(self.repo.path, [c3.id], outstream=outstream) self.assertEqual( c3.id + b"\n" + c2.id + b"\n" + c1.id + b"\n", outstream.getvalue() ) @skipIf( platform.python_implementation() == "PyPy" or sys.platform == "win32", "gpgme not easily available or supported on Windows and PyPy", ) class TagCreateSignTests(PorcelainGpgTestCase): def test_default_key(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id cfg = self.repo.get_config() cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID) self.import_default_key() porcelain.tag_create( self.repo.path, b"tryme", b"foo ", b"bar", annotated=True, sign=True, ) tags = self.repo.refs.as_dict(b"refs/tags") self.assertEqual(list(tags.keys()), [b"tryme"]) tag = self.repo[b"refs/tags/tryme"] self.assertIsInstance(tag, Tag) self.assertEqual(b"foo ", tag.tagger) self.assertEqual(b"bar\n", tag.message) self.assertRecentTimestamp(tag.tag_time) tag = self.repo[b"refs/tags/tryme"] # GPG Signatures aren't deterministic, so we can't do a static assertion. tag.verify() tag.verify(keyids=[PorcelainGpgTestCase.DEFAULT_KEY_ID]) self.import_non_default_key() self.assertRaises( gpg.errors.MissingSignatures, tag.verify, keyids=[PorcelainGpgTestCase.NON_DEFAULT_KEY_ID], ) tag._chunked_text = [b"bad data", tag._signature] self.assertRaises( gpg.errors.BadSignatures, tag.verify, ) def test_non_default_key(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id cfg = self.repo.get_config() cfg.set(("user",), "signingKey", PorcelainGpgTestCase.DEFAULT_KEY_ID) self.import_non_default_key() porcelain.tag_create( self.repo.path, b"tryme", b"foo ", b"bar", annotated=True, sign=PorcelainGpgTestCase.NON_DEFAULT_KEY_ID, ) tags = self.repo.refs.as_dict(b"refs/tags") self.assertEqual(list(tags.keys()), [b"tryme"]) tag = self.repo[b"refs/tags/tryme"] self.assertIsInstance(tag, Tag) self.assertEqual(b"foo ", tag.tagger) self.assertEqual(b"bar\n", tag.message) self.assertRecentTimestamp(tag.tag_time) tag = self.repo[b"refs/tags/tryme"] # GPG Signatures aren't deterministic, so we can't do a static assertion. tag.verify() class TagCreateTests(PorcelainTestCase): def test_annotated(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id porcelain.tag_create( self.repo.path, b"tryme", b"foo ", b"bar", annotated=True, ) tags = self.repo.refs.as_dict(b"refs/tags") self.assertEqual(list(tags.keys()), [b"tryme"]) tag = self.repo[b"refs/tags/tryme"] self.assertIsInstance(tag, Tag) self.assertEqual(b"foo ", tag.tagger) self.assertEqual(b"bar\n", tag.message) self.assertRecentTimestamp(tag.tag_time) def test_unannotated(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id porcelain.tag_create(self.repo.path, b"tryme", annotated=False) tags = self.repo.refs.as_dict(b"refs/tags") self.assertEqual(list(tags.keys()), [b"tryme"]) self.repo[b"refs/tags/tryme"] self.assertEqual(list(tags.values()), [self.repo.head()]) def test_unannotated_unicode(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id porcelain.tag_create(self.repo.path, "tryme", annotated=False) tags = self.repo.refs.as_dict(b"refs/tags") self.assertEqual(list(tags.keys()), [b"tryme"]) self.repo[b"refs/tags/tryme"] self.assertEqual(list(tags.values()), [self.repo.head()]) class TagListTests(PorcelainTestCase): def test_empty(self) -> None: tags = porcelain.tag_list(self.repo.path) self.assertEqual([], tags) def test_simple(self) -> None: self.repo.refs[b"refs/tags/foo"] = b"aa" * 20 self.repo.refs[b"refs/tags/bar/bla"] = b"bb" * 20 tags = porcelain.tag_list(self.repo.path) self.assertEqual([b"bar/bla", b"foo"], tags) class TagDeleteTests(PorcelainTestCase): def test_simple(self) -> None: [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.tag_create(self.repo, b"foo") self.assertIn(b"foo", porcelain.tag_list(self.repo)) porcelain.tag_delete(self.repo, b"foo") self.assertNotIn(b"foo", porcelain.tag_list(self.repo)) class ResetTests(PorcelainTestCase): def test_hard_head(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(self.repo.path, paths=[fullpath]) porcelain.commit( self.repo.path, message=b"Some message", committer=b"Jane ", author=b"John ", ) with open(os.path.join(self.repo.path, "foo"), "wb") as f: f.write(b"OOH") porcelain.reset(self.repo, "hard", b"HEAD") index = self.repo.open_index() changes = list( tree_changes( self.repo, index.commit(self.repo.object_store), self.repo[b"HEAD"].tree, ) ) self.assertEqual([], changes) def test_hard_commit(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(self.repo.path, paths=[fullpath]) sha = porcelain.commit( self.repo.path, message=b"Some message", committer=b"Jane ", author=b"John ", ) with open(fullpath, "wb") as f: f.write(b"BAZ") porcelain.add(self.repo.path, paths=[fullpath]) porcelain.commit( self.repo.path, message=b"Some other message", committer=b"Jane ", author=b"John ", ) porcelain.reset(self.repo, "hard", sha) index = self.repo.open_index() changes = list( tree_changes( self.repo, index.commit(self.repo.object_store), self.repo[sha].tree, ) ) self.assertEqual([], changes) class ResetFileTests(PorcelainTestCase): def test_reset_modify_file_to_commit(self) -> None: file = "foo" full_path = os.path.join(self.repo.path, file) with open(full_path, "w") as f: f.write("hello") porcelain.add(self.repo, paths=[full_path]) sha = porcelain.commit( self.repo, message=b"unitest", committer=b"Jane ", author=b"John ", ) with open(full_path, "a") as f: f.write("something new") porcelain.reset_file(self.repo, file, target=sha) with open(full_path) as f: self.assertEqual("hello", f.read()) def test_reset_remove_file_to_commit(self) -> None: file = "foo" full_path = os.path.join(self.repo.path, file) with open(full_path, "w") as f: f.write("hello") porcelain.add(self.repo, paths=[full_path]) sha = porcelain.commit( self.repo, message=b"unitest", committer=b"Jane ", author=b"John ", ) os.remove(full_path) porcelain.reset_file(self.repo, file, target=sha) with open(full_path) as f: self.assertEqual("hello", f.read()) def test_resetfile_with_dir(self) -> None: os.mkdir(os.path.join(self.repo.path, "new_dir")) full_path = os.path.join(self.repo.path, "new_dir", "foo") with open(full_path, "w") as f: f.write("hello") porcelain.add(self.repo, paths=[full_path]) sha = porcelain.commit( self.repo, message=b"unitest", committer=b"Jane ", author=b"John ", ) with open(full_path, "a") as f: f.write("something new") porcelain.commit( self.repo, message=b"unitest 2", committer=b"Jane ", author=b"John ", ) porcelain.reset_file(self.repo, os.path.join("new_dir", "foo"), target=sha) with open(full_path) as f: self.assertEqual("hello", f.read()) def _commit_file_with_content(repo, filename, content): file_path = os.path.join(repo.path, filename) with open(file_path, "w") as f: f.write(content) porcelain.add(repo, paths=[file_path]) sha = porcelain.commit( repo, message=b"add " + filename.encode(), committer=b"Jane ", author=b"John ", ) return sha, file_path class CheckoutTests(PorcelainTestCase): def setUp(self) -> None: super().setUp() self._sha, self._foo_path = _commit_file_with_content( self.repo, "foo", "hello\n" ) porcelain.branch_create(self.repo, "uni") def test_checkout_to_existing_branch(self) -> None: self.assertEqual(b"master", porcelain.active_branch(self.repo)) porcelain.checkout_branch(self.repo, b"uni") self.assertEqual(b"uni", porcelain.active_branch(self.repo)) def test_checkout_to_non_existing_branch(self) -> None: self.assertEqual(b"master", porcelain.active_branch(self.repo)) with self.assertRaises(KeyError): porcelain.checkout_branch(self.repo, b"bob") self.assertEqual(b"master", porcelain.active_branch(self.repo)) def test_checkout_to_branch_with_modified_files(self) -> None: with open(self._foo_path, "a") as f: f.write("new message\n") porcelain.add(self.repo, paths=[self._foo_path]) status = list(porcelain.status(self.repo)) self.assertEqual( [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status ) # Both branches have file 'foo' checkout should be fine. porcelain.checkout_branch(self.repo, b"uni") self.assertEqual(b"uni", porcelain.active_branch(self.repo)) status = list(porcelain.status(self.repo)) self.assertEqual( [{"add": [], "delete": [], "modify": [b"foo"]}, [], []], status ) def test_checkout_with_deleted_files(self) -> None: porcelain.remove(self.repo.path, [os.path.join(self.repo.path, "foo")]) status = list(porcelain.status(self.repo)) self.assertEqual( [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status ) # Both branches have file 'foo' checkout should be fine. porcelain.checkout_branch(self.repo, b"uni") self.assertEqual(b"uni", porcelain.active_branch(self.repo)) status = list(porcelain.status(self.repo)) self.assertEqual( [{"add": [], "delete": [b"foo"], "modify": []}, [], []], status ) def test_checkout_to_branch_with_added_files(self) -> None: file_path = os.path.join(self.repo.path, "bar") with open(file_path, "w") as f: f.write("bar content\n") porcelain.add(self.repo, paths=[file_path]) status = list(porcelain.status(self.repo)) self.assertEqual( [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status ) # Both branches have file 'foo' checkout should be fine. porcelain.checkout_branch(self.repo, b"uni") self.assertEqual(b"uni", porcelain.active_branch(self.repo)) status = list(porcelain.status(self.repo)) self.assertEqual( [{"add": [b"bar"], "delete": [], "modify": []}, [], []], status ) def test_checkout_to_branch_with_modified_file_not_present(self) -> None: # Commit a new file that the other branch doesn't have. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n") # Modify the file the other branch doesn't have. with open(nee_path, "a") as f: f.write("bar content\n") porcelain.add(self.repo, paths=[nee_path]) status = list(porcelain.status(self.repo)) self.assertEqual( [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status ) # 'uni' branch doesn't have 'nee' and it has been modified, should result in the checkout being aborted. with self.assertRaises(CheckoutError): porcelain.checkout_branch(self.repo, b"uni") self.assertEqual(b"master", porcelain.active_branch(self.repo)) status = list(porcelain.status(self.repo)) self.assertEqual( [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status ) def test_checkout_to_branch_with_modified_file_not_present_forced(self) -> None: # Commit a new file that the other branch doesn't have. _, nee_path = _commit_file_with_content(self.repo, "nee", "Good content\n") # Modify the file the other branch doesn't have. with open(nee_path, "a") as f: f.write("bar content\n") porcelain.add(self.repo, paths=[nee_path]) status = list(porcelain.status(self.repo)) self.assertEqual( [{"add": [], "delete": [], "modify": [b"nee"]}, [], []], status ) # 'uni' branch doesn't have 'nee' and it has been modified, but we force to reset the entire index. porcelain.checkout_branch(self.repo, b"uni", force=True) self.assertEqual(b"uni", porcelain.active_branch(self.repo)) status = list(porcelain.status(self.repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status) def test_checkout_to_branch_with_unstaged_files(self) -> None: # Edit `foo`. with open(self._foo_path, "a") as f: f.write("new message") status = list(porcelain.status(self.repo)) self.assertEqual( [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status ) porcelain.checkout_branch(self.repo, b"uni") status = list(porcelain.status(self.repo)) self.assertEqual( [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status ) def test_checkout_to_branch_with_untracked_files(self) -> None: with open(os.path.join(self.repo.path, "neu"), "a") as f: f.write("new message\n") status = list(porcelain.status(self.repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status) porcelain.checkout_branch(self.repo, b"uni") status = list(porcelain.status(self.repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["neu"]], status) def test_checkout_to_branch_with_new_files(self) -> None: porcelain.checkout_branch(self.repo, b"uni") sub_directory = os.path.join(self.repo.path, "sub1") os.mkdir(sub_directory) for index in range(5): _commit_file_with_content( self.repo, "new_file_" + str(index + 1), "Some content\n" ) _commit_file_with_content( self.repo, os.path.join("sub1", "new_file_" + str(index + 10)), "Good content\n", ) status = list(porcelain.status(self.repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status) porcelain.checkout_branch(self.repo, b"master") self.assertEqual(b"master", porcelain.active_branch(self.repo)) status = list(porcelain.status(self.repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status) porcelain.checkout_branch(self.repo, b"uni") self.assertEqual(b"uni", porcelain.active_branch(self.repo)) status = list(porcelain.status(self.repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status) def test_checkout_to_branch_with_file_in_sub_directory(self) -> None: sub_directory = os.path.join(self.repo.path, "sub1", "sub2") os.makedirs(sub_directory) sub_directory_file = os.path.join(sub_directory, "neu") with open(sub_directory_file, "w") as f: f.write("new message\n") porcelain.add(self.repo, paths=[sub_directory_file]) porcelain.commit( self.repo, message=b"add " + sub_directory_file.encode(), committer=b"Jane ", author=b"John ", ) status = list(porcelain.status(self.repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status) self.assertTrue(os.path.isdir(sub_directory)) self.assertTrue(os.path.isdir(os.path.dirname(sub_directory))) porcelain.checkout_branch(self.repo, b"uni") status = list(porcelain.status(self.repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status) self.assertFalse(os.path.isdir(sub_directory)) self.assertFalse(os.path.isdir(os.path.dirname(sub_directory))) porcelain.checkout_branch(self.repo, b"master") self.assertTrue(os.path.isdir(sub_directory)) self.assertTrue(os.path.isdir(os.path.dirname(sub_directory))) def test_checkout_to_branch_with_multiple_files_in_sub_directory(self) -> None: sub_directory = os.path.join(self.repo.path, "sub1", "sub2") os.makedirs(sub_directory) sub_directory_file_1 = os.path.join(sub_directory, "neu") with open(sub_directory_file_1, "w") as f: f.write("new message\n") sub_directory_file_2 = os.path.join(sub_directory, "gus") with open(sub_directory_file_2, "w") as f: f.write("alternative message\n") porcelain.add(self.repo, paths=[sub_directory_file_1, sub_directory_file_2]) porcelain.commit( self.repo, message=b"add files neu and gus.", committer=b"Jane ", author=b"John ", ) status = list(porcelain.status(self.repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status) self.assertTrue(os.path.isdir(sub_directory)) self.assertTrue(os.path.isdir(os.path.dirname(sub_directory))) porcelain.checkout_branch(self.repo, b"uni") status = list(porcelain.status(self.repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], []], status) self.assertFalse(os.path.isdir(sub_directory)) self.assertFalse(os.path.isdir(os.path.dirname(sub_directory))) def _commit_something_wrong(self): with open(self._foo_path, "a") as f: f.write("something wrong") porcelain.add(self.repo, paths=[self._foo_path]) return porcelain.commit( self.repo, message=b"I may added something wrong", committer=b"Jane ", author=b"John ", ) def test_checkout_to_commit_sha(self) -> None: self._commit_something_wrong() porcelain.checkout_branch(self.repo, self._sha) self.assertEqual(self._sha, self.repo.head()) def test_checkout_to_head(self) -> None: new_sha = self._commit_something_wrong() porcelain.checkout_branch(self.repo, b"HEAD") self.assertEqual(new_sha, self.repo.head()) def _checkout_remote_branch(self): errstream = BytesIO() outstream = BytesIO() porcelain.commit( repo=self.repo.path, message=b"init", author=b"author ", committer=b"committer ", ) # Setup target repo cloned from temp test repo clone_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, clone_path) target_repo = porcelain.clone( self.repo.path, target=clone_path, errstream=errstream ) try: self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"]) finally: target_repo.close() # create a second file to be pushed back to origin handle, fullpath = tempfile.mkstemp(dir=clone_path) os.close(handle) porcelain.add(repo=clone_path, paths=[fullpath]) porcelain.commit( repo=clone_path, message=b"push", author=b"author ", committer=b"committer ", ) # Setup a non-checked out branch in the remote refs_path = b"refs/heads/foo" new_id = self.repo[b"HEAD"].id self.assertNotEqual(new_id, ZERO_SHA) self.repo.refs[refs_path] = new_id # Push to the remote porcelain.push( clone_path, "origin", b"HEAD:" + refs_path, outstream=outstream, errstream=errstream, ) self.assertEqual( target_repo.refs[b"refs/remotes/origin/foo"], target_repo.refs[b"HEAD"], ) porcelain.checkout_branch(target_repo, b"origin/foo") original_id = target_repo[b"HEAD"].id uni_id = target_repo[b"refs/remotes/origin/uni"].id expected_refs = { b"HEAD": original_id, b"refs/heads/master": original_id, b"refs/heads/foo": original_id, b"refs/remotes/origin/foo": original_id, b"refs/remotes/origin/uni": uni_id, b"refs/remotes/origin/HEAD": new_id, b"refs/remotes/origin/master": new_id, } self.assertEqual(expected_refs, target_repo.get_refs()) return target_repo def test_checkout_remote_branch(self) -> None: repo = self._checkout_remote_branch() repo.close() def test_checkout_remote_branch_then_master_then_remote_branch_again(self) -> None: target_repo = self._checkout_remote_branch() self.assertEqual(b"foo", porcelain.active_branch(target_repo)) _commit_file_with_content(target_repo, "bar", "something\n") self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar"))) porcelain.checkout_branch(target_repo, b"master") self.assertEqual(b"master", porcelain.active_branch(target_repo)) self.assertFalse(os.path.isfile(os.path.join(target_repo.path, "bar"))) porcelain.checkout_branch(target_repo, b"origin/foo") self.assertEqual(b"foo", porcelain.active_branch(target_repo)) self.assertTrue(os.path.isfile(os.path.join(target_repo.path, "bar"))) target_repo.close() class SubmoduleTests(PorcelainTestCase): def test_empty(self) -> None: porcelain.commit( repo=self.repo.path, message=b"init", author=b"author ", committer=b"committer ", ) self.assertEqual([], list(porcelain.submodule_list(self.repo))) def test_add(self) -> None: porcelain.submodule_add(self.repo, "../bar.git", "bar") with open(f"{self.repo.path}/.gitmodules") as f: self.assertEqual( """\ [submodule "bar"] \turl = ../bar.git \tpath = bar """, f.read(), ) def test_init(self) -> None: porcelain.submodule_add(self.repo, "../bar.git", "bar") porcelain.submodule_init(self.repo) class PushTests(PorcelainTestCase): def test_simple(self) -> None: """Basic test of porcelain push where self.repo is the remote. First clone the remote, commit a file to the clone, then push the changes back to the remote. """ outstream = BytesIO() errstream = BytesIO() porcelain.commit( repo=self.repo.path, message=b"init", author=b"author ", committer=b"committer ", ) # Setup target repo cloned from temp test repo clone_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, clone_path) target_repo = porcelain.clone( self.repo.path, target=clone_path, errstream=errstream ) try: self.assertEqual(target_repo[b"HEAD"], self.repo[b"HEAD"]) finally: target_repo.close() # create a second file to be pushed back to origin handle, fullpath = tempfile.mkstemp(dir=clone_path) os.close(handle) porcelain.add(repo=clone_path, paths=[fullpath]) porcelain.commit( repo=clone_path, message=b"push", author=b"author ", committer=b"committer ", ) # Setup a non-checked out branch in the remote refs_path = b"refs/heads/foo" new_id = self.repo[b"HEAD"].id self.assertNotEqual(new_id, ZERO_SHA) self.repo.refs[refs_path] = new_id # Push to the remote porcelain.push( clone_path, "origin", b"HEAD:" + refs_path, outstream=outstream, errstream=errstream, ) self.assertEqual( target_repo.refs[b"refs/remotes/origin/foo"], target_repo.refs[b"HEAD"], ) # Check that the target and source with Repo(clone_path) as r_clone: self.assertEqual( { b"HEAD": new_id, b"refs/heads/foo": r_clone[b"HEAD"].id, b"refs/heads/master": new_id, }, self.repo.get_refs(), ) self.assertEqual(r_clone[b"HEAD"].id, self.repo[refs_path].id) # Get the change in the target repo corresponding to the add # this will be in the foo branch. change = next( iter( tree_changes( self.repo, self.repo[b"HEAD"].tree, self.repo[b"refs/heads/foo"].tree, ) ) ) self.assertEqual( os.path.basename(fullpath), change.new.path.decode("ascii") ) def test_local_missing(self) -> None: """Pushing a new branch.""" outstream = BytesIO() errstream = BytesIO() # Setup target repo cloned from temp test repo clone_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, clone_path) target_repo = porcelain.init(clone_path) target_repo.close() self.assertRaises( porcelain.Error, porcelain.push, self.repo, clone_path, b"HEAD:refs/heads/master", outstream=outstream, errstream=errstream, ) def test_new(self) -> None: """Pushing a new branch.""" outstream = BytesIO() errstream = BytesIO() # Setup target repo cloned from temp test repo clone_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, clone_path) target_repo = porcelain.init(clone_path) target_repo.close() # create a second file to be pushed back to origin handle, fullpath = tempfile.mkstemp(dir=clone_path) os.close(handle) porcelain.add(repo=clone_path, paths=[fullpath]) new_id = porcelain.commit( repo=self.repo, message=b"push", author=b"author ", committer=b"committer ", ) # Push to the remote porcelain.push( self.repo, clone_path, b"HEAD:refs/heads/master", outstream=outstream, errstream=errstream, ) with Repo(clone_path) as r_clone: self.assertEqual( { b"HEAD": new_id, b"refs/heads/master": new_id, }, r_clone.get_refs(), ) def test_delete(self) -> None: """Basic test of porcelain push, removing a branch.""" outstream = BytesIO() errstream = BytesIO() porcelain.commit( repo=self.repo.path, message=b"init", author=b"author ", committer=b"committer ", ) # Setup target repo cloned from temp test repo clone_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, clone_path) target_repo = porcelain.clone( self.repo.path, target=clone_path, errstream=errstream ) target_repo.close() # Setup a non-checked out branch in the remote refs_path = b"refs/heads/foo" new_id = self.repo[b"HEAD"].id self.assertNotEqual(new_id, ZERO_SHA) self.repo.refs[refs_path] = new_id # Push to the remote porcelain.push( clone_path, self.repo.path, b":" + refs_path, outstream=outstream, errstream=errstream, ) self.assertEqual( { b"HEAD": new_id, b"refs/heads/master": new_id, }, self.repo.get_refs(), ) def test_diverged(self) -> None: outstream = BytesIO() errstream = BytesIO() porcelain.commit( repo=self.repo.path, message=b"init", author=b"author ", committer=b"committer ", ) # Setup target repo cloned from temp test repo clone_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, clone_path) target_repo = porcelain.clone( self.repo.path, target=clone_path, errstream=errstream ) target_repo.close() remote_id = porcelain.commit( repo=self.repo.path, message=b"remote change", author=b"author ", committer=b"committer ", ) local_id = porcelain.commit( repo=clone_path, message=b"local change", author=b"author ", committer=b"committer ", ) outstream = BytesIO() errstream = BytesIO() # Push to the remote self.assertRaises( porcelain.DivergedBranches, porcelain.push, clone_path, self.repo.path, b"refs/heads/master", outstream=outstream, errstream=errstream, ) self.assertEqual( { b"HEAD": remote_id, b"refs/heads/master": remote_id, }, self.repo.get_refs(), ) self.assertEqual(b"", outstream.getvalue()) self.assertEqual(b"", errstream.getvalue()) outstream = BytesIO() errstream = BytesIO() # Push to the remote with --force porcelain.push( clone_path, self.repo.path, b"refs/heads/master", outstream=outstream, errstream=errstream, force=True, ) self.assertEqual( { b"HEAD": local_id, b"refs/heads/master": local_id, }, self.repo.get_refs(), ) self.assertEqual(b"", outstream.getvalue()) self.assertTrue(re.match(b"Push to .* successful.\n", errstream.getvalue())) class PullTests(PorcelainTestCase): def setUp(self) -> None: super().setUp() # create a file for initial commit handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit( repo=self.repo.path, message=b"test", author=b"test ", committer=b"test ", ) # Setup target repo self.target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.target_path) target_repo = porcelain.clone( self.repo.path, target=self.target_path, errstream=BytesIO() ) target_repo.close() # create a second file to be pushed handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit( repo=self.repo.path, message=b"test2", author=b"test2 ", committer=b"test2 ", ) self.assertIn(b"refs/heads/master", self.repo.refs) self.assertIn(b"refs/heads/master", target_repo.refs) def test_simple(self) -> None: outstream = BytesIO() errstream = BytesIO() # Pull changes into the cloned repo porcelain.pull( self.target_path, self.repo.path, b"refs/heads/master", outstream=outstream, errstream=errstream, ) # Check the target repo for pushed changes with Repo(self.target_path) as r: self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id) def test_diverged(self) -> None: outstream = BytesIO() errstream = BytesIO() c3a = porcelain.commit( repo=self.target_path, message=b"test3a", author=b"test2 ", committer=b"test2 ", ) porcelain.commit( repo=self.repo.path, message=b"test3b", author=b"test2 ", committer=b"test2 ", ) # Pull changes into the cloned repo self.assertRaises( porcelain.DivergedBranches, porcelain.pull, self.target_path, self.repo.path, b"refs/heads/master", outstream=outstream, errstream=errstream, ) # Check the target repo for pushed changes with Repo(self.target_path) as r: self.assertEqual(r[b"refs/heads/master"].id, c3a) self.assertRaises( NotImplementedError, porcelain.pull, self.target_path, self.repo.path, b"refs/heads/master", outstream=outstream, errstream=errstream, fast_forward=False, ) # Check the target repo for pushed changes with Repo(self.target_path) as r: self.assertEqual(r[b"refs/heads/master"].id, c3a) def test_no_refspec(self) -> None: outstream = BytesIO() errstream = BytesIO() # Pull changes into the cloned repo porcelain.pull( self.target_path, self.repo.path, outstream=outstream, errstream=errstream, ) # Check the target repo for pushed changes with Repo(self.target_path) as r: self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id) def test_no_remote_location(self) -> None: outstream = BytesIO() errstream = BytesIO() # Pull changes into the cloned repo porcelain.pull( self.target_path, refspecs=b"refs/heads/master", outstream=outstream, errstream=errstream, ) # Check the target repo for pushed changes with Repo(self.target_path) as r: self.assertEqual(r[b"HEAD"].id, self.repo[b"HEAD"].id) class StatusTests(PorcelainTestCase): def test_empty(self) -> None: results = porcelain.status(self.repo) self.assertEqual({"add": [], "delete": [], "modify": []}, results.staged) self.assertEqual([], results.unstaged) def test_status_base(self) -> None: """Integration test for `status` functionality.""" # Commit a dummy file then modify it fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("origstuff") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) # modify access and modify time of path os.utime(fullpath, (0, 0)) with open(fullpath, "wb") as f: f.write(b"stuff") # Make a dummy file and stage it filename_add = "bar" fullpath = os.path.join(self.repo.path, filename_add) with open(fullpath, "w") as f: f.write("stuff") porcelain.add(repo=self.repo.path, paths=fullpath) results = porcelain.status(self.repo) self.assertEqual(results.staged["add"][0], filename_add.encode("ascii")) self.assertEqual(results.unstaged, [b"foo"]) def test_status_all(self) -> None: del_path = os.path.join(self.repo.path, "foo") mod_path = os.path.join(self.repo.path, "bar") add_path = os.path.join(self.repo.path, "baz") us_path = os.path.join(self.repo.path, "blye") ut_path = os.path.join(self.repo.path, "blyat") with open(del_path, "w") as f: f.write("origstuff") with open(mod_path, "w") as f: f.write("origstuff") with open(us_path, "w") as f: f.write("origstuff") porcelain.add(repo=self.repo.path, paths=[del_path, mod_path, us_path]) porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) porcelain.remove(self.repo.path, [del_path]) with open(add_path, "w") as f: f.write("origstuff") with open(mod_path, "w") as f: f.write("more_origstuff") with open(us_path, "w") as f: f.write("more_origstuff") porcelain.add(repo=self.repo.path, paths=[add_path, mod_path]) with open(us_path, "w") as f: f.write("\norigstuff") with open(ut_path, "w") as f: f.write("origstuff") results = porcelain.status(self.repo.path) self.assertDictEqual( {"add": [b"baz"], "delete": [b"foo"], "modify": [b"bar"]}, results.staged, ) self.assertListEqual(results.unstaged, [b"blye"]) results_no_untracked = porcelain.status(self.repo.path, untracked_files="no") self.assertListEqual(results_no_untracked.untracked, []) def test_status_wrong_untracked_files_value(self) -> None: with self.assertRaises(ValueError): porcelain.status(self.repo.path, untracked_files="antani") def test_status_untracked_path(self) -> None: untracked_dir = os.path.join(self.repo_path, "untracked_dir") os.mkdir(untracked_dir) untracked_file = os.path.join(untracked_dir, "untracked_file") with open(untracked_file, "w") as fh: fh.write("untracked") _, _, untracked = porcelain.status(self.repo.path, untracked_files="all") self.assertEqual(untracked, ["untracked_dir/untracked_file"]) def test_status_crlf_mismatch(self) -> None: # First make a commit as if the file has been added on a Linux system # or with core.autocrlf=True file_path = os.path.join(self.repo.path, "crlf") with open(file_path, "wb") as f: f.write(b"line1\nline2") porcelain.add(repo=self.repo.path, paths=[file_path]) porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) # Then update the file as if it was created by CGit on a Windows # system with core.autocrlf=true with open(file_path, "wb") as f: f.write(b"line1\r\nline2") results = porcelain.status(self.repo) self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged) self.assertListEqual(results.unstaged, [b"crlf"]) self.assertListEqual(results.untracked, []) def test_status_autocrlf_true(self) -> None: # First make a commit as if the file has been added on a Linux system # or with core.autocrlf=True file_path = os.path.join(self.repo.path, "crlf") with open(file_path, "wb") as f: f.write(b"line1\nline2") porcelain.add(repo=self.repo.path, paths=[file_path]) porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) # Then update the file as if it was created by CGit on a Windows # system with core.autocrlf=true with open(file_path, "wb") as f: f.write(b"line1\r\nline2") # TODO: It should be set automatically by looking at the configuration c = self.repo.get_config() c.set("core", "autocrlf", True) c.write_to_path() results = porcelain.status(self.repo) self.assertDictEqual({"add": [], "delete": [], "modify": []}, results.staged) self.assertListEqual(results.unstaged, []) self.assertListEqual(results.untracked, []) def test_status_autocrlf_input(self) -> None: # Commit existing file with CRLF file_path = os.path.join(self.repo.path, "crlf-exists") with open(file_path, "wb") as f: f.write(b"line1\r\nline2") porcelain.add(repo=self.repo.path, paths=[file_path]) porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) c = self.repo.get_config() c.set("core", "autocrlf", "input") c.write_to_path() # Add new (untracked) file file_path = os.path.join(self.repo.path, "crlf-new") with open(file_path, "wb") as f: f.write(b"line1\r\nline2") porcelain.add(repo=self.repo.path, paths=[file_path]) results = porcelain.status(self.repo) self.assertDictEqual( {"add": [b"crlf-new"], "delete": [], "modify": []}, results.staged ) self.assertListEqual(results.unstaged, []) self.assertListEqual(results.untracked, []) def test_get_tree_changes_add(self) -> None: """Unit test for get_tree_changes add.""" # Make a dummy file, stage filename = "bar" fullpath = os.path.join(self.repo.path, filename) with open(fullpath, "w") as f: f.write("stuff") porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) filename = "foo" fullpath = os.path.join(self.repo.path, filename) with open(fullpath, "w") as f: f.write("stuff") porcelain.add(repo=self.repo.path, paths=fullpath) changes = porcelain.get_tree_changes(self.repo.path) self.assertEqual(changes["add"][0], filename.encode("ascii")) self.assertEqual(len(changes["add"]), 1) self.assertEqual(len(changes["modify"]), 0) self.assertEqual(len(changes["delete"]), 0) def test_get_tree_changes_modify(self) -> None: """Unit test for get_tree_changes modify.""" # Make a dummy file, stage, commit, modify filename = "foo" fullpath = os.path.join(self.repo.path, filename) with open(fullpath, "w") as f: f.write("stuff") porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) with open(fullpath, "w") as f: f.write("otherstuff") porcelain.add(repo=self.repo.path, paths=fullpath) changes = porcelain.get_tree_changes(self.repo.path) self.assertEqual(changes["modify"][0], filename.encode("ascii")) self.assertEqual(len(changes["add"]), 0) self.assertEqual(len(changes["modify"]), 1) self.assertEqual(len(changes["delete"]), 0) def test_get_tree_changes_delete(self) -> None: """Unit test for get_tree_changes delete.""" # Make a dummy file, stage, commit, remove filename = "foo" fullpath = os.path.join(self.repo.path, filename) with open(fullpath, "w") as f: f.write("stuff") porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) cwd = os.getcwd() try: os.chdir(self.repo.path) porcelain.remove(repo=self.repo.path, paths=[filename]) finally: os.chdir(cwd) changes = porcelain.get_tree_changes(self.repo.path) self.assertEqual(changes["delete"][0], filename.encode("ascii")) self.assertEqual(len(changes["add"]), 0) self.assertEqual(len(changes["modify"]), 0) self.assertEqual(len(changes["delete"]), 1) def test_get_untracked_paths(self) -> None: with open(os.path.join(self.repo.path, ".gitignore"), "w") as f: f.write("ignored\n") with open(os.path.join(self.repo.path, "ignored"), "w") as f: f.write("blah\n") with open(os.path.join(self.repo.path, "notignored"), "w") as f: f.write("blah\n") os.symlink( os.path.join(self.repo.path, os.pardir, "external_target"), os.path.join(self.repo.path, "link"), ) self.assertEqual( {"ignored", "notignored", ".gitignore", "link"}, set( porcelain.get_untracked_paths( self.repo.path, self.repo.path, self.repo.open_index() ) ), ) self.assertEqual( {".gitignore", "notignored", "link"}, set(porcelain.status(self.repo).untracked), ) self.assertEqual( {".gitignore", "notignored", "ignored", "link"}, set(porcelain.status(self.repo, ignored=True).untracked), ) def test_get_untracked_paths_subrepo(self) -> None: with open(os.path.join(self.repo.path, ".gitignore"), "w") as f: f.write("nested/\n") with open(os.path.join(self.repo.path, "notignored"), "w") as f: f.write("blah\n") subrepo = Repo.init(os.path.join(self.repo.path, "nested"), mkdir=True) with open(os.path.join(subrepo.path, "ignored"), "w") as f: f.write("bleep\n") with open(os.path.join(subrepo.path, "with"), "w") as f: f.write("bloop\n") with open(os.path.join(subrepo.path, "manager"), "w") as f: f.write("blop\n") self.assertEqual( {".gitignore", "notignored", os.path.join("nested", "")}, set( porcelain.get_untracked_paths( self.repo.path, self.repo.path, self.repo.open_index() ) ), ) self.assertEqual( {".gitignore", "notignored"}, set( porcelain.get_untracked_paths( self.repo.path, self.repo.path, self.repo.open_index(), exclude_ignored=True, ) ), ) self.assertEqual( {"ignored", "with", "manager"}, set( porcelain.get_untracked_paths( subrepo.path, subrepo.path, subrepo.open_index() ) ), ) self.assertEqual( set(), set( porcelain.get_untracked_paths( subrepo.path, self.repo.path, self.repo.open_index(), ) ), ) self.assertEqual( { os.path.join("nested", "ignored"), os.path.join("nested", "with"), os.path.join("nested", "manager"), }, set( porcelain.get_untracked_paths( self.repo.path, subrepo.path, self.repo.open_index(), ) ), ) def test_get_untracked_paths_subdir(self) -> None: with open(os.path.join(self.repo.path, ".gitignore"), "w") as f: f.write("subdir/\nignored") with open(os.path.join(self.repo.path, "notignored"), "w") as f: f.write("blah\n") os.mkdir(os.path.join(self.repo.path, "subdir")) with open(os.path.join(self.repo.path, "ignored"), "w") as f: f.write("foo") with open(os.path.join(self.repo.path, "subdir", "ignored"), "w") as f: f.write("foo") self.assertEqual( { ".gitignore", "notignored", "ignored", os.path.join("subdir", ""), }, set( porcelain.get_untracked_paths( self.repo.path, self.repo.path, self.repo.open_index(), ) ), ) self.assertEqual( {".gitignore", "notignored"}, set( porcelain.get_untracked_paths( self.repo.path, self.repo.path, self.repo.open_index(), exclude_ignored=True, ) ), ) def test_get_untracked_paths_invalid_untracked_files(self) -> None: with self.assertRaises(ValueError): list( porcelain.get_untracked_paths( self.repo.path, self.repo.path, self.repo.open_index(), untracked_files="invalid_value", ) ) def test_get_untracked_paths_normal(self) -> None: with self.assertRaises(NotImplementedError): _, _, _ = porcelain.status(repo=self.repo.path, untracked_files="normal") # TODO(jelmer): Add test for dulwich.porcelain.daemon class UploadPackTests(PorcelainTestCase): """Tests for upload_pack.""" def test_upload_pack(self) -> None: outf = BytesIO() exitcode = porcelain.upload_pack(self.repo.path, BytesIO(b"0000"), outf) outlines = outf.getvalue().splitlines() self.assertEqual([b"0000"], outlines) self.assertEqual(0, exitcode) class ReceivePackTests(PorcelainTestCase): """Tests for receive_pack.""" def test_receive_pack(self) -> None: filename = "foo" fullpath = os.path.join(self.repo.path, filename) with open(fullpath, "w") as f: f.write("stuff") porcelain.add(repo=self.repo.path, paths=fullpath) self.repo.do_commit( message=b"test status", author=b"author ", committer=b"committer ", author_timestamp=1402354300, commit_timestamp=1402354300, author_timezone=0, commit_timezone=0, ) outf = BytesIO() exitcode = porcelain.receive_pack(self.repo.path, BytesIO(b"0000"), outf) outlines = outf.getvalue().splitlines() self.assertEqual( [ b"0091319b56ce3aee2d489f759736a79cc552c9bb86d9 HEAD\x00 report-status " b"delete-refs quiet ofs-delta side-band-64k " b"no-done symref=HEAD:refs/heads/master", b"003f319b56ce3aee2d489f759736a79cc552c9bb86d9 refs/heads/master", b"0000", ], outlines, ) self.assertEqual(0, exitcode) class BranchListTests(PorcelainTestCase): def test_standard(self) -> None: self.assertEqual(set(), set(porcelain.branch_list(self.repo))) def test_new_branch(self) -> None: [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b"foo") self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo))) class BranchCreateTests(PorcelainTestCase): def test_branch_exists(self) -> None: [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b"foo") self.assertRaises(porcelain.Error, porcelain.branch_create, self.repo, b"foo") porcelain.branch_create(self.repo, b"foo", force=True) def test_new_branch(self) -> None: [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b"foo") self.assertEqual({b"master", b"foo"}, set(porcelain.branch_list(self.repo))) class BranchDeleteTests(PorcelainTestCase): def test_simple(self) -> None: [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, b"foo") self.assertIn(b"foo", porcelain.branch_list(self.repo)) porcelain.branch_delete(self.repo, b"foo") self.assertNotIn(b"foo", porcelain.branch_list(self.repo)) def test_simple_unicode(self) -> None: [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo[b"HEAD"] = c1.id porcelain.branch_create(self.repo, "foo") self.assertIn(b"foo", porcelain.branch_list(self.repo)) porcelain.branch_delete(self.repo, "foo") self.assertNotIn(b"foo", porcelain.branch_list(self.repo)) class FetchTests(PorcelainTestCase): def test_simple(self) -> None: outstream = BytesIO() errstream = BytesIO() # create a file for initial commit handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit( repo=self.repo.path, message=b"test", author=b"test ", committer=b"test ", ) # Setup target repo target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) target_repo = porcelain.clone( self.repo.path, target=target_path, errstream=errstream ) # create a second file to be pushed handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit( repo=self.repo.path, message=b"test2", author=b"test2 ", committer=b"test2 ", ) self.assertNotIn(self.repo[b"HEAD"].id, target_repo) target_repo.close() # Fetch changes into the cloned repo porcelain.fetch(target_path, "origin", outstream=outstream, errstream=errstream) # Assert that fetch updated the local image of the remote self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs()) # Check the target repo for pushed changes with Repo(target_path) as r: self.assertIn(self.repo[b"HEAD"].id, r) def test_with_remote_name(self) -> None: remote_name = "origin" outstream = BytesIO() errstream = BytesIO() # create a file for initial commit handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit( repo=self.repo.path, message=b"test", author=b"test ", committer=b"test ", ) # Setup target repo target_path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, target_path) target_repo = porcelain.clone( self.repo.path, target=target_path, errstream=errstream ) # Capture current refs target_refs = target_repo.get_refs() # create a second file to be pushed handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.commit( repo=self.repo.path, message=b"test2", author=b"test2 ", committer=b"test2 ", ) self.assertNotIn(self.repo[b"HEAD"].id, target_repo) target_config = target_repo.get_config() target_config.set( (b"remote", remote_name.encode()), b"url", self.repo.path.encode() ) target_repo.close() # Fetch changes into the cloned repo porcelain.fetch( target_path, remote_name, outstream=outstream, errstream=errstream ) # Assert that fetch updated the local image of the remote self.assert_correct_remote_refs(target_repo.get_refs(), self.repo.get_refs()) # Check the target repo for pushed changes, as well as updates # for the refs with Repo(target_path) as r: self.assertIn(self.repo[b"HEAD"].id, r) self.assertNotEqual(self.repo.get_refs(), target_refs) def assert_correct_remote_refs( self, local_refs, remote_refs, remote_name=b"origin" ) -> None: """Assert that known remote refs corresponds to actual remote refs.""" local_ref_prefix = b"refs/heads" remote_ref_prefix = b"refs/remotes/" + remote_name locally_known_remote_refs = { k[len(remote_ref_prefix) + 1 :]: v for k, v in local_refs.items() if k.startswith(remote_ref_prefix) } normalized_remote_refs = { k[len(local_ref_prefix) + 1 :]: v for k, v in remote_refs.items() if k.startswith(local_ref_prefix) } if b"HEAD" in locally_known_remote_refs and b"HEAD" in remote_refs: normalized_remote_refs[b"HEAD"] = remote_refs[b"HEAD"] self.assertEqual(locally_known_remote_refs, normalized_remote_refs) class RepackTests(PorcelainTestCase): def test_empty(self) -> None: porcelain.repack(self.repo) def test_simple(self) -> None: handle, fullpath = tempfile.mkstemp(dir=self.repo.path) os.close(handle) porcelain.add(repo=self.repo.path, paths=fullpath) porcelain.repack(self.repo) class LsTreeTests(PorcelainTestCase): def test_empty(self) -> None: porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) f = StringIO() porcelain.ls_tree(self.repo, b"HEAD", outstream=f) self.assertEqual(f.getvalue(), "") def test_simple(self) -> None: # Commit a dummy file then modify it fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("origstuff") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) f = StringIO() porcelain.ls_tree(self.repo, b"HEAD", outstream=f) self.assertEqual( f.getvalue(), "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tfoo\n", ) def test_recursive(self) -> None: # Create a directory then write a dummy file in it dirpath = os.path.join(self.repo.path, "adir") filepath = os.path.join(dirpath, "afile") os.mkdir(dirpath) with open(filepath, "w") as f: f.write("origstuff") porcelain.add(repo=self.repo.path, paths=[filepath]) porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) f = StringIO() porcelain.ls_tree(self.repo, b"HEAD", outstream=f) self.assertEqual( f.getvalue(), "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n", ) f = StringIO() porcelain.ls_tree(self.repo, b"HEAD", outstream=f, recursive=True) self.assertEqual( f.getvalue(), "40000 tree b145cc69a5e17693e24d8a7be0016ed8075de66d\tadir\n" "100644 blob 8b82634d7eae019850bb883f06abf428c58bc9aa\tadir" "/afile\n", ) class LsRemoteTests(PorcelainTestCase): def test_empty(self) -> None: self.assertEqual({}, porcelain.ls_remote(self.repo.path)) def test_some(self) -> None: cid = porcelain.commit( repo=self.repo.path, message=b"test status", author=b"author ", committer=b"committer ", ) self.assertEqual( {b"refs/heads/master": cid, b"HEAD": cid}, porcelain.ls_remote(self.repo.path), ) class LsFilesTests(PorcelainTestCase): def test_empty(self) -> None: self.assertEqual([], list(porcelain.ls_files(self.repo))) def test_simple(self) -> None: # Commit a dummy file then modify it fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("origstuff") porcelain.add(repo=self.repo.path, paths=[fullpath]) self.assertEqual([b"foo"], list(porcelain.ls_files(self.repo))) class RemoteAddTests(PorcelainTestCase): def test_new(self) -> None: porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich") c = self.repo.get_config() self.assertEqual( c.get((b"remote", b"jelmer"), b"url"), b"git://jelmer.uk/code/dulwich", ) def test_exists(self) -> None: porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich") self.assertRaises( porcelain.RemoteExists, porcelain.remote_add, self.repo, "jelmer", "git://jelmer.uk/code/dulwich", ) class RemoteRemoveTests(PorcelainTestCase): def test_remove(self) -> None: porcelain.remote_add(self.repo, "jelmer", "git://jelmer.uk/code/dulwich") c = self.repo.get_config() self.assertEqual( c.get((b"remote", b"jelmer"), b"url"), b"git://jelmer.uk/code/dulwich", ) porcelain.remote_remove(self.repo, "jelmer") self.assertRaises(KeyError, porcelain.remote_remove, self.repo, "jelmer") c = self.repo.get_config() self.assertRaises(KeyError, c.get, (b"remote", b"jelmer"), b"url") class CheckIgnoreTests(PorcelainTestCase): def test_check_ignored(self) -> None: with open(os.path.join(self.repo.path, ".gitignore"), "w") as f: f.write("foo") foo_path = os.path.join(self.repo.path, "foo") with open(foo_path, "w") as f: f.write("BAR") bar_path = os.path.join(self.repo.path, "bar") with open(bar_path, "w") as f: f.write("BAR") self.assertEqual(["foo"], list(porcelain.check_ignore(self.repo, [foo_path]))) self.assertEqual([], list(porcelain.check_ignore(self.repo, [bar_path]))) def test_check_added_abs(self) -> None: path = os.path.join(self.repo.path, "foo") with open(path, "w") as f: f.write("BAR") self.repo.stage(["foo"]) with open(os.path.join(self.repo.path, ".gitignore"), "w") as f: f.write("foo\n") self.assertEqual([], list(porcelain.check_ignore(self.repo, [path]))) self.assertEqual( ["foo"], list(porcelain.check_ignore(self.repo, [path], no_index=True)), ) def test_check_added_rel(self) -> None: with open(os.path.join(self.repo.path, "foo"), "w") as f: f.write("BAR") self.repo.stage(["foo"]) with open(os.path.join(self.repo.path, ".gitignore"), "w") as f: f.write("foo\n") cwd = os.getcwd() os.mkdir(os.path.join(self.repo.path, "bar")) os.chdir(os.path.join(self.repo.path, "bar")) try: self.assertEqual(list(porcelain.check_ignore(self.repo, ["../foo"])), []) self.assertEqual( ["../foo"], list(porcelain.check_ignore(self.repo, ["../foo"], no_index=True)), ) finally: os.chdir(cwd) class UpdateHeadTests(PorcelainTestCase): def test_set_to_branch(self) -> None: [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo.refs[b"refs/heads/blah"] = c1.id porcelain.update_head(self.repo, "blah") self.assertEqual(c1.id, self.repo.head()) self.assertEqual(b"ref: refs/heads/blah", self.repo.refs.read_ref(b"HEAD")) def test_set_to_branch_detached(self) -> None: [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo.refs[b"refs/heads/blah"] = c1.id porcelain.update_head(self.repo, "blah", detached=True) self.assertEqual(c1.id, self.repo.head()) self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD")) def test_set_to_commit_detached(self) -> None: [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo.refs[b"refs/heads/blah"] = c1.id porcelain.update_head(self.repo, c1.id, detached=True) self.assertEqual(c1.id, self.repo.head()) self.assertEqual(c1.id, self.repo.refs.read_ref(b"HEAD")) def test_set_new_branch(self) -> None: [c1] = build_commit_graph(self.repo.object_store, [[1]]) self.repo.refs[b"refs/heads/blah"] = c1.id porcelain.update_head(self.repo, "blah", new_branch="bar") self.assertEqual(c1.id, self.repo.head()) self.assertEqual(b"ref: refs/heads/bar", self.repo.refs.read_ref(b"HEAD")) class MailmapTests(PorcelainTestCase): def test_no_mailmap(self) -> None: self.assertEqual( b"Jelmer Vernooij ", porcelain.check_mailmap(self.repo, b"Jelmer Vernooij "), ) def test_mailmap_lookup(self) -> None: with open(os.path.join(self.repo.path, ".mailmap"), "wb") as f: f.write( b"""\ Jelmer Vernooij """ ) self.assertEqual( b"Jelmer Vernooij ", porcelain.check_mailmap(self.repo, b"Jelmer Vernooij "), ) class FsckTests(PorcelainTestCase): def test_none(self) -> None: self.assertEqual([], list(porcelain.fsck(self.repo))) def test_git_dir(self) -> None: obj = Tree() a = Blob() a.data = b"foo" obj.add(b".git", 0o100644, a.id) self.repo.object_store.add_objects([(a, None), (obj, None)]) self.assertEqual( [(obj.id, "invalid name .git")], [(sha, str(e)) for (sha, e) in porcelain.fsck(self.repo)], ) class DescribeTests(PorcelainTestCase): def test_no_commits(self) -> None: self.assertRaises(KeyError, porcelain.describe, self.repo.path) def test_single_commit(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) sha = porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ", ) self.assertEqual( "g{}".format(sha[:7].decode("ascii")), porcelain.describe(self.repo.path), ) def test_tag(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ", ) porcelain.tag_create( self.repo.path, b"tryme", b"foo ", b"bar", annotated=True, ) self.assertEqual("tryme", porcelain.describe(self.repo.path)) def test_tag_and_commit(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ", ) porcelain.tag_create( self.repo.path, b"tryme", b"foo ", b"bar", annotated=True, ) with open(fullpath, "w") as f: f.write("BAR2") porcelain.add(repo=self.repo.path, paths=[fullpath]) sha = porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ", ) self.assertEqual( "tryme-1-g{}".format(sha[:7].decode("ascii")), porcelain.describe(self.repo.path), ) def test_tag_and_commit_full(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ", ) porcelain.tag_create( self.repo.path, b"tryme", b"foo ", b"bar", annotated=True, ) with open(fullpath, "w") as f: f.write("BAR2") porcelain.add(repo=self.repo.path, paths=[fullpath]) sha = porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ", ) self.assertEqual( "tryme-1-g{}".format(sha.decode("ascii")), porcelain.describe(self.repo.path, abbrev=40), ) class PathToTreeTests(PorcelainTestCase): def setUp(self) -> None: super().setUp() self.fp = os.path.join(self.test_dir, "bar") with open(self.fp, "w") as f: f.write("something") oldcwd = os.getcwd() self.addCleanup(os.chdir, oldcwd) os.chdir(self.test_dir) def test_path_to_tree_path_base(self) -> None: self.assertEqual(b"bar", porcelain.path_to_tree_path(self.test_dir, self.fp)) self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar")) self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "bar")) cwd = os.getcwd() self.assertEqual( b"bar", porcelain.path_to_tree_path(".", os.path.join(cwd, "bar")) ) self.assertEqual(b"bar", porcelain.path_to_tree_path(cwd, "bar")) def test_path_to_tree_path_syntax(self) -> None: self.assertEqual(b"bar", porcelain.path_to_tree_path(".", "./bar")) def test_path_to_tree_path_error(self) -> None: with self.assertRaises(ValueError): with tempfile.TemporaryDirectory() as od: porcelain.path_to_tree_path(od, self.fp) def test_path_to_tree_path_rel(self) -> None: cwd = os.getcwd() os.mkdir(os.path.join(self.repo.path, "foo")) os.mkdir(os.path.join(self.repo.path, "foo/bar")) try: os.chdir(os.path.join(self.repo.path, "foo/bar")) with open("baz", "w") as f: f.write("contents") self.assertEqual(b"bar/baz", porcelain.path_to_tree_path("..", "baz")) self.assertEqual( b"bar/baz", porcelain.path_to_tree_path( os.path.join(os.getcwd(), ".."), os.path.join(os.getcwd(), "baz"), ), ) self.assertEqual( b"bar/baz", porcelain.path_to_tree_path("..", os.path.join(os.getcwd(), "baz")), ) self.assertEqual( b"bar/baz", porcelain.path_to_tree_path(os.path.join(os.getcwd(), ".."), "baz"), ) finally: os.chdir(cwd) class GetObjectByPathTests(PorcelainTestCase): def test_simple(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ", ) self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data) self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data) def test_encoding(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) porcelain.commit( self.repo.path, message=b"Some message", author=b"Joe ", committer=b"Bob ", encoding=b"utf-8", ) self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, "foo").data) self.assertEqual(b"BAR", porcelain.get_object_by_path(self.repo, b"foo").data) def test_missing(self) -> None: self.assertRaises(KeyError, porcelain.get_object_by_path, self.repo, "foo") class WriteTreeTests(PorcelainTestCase): def test_simple(self) -> None: fullpath = os.path.join(self.repo.path, "foo") with open(fullpath, "w") as f: f.write("BAR") porcelain.add(repo=self.repo.path, paths=[fullpath]) self.assertEqual( b"d2092c8a9f311f0311083bf8d177f2ca0ab5b241", porcelain.write_tree(self.repo), ) class ActiveBranchTests(PorcelainTestCase): def test_simple(self) -> None: self.assertEqual(b"master", porcelain.active_branch(self.repo)) class FindUniqueAbbrevTests(PorcelainTestCase): def test_simple(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id self.assertEqual( c1.id.decode("ascii")[:7], porcelain.find_unique_abbrev(self.repo.object_store, c1.id), ) class PackRefsTests(PorcelainTestCase): def test_all(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id self.repo.refs[b"refs/heads/master"] = c2.id self.repo.refs[b"refs/tags/foo"] = c1.id porcelain.pack_refs(self.repo, all=True) self.assertEqual( self.repo.refs.get_packed_refs(), { b"refs/heads/master": c2.id, b"refs/tags/foo": c1.id, }, ) def test_not_all(self) -> None: c1, c2, c3 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2]] ) self.repo.refs[b"HEAD"] = c3.id self.repo.refs[b"refs/heads/master"] = c2.id self.repo.refs[b"refs/tags/foo"] = c1.id porcelain.pack_refs(self.repo) self.assertEqual( self.repo.refs.get_packed_refs(), { b"refs/tags/foo": c1.id, }, ) class ServerTests(PorcelainTestCase): @contextlib.contextmanager def _serving(self): with make_server("localhost", 0, self.app) as server: thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() try: yield f"http://localhost:{server.server_port}" finally: server.shutdown() thread.join(10) def setUp(self) -> None: super().setUp() self.served_repo_path = os.path.join(self.test_dir, "served_repo.git") self.served_repo = Repo.init_bare(self.served_repo_path, mkdir=True) self.addCleanup(self.served_repo.close) backend = DictBackend({"/": self.served_repo}) self.app = make_wsgi_chain(backend) def test_pull(self) -> None: (c1,) = build_commit_graph(self.served_repo.object_store, [[1]]) self.served_repo.refs[b"refs/heads/master"] = c1.id with self._serving() as url: porcelain.pull(self.repo, url, "master") def test_push(self) -> None: (c1,) = build_commit_graph(self.repo.object_store, [[1]]) self.repo.refs[b"refs/heads/master"] = c1.id with self._serving() as url: porcelain.push(self.repo, url, "master") class ForEachTests(PorcelainTestCase): def setUp(self) -> None: super().setUp() c1, c2, c3, c4 = build_commit_graph( self.repo.object_store, [[1], [2, 1], [3, 1, 2], [4]] ) porcelain.tag_create( self.repo.path, b"v0.1", objectish=c1.id, annotated=True, message=b"0.1", ) porcelain.tag_create( self.repo.path, b"v1.0", objectish=c2.id, annotated=True, message=b"1.0", ) porcelain.tag_create(self.repo.path, b"simple-tag", objectish=c3.id) porcelain.tag_create( self.repo.path, b"v1.1", objectish=c4.id, annotated=True, message=b"1.1", ) porcelain.branch_create( self.repo.path, b"feat", objectish=c2.id.decode("ascii") ) self.repo.refs[b"HEAD"] = c4.id def test_for_each_ref(self) -> None: refs = porcelain.for_each_ref(self.repo) self.assertEqual( [(object_type, tag) for _, object_type, tag in refs], [ (b"commit", b"refs/heads/feat"), (b"commit", b"refs/heads/master"), (b"commit", b"refs/tags/simple-tag"), (b"tag", b"refs/tags/v0.1"), (b"tag", b"refs/tags/v1.0"), (b"tag", b"refs/tags/v1.1"), ], ) def test_for_each_ref_pattern(self) -> None: versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v*") self.assertEqual( [(object_type, tag) for _, object_type, tag in versions], [ (b"tag", b"refs/tags/v0.1"), (b"tag", b"refs/tags/v1.0"), (b"tag", b"refs/tags/v1.1"), ], ) versions = porcelain.for_each_ref(self.repo, pattern="refs/tags/v1.?") self.assertEqual( [(object_type, tag) for _, object_type, tag in versions], [ (b"tag", b"refs/tags/v1.0"), (b"tag", b"refs/tags/v1.1"), ], ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_protocol.py0000644000175100002000000002774014731042555017265 0ustar00runnerdocker# test_protocol.py -- Tests for the git protocol # Copyright (C) 2009 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for the smart protocol utility functions.""" from io import BytesIO from dulwich.errors import HangupException from dulwich.protocol import ( MULTI_ACK, MULTI_ACK_DETAILED, SINGLE_ACK, BufferedPktLineWriter, GitProtocolError, PktLineParser, Protocol, ReceivableProtocol, ack_type, extract_capabilities, extract_want_line_capabilities, filter_ref_prefix, pkt_line, pkt_seq, ) from . import TestCase class PktLineTests(TestCase): def test_pkt_line(self) -> None: self.assertEqual(b"0007bla", pkt_line(b"bla")) self.assertEqual(b"0000", pkt_line(None)) def test_pkt_seq(self) -> None: self.assertEqual(b"0007bla0007foo0000", pkt_seq(b"bla", b"foo")) self.assertEqual(b"0000", pkt_seq()) class FilterRefPrefixTests(TestCase): def test_filter_ref_prefix(self) -> None: self.assertEqual( {b"refs/heads/foo": b"0123456789", b"refs/heads/bar": b"0123456789"}, filter_ref_prefix( { b"refs/heads/foo": b"0123456789", b"refs/heads/bar": b"0123456789", b"refs/tags/bar": b"0123456789", }, [b"refs/heads/"], ), ) class BaseProtocolTests: def test_write_pkt_line_none(self) -> None: self.proto.write_pkt_line(None) self.assertEqual(self.rout.getvalue(), b"0000") def test_write_pkt_line(self) -> None: self.proto.write_pkt_line(b"bla") self.assertEqual(self.rout.getvalue(), b"0007bla") def test_read_pkt_line(self) -> None: self.rin.write(b"0008cmd ") self.rin.seek(0) self.assertEqual(b"cmd ", self.proto.read_pkt_line()) def test_eof(self) -> None: self.rin.write(b"0000") self.rin.seek(0) self.assertFalse(self.proto.eof()) self.assertEqual(None, self.proto.read_pkt_line()) self.assertTrue(self.proto.eof()) self.assertRaises(HangupException, self.proto.read_pkt_line) def test_unread_pkt_line(self) -> None: self.rin.write(b"0007foo0000") self.rin.seek(0) self.assertEqual(b"foo", self.proto.read_pkt_line()) self.proto.unread_pkt_line(b"bar") self.assertEqual(b"bar", self.proto.read_pkt_line()) self.assertEqual(None, self.proto.read_pkt_line()) self.proto.unread_pkt_line(b"baz1") self.assertRaises(ValueError, self.proto.unread_pkt_line, b"baz2") def test_read_pkt_seq(self) -> None: self.rin.write(b"0008cmd 0005l0000") self.rin.seek(0) self.assertEqual([b"cmd ", b"l"], list(self.proto.read_pkt_seq())) def test_read_pkt_line_none(self) -> None: self.rin.write(b"0000") self.rin.seek(0) self.assertEqual(None, self.proto.read_pkt_line()) def test_read_pkt_line_wrong_size(self) -> None: self.rin.write(b"0100too short") self.rin.seek(0) self.assertRaises(GitProtocolError, self.proto.read_pkt_line) def test_write_sideband(self) -> None: self.proto.write_sideband(3, b"bloe") self.assertEqual(self.rout.getvalue(), b"0009\x03bloe") def test_send_cmd(self) -> None: self.proto.send_cmd(b"fetch", b"a", b"b") self.assertEqual(self.rout.getvalue(), b"000efetch a\x00b\x00") def test_read_cmd(self) -> None: self.rin.write(b"0012cmd arg1\x00arg2\x00") self.rin.seek(0) self.assertEqual((b"cmd", [b"arg1", b"arg2"]), self.proto.read_cmd()) def test_read_cmd_noend0(self) -> None: self.rin.write(b"0011cmd arg1\x00arg2") self.rin.seek(0) self.assertRaises(AssertionError, self.proto.read_cmd) class ProtocolTests(BaseProtocolTests, TestCase): def setUp(self) -> None: TestCase.setUp(self) self.rout = BytesIO() self.rin = BytesIO() self.proto = Protocol(self.rin.read, self.rout.write) class ReceivableBytesIO(BytesIO): """BytesIO with socket-like recv semantics for testing.""" def __init__(self) -> None: BytesIO.__init__(self) self.allow_read_past_eof = False def recv(self, size): # fail fast if no bytes are available; in a real socket, this would # block forever if self.tell() == len(self.getvalue()) and not self.allow_read_past_eof: raise GitProtocolError("Blocking read past end of socket") if size == 1: return self.read(1) # calls shouldn't return quite as much as asked for return self.read(size - 1) class ReceivableProtocolTests(BaseProtocolTests, TestCase): def setUp(self) -> None: TestCase.setUp(self) self.rout = BytesIO() self.rin = ReceivableBytesIO() self.proto = ReceivableProtocol(self.rin.recv, self.rout.write) self.proto._rbufsize = 8 def test_eof(self) -> None: # Allow blocking reads past EOF just for this test. The only parts of # the protocol that might check for EOF do not depend on the recv() # semantics anyway. self.rin.allow_read_past_eof = True BaseProtocolTests.test_eof(self) def test_recv(self) -> None: all_data = b"1234567" * 10 # not a multiple of bufsize self.rin.write(all_data) self.rin.seek(0) data = b"" # We ask for 8 bytes each time and actually read 7, so it should take # exactly 10 iterations. for _ in range(10): data += self.proto.recv(10) # any more reads would block self.assertRaises(GitProtocolError, self.proto.recv, 10) self.assertEqual(all_data, data) def test_recv_read(self) -> None: all_data = b"1234567" # recv exactly in one call self.rin.write(all_data) self.rin.seek(0) self.assertEqual(b"1234", self.proto.recv(4)) self.assertEqual(b"567", self.proto.read(3)) self.assertRaises(GitProtocolError, self.proto.recv, 10) def test_read_recv(self) -> None: all_data = b"12345678abcdefg" self.rin.write(all_data) self.rin.seek(0) self.assertEqual(b"1234", self.proto.read(4)) self.assertEqual(b"5678abc", self.proto.recv(8)) self.assertEqual(b"defg", self.proto.read(4)) self.assertRaises(GitProtocolError, self.proto.recv, 10) def test_mixed(self) -> None: # arbitrary non-repeating string all_data = b",".join(str(i).encode("ascii") for i in range(100)) self.rin.write(all_data) self.rin.seek(0) data = b"" for i in range(1, 100): data += self.proto.recv(i) # if we get to the end, do a non-blocking read instead of blocking if len(data) + i > len(all_data): data += self.proto.recv(i) # ReceivableBytesIO leaves off the last byte unless we ask # nicely data += self.proto.recv(1) break else: data += self.proto.read(i) else: # didn't break, something must have gone wrong self.fail() self.assertEqual(all_data, data) class CapabilitiesTestCase(TestCase): def test_plain(self) -> None: self.assertEqual((b"bla", []), extract_capabilities(b"bla")) def test_caps(self) -> None: self.assertEqual((b"bla", [b"la"]), extract_capabilities(b"bla\0la")) self.assertEqual((b"bla", [b"la"]), extract_capabilities(b"bla\0la\n")) self.assertEqual((b"bla", [b"la", b"la"]), extract_capabilities(b"bla\0la la")) def test_plain_want_line(self) -> None: self.assertEqual((b"want bla", []), extract_want_line_capabilities(b"want bla")) def test_caps_want_line(self) -> None: self.assertEqual( (b"want bla", [b"la"]), extract_want_line_capabilities(b"want bla la"), ) self.assertEqual( (b"want bla", [b"la"]), extract_want_line_capabilities(b"want bla la\n"), ) self.assertEqual( (b"want bla", [b"la", b"la"]), extract_want_line_capabilities(b"want bla la la"), ) def test_ack_type(self) -> None: self.assertEqual(SINGLE_ACK, ack_type([b"foo", b"bar"])) self.assertEqual(MULTI_ACK, ack_type([b"foo", b"bar", b"multi_ack"])) self.assertEqual( MULTI_ACK_DETAILED, ack_type([b"foo", b"bar", b"multi_ack_detailed"]), ) # choose detailed when both present self.assertEqual( MULTI_ACK_DETAILED, ack_type([b"foo", b"bar", b"multi_ack", b"multi_ack_detailed"]), ) class BufferedPktLineWriterTests(TestCase): def setUp(self) -> None: TestCase.setUp(self) self._output = BytesIO() self._writer = BufferedPktLineWriter(self._output.write, bufsize=16) def assertOutputEquals(self, expected) -> None: self.assertEqual(expected, self._output.getvalue()) def _truncate(self) -> None: self._output.seek(0) self._output.truncate() def test_write(self) -> None: self._writer.write(b"foo") self.assertOutputEquals(b"") self._writer.flush() self.assertOutputEquals(b"0007foo") def test_write_none(self) -> None: self._writer.write(None) self.assertOutputEquals(b"") self._writer.flush() self.assertOutputEquals(b"0000") def test_flush_empty(self) -> None: self._writer.flush() self.assertOutputEquals(b"") def test_write_multiple(self) -> None: self._writer.write(b"foo") self._writer.write(b"bar") self.assertOutputEquals(b"") self._writer.flush() self.assertOutputEquals(b"0007foo0007bar") def test_write_across_boundary(self) -> None: self._writer.write(b"foo") self._writer.write(b"barbaz") self.assertOutputEquals(b"0007foo000abarba") self._truncate() self._writer.flush() self.assertOutputEquals(b"z") def test_write_to_boundary(self) -> None: self._writer.write(b"foo") self._writer.write(b"barba") self.assertOutputEquals(b"0007foo0009barba") self._truncate() self._writer.write(b"z") self._writer.flush() self.assertOutputEquals(b"0005z") class PktLineParserTests(TestCase): def test_none(self) -> None: pktlines = [] parser = PktLineParser(pktlines.append) parser.parse(b"0000") self.assertEqual(pktlines, [None]) self.assertEqual(b"", parser.get_tail()) def test_small_fragments(self) -> None: pktlines = [] parser = PktLineParser(pktlines.append) parser.parse(b"00") parser.parse(b"05") parser.parse(b"z0000") self.assertEqual(pktlines, [b"z", None]) self.assertEqual(b"", parser.get_tail()) def test_multiple_packets(self) -> None: pktlines = [] parser = PktLineParser(pktlines.append) parser.parse(b"0005z0006aba") self.assertEqual(pktlines, [b"z", b"ab"]) self.assertEqual(b"a", parser.get_tail()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_reflog.py0000644000175100002000000001210114731042555016663 0ustar00runnerdocker# test_reflog.py -- tests for reflog.py # Copyright (C) 2015 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for dulwich.reflog.""" from io import BytesIO from dulwich.objects import ZERO_SHA from dulwich.reflog import ( drop_reflog_entry, format_reflog_line, parse_reflog_line, read_reflog, ) from . import TestCase class ReflogLineTests(TestCase): def test_format(self) -> None: self.assertEqual( b"0000000000000000000000000000000000000000 " b"49030649db3dfec5a9bc03e5dde4255a14499f16 Jelmer Vernooij " b" 1446552482 +0000 " b"clone: from git://jelmer.uk/samba", format_reflog_line( b"0000000000000000000000000000000000000000", b"49030649db3dfec5a9bc03e5dde4255a14499f16", b"Jelmer Vernooij ", 1446552482, 0, b"clone: from git://jelmer.uk/samba", ), ) self.assertEqual( b"0000000000000000000000000000000000000000 " b"49030649db3dfec5a9bc03e5dde4255a14499f16 Jelmer Vernooij " b" 1446552482 +0000 " b"clone: from git://jelmer.uk/samba", format_reflog_line( None, b"49030649db3dfec5a9bc03e5dde4255a14499f16", b"Jelmer Vernooij ", 1446552482, 0, b"clone: from git://jelmer.uk/samba", ), ) def test_parse(self) -> None: reflog_line = ( b"0000000000000000000000000000000000000000 " b"49030649db3dfec5a9bc03e5dde4255a14499f16 Jelmer Vernooij " b" 1446552482 +0000 " b"clone: from git://jelmer.uk/samba" ) self.assertEqual( ( b"0000000000000000000000000000000000000000", b"49030649db3dfec5a9bc03e5dde4255a14499f16", b"Jelmer Vernooij ", 1446552482, 0, b"clone: from git://jelmer.uk/samba", ), parse_reflog_line(reflog_line), ) _TEST_REFLOG = ( b"0000000000000000000000000000000000000000 " b"49030649db3dfec5a9bc03e5dde4255a14499f16 Jelmer Vernooij " b" 1446552482 +0000 " b"clone: from git://jelmer.uk/samba\n" b"49030649db3dfec5a9bc03e5dde4255a14499f16 " b"42d06bd4b77fed026b154d16493e5deab78f02ec Jelmer Vernooij " b" 1446552483 +0000 " b"clone: from git://jelmer.uk/samba\n" b"42d06bd4b77fed026b154d16493e5deab78f02ec " b"df6800012397fb85c56e7418dd4eb9405dee075c Jelmer Vernooij " b" 1446552484 +0000 " b"clone: from git://jelmer.uk/samba\n" ) class ReflogDropTests(TestCase): def setUp(self) -> None: TestCase.setUp(self) self.f = BytesIO(_TEST_REFLOG) self.original_log = list(read_reflog(self.f)) self.f.seek(0) def _read_log(self): self.f.seek(0) return list(read_reflog(self.f)) def test_invalid(self) -> None: self.assertRaises(ValueError, drop_reflog_entry, self.f, -1) def test_drop_entry(self) -> None: drop_reflog_entry(self.f, 0) log = self._read_log() self.assertEqual(len(log), 2) self.assertEqual(self.original_log[0:2], log) self.f.seek(0) drop_reflog_entry(self.f, 1) log = self._read_log() self.assertEqual(len(log), 1) self.assertEqual(self.original_log[1], log[0]) def test_drop_entry_with_rewrite(self) -> None: drop_reflog_entry(self.f, 1, True) log = self._read_log() self.assertEqual(len(log), 2) self.assertEqual(self.original_log[0], log[0]) self.assertEqual(self.original_log[0].new_sha, log[1].old_sha) self.assertEqual(self.original_log[2].new_sha, log[1].new_sha) self.f.seek(0) drop_reflog_entry(self.f, 1, True) log = self._read_log() self.assertEqual(len(log), 1) self.assertEqual(ZERO_SHA, log[0].old_sha) self.assertEqual(self.original_log[2].new_sha, log[0].new_sha) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_refs.py0000644000175100002000000007603114731042555016360 0ustar00runnerdocker# test_refs.py -- tests for refs.py # Copyright (C) 2013 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for dulwich.refs.""" import os import sys import tempfile from io import BytesIO from typing import ClassVar from dulwich import errors from dulwich.file import GitFile from dulwich.objects import ZERO_SHA from dulwich.refs import ( DictRefsContainer, InfoRefsContainer, SymrefLoop, _split_ref_line, check_ref_format, parse_symref_value, read_packed_refs, read_packed_refs_with_peeled, split_peeled_refs, strip_peeled_refs, write_packed_refs, ) from dulwich.repo import Repo from dulwich.tests.utils import open_repo, tear_down_repo from . import SkipTest, TestCase class CheckRefFormatTests(TestCase): """Tests for the check_ref_format function. These are the same tests as in the git test suite. """ def test_valid(self) -> None: self.assertTrue(check_ref_format(b"heads/foo")) self.assertTrue(check_ref_format(b"foo/bar/baz")) self.assertTrue(check_ref_format(b"refs///heads/foo")) self.assertTrue(check_ref_format(b"foo./bar")) self.assertTrue(check_ref_format(b"heads/foo@bar")) self.assertTrue(check_ref_format(b"heads/fix.lock.error")) def test_invalid(self) -> None: self.assertFalse(check_ref_format(b"foo")) self.assertFalse(check_ref_format(b"heads/foo/")) self.assertFalse(check_ref_format(b"./foo")) self.assertFalse(check_ref_format(b".refs/foo")) self.assertFalse(check_ref_format(b"heads/foo..bar")) self.assertFalse(check_ref_format(b"heads/foo?bar")) self.assertFalse(check_ref_format(b"heads/foo.lock")) self.assertFalse(check_ref_format(b"heads/v@{ation")) self.assertFalse(check_ref_format(b"heads/foo\bar")) ONES = b"1" * 40 TWOS = b"2" * 40 THREES = b"3" * 40 FOURS = b"4" * 40 class PackedRefsFileTests(TestCase): def test_split_ref_line_errors(self) -> None: self.assertRaises(errors.PackedRefsException, _split_ref_line, b"singlefield") self.assertRaises(errors.PackedRefsException, _split_ref_line, b"badsha name") self.assertRaises( errors.PackedRefsException, _split_ref_line, ONES + b" bad/../refname", ) def test_read_without_peeled(self) -> None: f = BytesIO(b"\n".join([b"# comment", ONES + b" ref/1", TWOS + b" ref/2"])) self.assertEqual( [(ONES, b"ref/1"), (TWOS, b"ref/2")], list(read_packed_refs(f)) ) def test_read_without_peeled_errors(self) -> None: f = BytesIO(b"\n".join([ONES + b" ref/1", b"^" + TWOS])) self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f)) def test_read_with_peeled(self) -> None: f = BytesIO( b"\n".join( [ ONES + b" ref/1", TWOS + b" ref/2", b"^" + THREES, FOURS + b" ref/4", ] ) ) self.assertEqual( [ (ONES, b"ref/1", None), (TWOS, b"ref/2", THREES), (FOURS, b"ref/4", None), ], list(read_packed_refs_with_peeled(f)), ) def test_read_with_peeled_errors(self) -> None: f = BytesIO(b"\n".join([b"^" + TWOS, ONES + b" ref/1"])) self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f)) f = BytesIO(b"\n".join([ONES + b" ref/1", b"^" + TWOS, b"^" + THREES])) self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f)) def test_write_with_peeled(self) -> None: f = BytesIO() write_packed_refs(f, {b"ref/1": ONES, b"ref/2": TWOS}, {b"ref/1": THREES}) self.assertEqual( b"\n".join( [ b"# pack-refs with: peeled", ONES + b" ref/1", b"^" + THREES, TWOS + b" ref/2", ] ) + b"\n", f.getvalue(), ) def test_write_without_peeled(self) -> None: f = BytesIO() write_packed_refs(f, {b"ref/1": ONES, b"ref/2": TWOS}) self.assertEqual( b"\n".join([ONES + b" ref/1", TWOS + b" ref/2"]) + b"\n", f.getvalue(), ) # Dict of refs that we expect all RefsContainerTests subclasses to define. _TEST_REFS = { b"HEAD": b"42d06bd4b77fed026b154d16493e5deab78f02ec", b"refs/heads/40-char-ref-aaaaaaaaaaaaaaaaaa": b"42d06bd4b77fed026b154d16493e5deab78f02ec", b"refs/heads/master": b"42d06bd4b77fed026b154d16493e5deab78f02ec", b"refs/heads/packed": b"42d06bd4b77fed026b154d16493e5deab78f02ec", b"refs/tags/refs-0.1": b"df6800012397fb85c56e7418dd4eb9405dee075c", b"refs/tags/refs-0.2": b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8", b"refs/heads/loop": b"ref: refs/heads/loop", } class RefsContainerTests: def test_keys(self) -> None: actual_keys = set(self._refs.keys()) self.assertEqual(set(self._refs.allkeys()), actual_keys) self.assertEqual(set(_TEST_REFS.keys()), actual_keys) actual_keys = self._refs.keys(b"refs/heads") actual_keys.discard(b"loop") self.assertEqual( [b"40-char-ref-aaaaaaaaaaaaaaaaaa", b"master", b"packed"], sorted(actual_keys), ) self.assertEqual( [b"refs-0.1", b"refs-0.2"], sorted(self._refs.keys(b"refs/tags")) ) def test_iter(self) -> None: actual_keys = set(self._refs.keys()) self.assertEqual(set(self._refs), actual_keys) self.assertEqual(set(_TEST_REFS.keys()), actual_keys) def test_as_dict(self) -> None: # refs/heads/loop does not show up even if it exists expected_refs = dict(_TEST_REFS) del expected_refs[b"refs/heads/loop"] self.assertEqual(expected_refs, self._refs.as_dict()) def test_get_symrefs(self) -> None: self._refs.set_symbolic_ref(b"refs/heads/src", b"refs/heads/dst") symrefs = self._refs.get_symrefs() if b"HEAD" in symrefs: symrefs.pop(b"HEAD") self.assertEqual( { b"refs/heads/src": b"refs/heads/dst", b"refs/heads/loop": b"refs/heads/loop", }, symrefs, ) def test_setitem(self) -> None: self._refs[b"refs/some/ref"] = b"42d06bd4b77fed026b154d16493e5deab78f02ec" self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"refs/some/ref"], ) # should accept symref self._refs[b"refs/heads/symbolic"] = b"ref: refs/heads/master" self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"refs/heads/symbolic"], ) # should not accept bad ref names self.assertRaises( errors.RefFormatError, self._refs.__setitem__, b"notrefs/foo", b"42d06bd4b77fed026b154d16493e5deab78f02ec", ) # should not accept short sha self.assertRaises( ValueError, self._refs.__setitem__, b"refs/some/ref", b"42d06bd", ) def test_set_if_equals(self) -> None: nines = b"9" * 40 self.assertFalse(self._refs.set_if_equals(b"HEAD", b"c0ffee", nines)) self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"HEAD"] ) self.assertTrue( self._refs.set_if_equals( b"HEAD", b"42d06bd4b77fed026b154d16493e5deab78f02ec", nines ) ) self.assertEqual(nines, self._refs[b"HEAD"]) # Setting the ref again is a no-op, but will return True. self.assertTrue(self._refs.set_if_equals(b"HEAD", nines, nines)) self.assertEqual(nines, self._refs[b"HEAD"]) self.assertTrue(self._refs.set_if_equals(b"refs/heads/master", None, nines)) self.assertEqual(nines, self._refs[b"refs/heads/master"]) self.assertTrue( self._refs.set_if_equals(b"refs/heads/nonexistent", ZERO_SHA, nines) ) self.assertEqual(nines, self._refs[b"refs/heads/nonexistent"]) def test_add_if_new(self) -> None: nines = b"9" * 40 self.assertFalse(self._refs.add_if_new(b"refs/heads/master", nines)) self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"refs/heads/master"], ) self.assertTrue(self._refs.add_if_new(b"refs/some/ref", nines)) self.assertEqual(nines, self._refs[b"refs/some/ref"]) def test_set_symbolic_ref(self) -> None: self._refs.set_symbolic_ref(b"refs/heads/symbolic", b"refs/heads/master") self.assertEqual( b"ref: refs/heads/master", self._refs.read_loose_ref(b"refs/heads/symbolic"), ) self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"refs/heads/symbolic"], ) def test_set_symbolic_ref_overwrite(self) -> None: nines = b"9" * 40 self.assertNotIn(b"refs/heads/symbolic", self._refs) self._refs[b"refs/heads/symbolic"] = nines self.assertEqual(nines, self._refs.read_loose_ref(b"refs/heads/symbolic")) self._refs.set_symbolic_ref(b"refs/heads/symbolic", b"refs/heads/master") self.assertEqual( b"ref: refs/heads/master", self._refs.read_loose_ref(b"refs/heads/symbolic"), ) self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"refs/heads/symbolic"], ) def test_check_refname(self) -> None: self._refs._check_refname(b"HEAD") self._refs._check_refname(b"refs/stash") self._refs._check_refname(b"refs/heads/foo") self.assertRaises(errors.RefFormatError, self._refs._check_refname, b"refs") self.assertRaises( errors.RefFormatError, self._refs._check_refname, b"notrefs/foo" ) def test_contains(self) -> None: self.assertIn(b"refs/heads/master", self._refs) self.assertNotIn(b"refs/heads/bar", self._refs) def test_delitem(self) -> None: self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"refs/heads/master"], ) del self._refs[b"refs/heads/master"] self.assertRaises(KeyError, lambda: self._refs[b"refs/heads/master"]) def test_remove_if_equals(self) -> None: self.assertFalse(self._refs.remove_if_equals(b"HEAD", b"c0ffee")) self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"HEAD"] ) self.assertTrue( self._refs.remove_if_equals( b"refs/tags/refs-0.2", b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8", ) ) self.assertTrue(self._refs.remove_if_equals(b"refs/tags/refs-0.2", ZERO_SHA)) self.assertNotIn(b"refs/tags/refs-0.2", self._refs) def test_import_refs_name(self) -> None: self._refs[b"refs/remotes/origin/other"] = ( b"48d01bd4b77fed026b154d16493e5deab78f02ec" ) self._refs.import_refs( b"refs/remotes/origin", {b"master": b"42d06bd4b77fed026b154d16493e5deab78f02ec"}, ) self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"refs/remotes/origin/master"], ) self.assertEqual( b"48d01bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"refs/remotes/origin/other"], ) def test_import_refs_name_prune(self) -> None: self._refs[b"refs/remotes/origin/other"] = ( b"48d01bd4b77fed026b154d16493e5deab78f02ec" ) self._refs.import_refs( b"refs/remotes/origin", {b"master": b"42d06bd4b77fed026b154d16493e5deab78f02ec"}, prune=True, ) self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"refs/remotes/origin/master"], ) self.assertNotIn(b"refs/remotes/origin/other", self._refs) class DictRefsContainerTests(RefsContainerTests, TestCase): def setUp(self) -> None: TestCase.setUp(self) self._refs = DictRefsContainer(dict(_TEST_REFS)) def test_invalid_refname(self) -> None: # FIXME: Move this test into RefsContainerTests, but requires # some way of injecting invalid refs. self._refs._refs[b"refs/stash"] = b"00" * 20 expected_refs = dict(_TEST_REFS) del expected_refs[b"refs/heads/loop"] expected_refs[b"refs/stash"] = b"00" * 20 self.assertEqual(expected_refs, self._refs.as_dict()) class DiskRefsContainerTests(RefsContainerTests, TestCase): def setUp(self) -> None: TestCase.setUp(self) self._repo = open_repo("refs.git") self.addCleanup(tear_down_repo, self._repo) self._refs = self._repo.refs def test_get_packed_refs(self) -> None: self.assertEqual( { b"refs/heads/packed": b"42d06bd4b77fed026b154d16493e5deab78f02ec", b"refs/tags/refs-0.1": b"df6800012397fb85c56e7418dd4eb9405dee075c", }, self._refs.get_packed_refs(), ) def test_get_peeled_not_packed(self) -> None: # not packed self.assertEqual(None, self._refs.get_peeled(b"refs/tags/refs-0.2")) self.assertEqual( b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8", self._refs[b"refs/tags/refs-0.2"], ) # packed, known not peelable self.assertEqual( self._refs[b"refs/heads/packed"], self._refs.get_peeled(b"refs/heads/packed"), ) # packed, peeled self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs.get_peeled(b"refs/tags/refs-0.1"), ) def test_setitem(self) -> None: RefsContainerTests.test_setitem(self) path = os.path.join(self._refs.path, b"refs", b"some", b"ref") with open(path, "rb") as f: self.assertEqual(b"42d06bd4b77fed026b154d16493e5deab78f02ec", f.read()[:40]) self.assertRaises( OSError, self._refs.__setitem__, b"refs/some/ref/sub", b"42d06bd4b77fed026b154d16493e5deab78f02ec", ) def test_delete_refs_container(self) -> None: # We shouldn't delete the refs directory self._refs[b"refs/heads/blah"] = b"42d06bd4b77fed026b154d16493e5deab78f02ec" for ref in self._refs.allkeys(): del self._refs[ref] self.assertTrue(os.path.exists(os.path.join(self._refs.path, b"refs"))) def test_setitem_packed(self) -> None: with open(os.path.join(self._refs.path, b"packed-refs"), "w") as f: f.write("# pack-refs with: peeled fully-peeled sorted \n") f.write("42d06bd4b77fed026b154d16493e5deab78f02ec refs/heads/packed\n") # It's allowed to set a new ref on a packed ref, the new ref will be # placed outside on refs/ self._refs[b"refs/heads/packed"] = b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8" packed_ref_path = os.path.join(self._refs.path, b"refs", b"heads", b"packed") with open(packed_ref_path, "rb") as f: self.assertEqual(b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8", f.read()[:40]) self.assertRaises( OSError, self._refs.__setitem__, b"refs/heads/packed/sub", b"42d06bd4b77fed026b154d16493e5deab78f02ec", ) # this shouldn't overwrite the packed refs self.assertEqual( {b"refs/heads/packed": b"42d06bd4b77fed026b154d16493e5deab78f02ec"}, self._refs.get_packed_refs(), ) def test_add_packed_refs(self) -> None: # first, create a non-packed ref self._refs[b"refs/heads/packed"] = b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8" packed_ref_path = os.path.join(self._refs.path, b"refs", b"heads", b"packed") self.assertTrue(os.path.exists(packed_ref_path)) # now overwrite that with a packed ref packed_refs_file_path = os.path.join(self._refs.path, b"packed-refs") self._refs.add_packed_refs( { b"refs/heads/packed": b"42d06bd4b77fed026b154d16493e5deab78f02ec", } ) # that should kill the file self.assertFalse(os.path.exists(packed_ref_path)) # now delete the packed ref self._refs.add_packed_refs( { b"refs/heads/packed": None, } ) # and it's gone! self.assertFalse(os.path.exists(packed_ref_path)) self.assertRaises( KeyError, self._refs.__getitem__, b"refs/heads/packed", ) # just in case, make sure we can't pack HEAD self.assertRaises( ValueError, self._refs.add_packed_refs, {b"HEAD": "02ac81614bcdbd585a37b4b0edf8cb8a"}, ) # delete all packed refs self._refs.add_packed_refs({ref: None for ref in self._refs.get_packed_refs()}) self.assertEqual({}, self._refs.get_packed_refs()) # remove the packed ref file, and check that adding nothing doesn't affect that os.remove(packed_refs_file_path) # adding nothing doesn't make it reappear self._refs.add_packed_refs({}) self.assertFalse(os.path.exists(packed_refs_file_path)) def test_setitem_symbolic(self) -> None: ones = b"1" * 40 self._refs[b"HEAD"] = ones self.assertEqual(ones, self._refs[b"HEAD"]) # ensure HEAD was not modified f = open(os.path.join(self._refs.path, b"HEAD"), "rb") v = next(iter(f)).rstrip(b"\n\r") f.close() self.assertEqual(b"ref: refs/heads/master", v) # ensure the symbolic link was written through f = open(os.path.join(self._refs.path, b"refs", b"heads", b"master"), "rb") self.assertEqual(ones, f.read()[:40]) f.close() def test_set_if_equals(self) -> None: RefsContainerTests.test_set_if_equals(self) # ensure symref was followed self.assertEqual(b"9" * 40, self._refs[b"refs/heads/master"]) # ensure lockfile was deleted self.assertFalse( os.path.exists( os.path.join(self._refs.path, b"refs", b"heads", b"master.lock") ) ) self.assertFalse(os.path.exists(os.path.join(self._refs.path, b"HEAD.lock"))) def test_add_if_new_packed(self) -> None: # don't overwrite packed ref self.assertFalse(self._refs.add_if_new(b"refs/tags/refs-0.1", b"9" * 40)) self.assertEqual( b"df6800012397fb85c56e7418dd4eb9405dee075c", self._refs[b"refs/tags/refs-0.1"], ) def test_add_if_new_symbolic(self) -> None: # Use an empty repo instead of the default. repo_dir = os.path.join(tempfile.mkdtemp(), "test") os.makedirs(repo_dir) repo = Repo.init(repo_dir) self.addCleanup(tear_down_repo, repo) refs = repo.refs nines = b"9" * 40 self.assertEqual(b"ref: refs/heads/master", refs.read_ref(b"HEAD")) self.assertNotIn(b"refs/heads/master", refs) self.assertTrue(refs.add_if_new(b"HEAD", nines)) self.assertEqual(b"ref: refs/heads/master", refs.read_ref(b"HEAD")) self.assertEqual(nines, refs[b"HEAD"]) self.assertEqual(nines, refs[b"refs/heads/master"]) self.assertFalse(refs.add_if_new(b"HEAD", b"1" * 40)) self.assertEqual(nines, refs[b"HEAD"]) self.assertEqual(nines, refs[b"refs/heads/master"]) def test_follow(self) -> None: self.assertEqual( ( [b"HEAD", b"refs/heads/master"], b"42d06bd4b77fed026b154d16493e5deab78f02ec", ), self._refs.follow(b"HEAD"), ) self.assertEqual( ( [b"refs/heads/master"], b"42d06bd4b77fed026b154d16493e5deab78f02ec", ), self._refs.follow(b"refs/heads/master"), ) self.assertRaises(SymrefLoop, self._refs.follow, b"refs/heads/loop") def test_set_overwrite_loop(self) -> None: self.assertRaises(SymrefLoop, self._refs.follow, b"refs/heads/loop") self._refs[b"refs/heads/loop"] = b"42d06bd4b77fed026b154d16493e5deab78f02ec" self.assertEqual( ([b"refs/heads/loop"], b"42d06bd4b77fed026b154d16493e5deab78f02ec"), self._refs.follow(b"refs/heads/loop"), ) def test_delitem(self) -> None: RefsContainerTests.test_delitem(self) ref_file = os.path.join(self._refs.path, b"refs", b"heads", b"master") self.assertFalse(os.path.exists(ref_file)) self.assertNotIn(b"refs/heads/master", self._refs.get_packed_refs()) def test_delitem_symbolic(self) -> None: self.assertEqual(b"ref: refs/heads/master", self._refs.read_loose_ref(b"HEAD")) del self._refs[b"HEAD"] self.assertRaises(KeyError, lambda: self._refs[b"HEAD"]) self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"refs/heads/master"], ) self.assertFalse(os.path.exists(os.path.join(self._refs.path, b"HEAD"))) def test_remove_if_equals_symref(self) -> None: # HEAD is a symref, so shouldn't equal its dereferenced value self.assertFalse( self._refs.remove_if_equals( b"HEAD", b"42d06bd4b77fed026b154d16493e5deab78f02ec" ) ) self.assertTrue( self._refs.remove_if_equals( b"refs/heads/master", b"42d06bd4b77fed026b154d16493e5deab78f02ec", ) ) self.assertRaises(KeyError, lambda: self._refs[b"refs/heads/master"]) # HEAD is now a broken symref self.assertRaises(KeyError, lambda: self._refs[b"HEAD"]) self.assertEqual(b"ref: refs/heads/master", self._refs.read_loose_ref(b"HEAD")) self.assertFalse( os.path.exists( os.path.join(self._refs.path, b"refs", b"heads", b"master.lock") ) ) self.assertFalse(os.path.exists(os.path.join(self._refs.path, b"HEAD.lock"))) def test_remove_packed_without_peeled(self) -> None: refs_file = os.path.join(self._repo.path, "packed-refs") f = GitFile(refs_file) refs_data = f.read() f.close() f = GitFile(refs_file, "wb") f.write( b"\n".join( line for line in refs_data.split(b"\n") if not line or line[0] not in b"#^" ) ) f.close() self._repo = Repo(self._repo.path) refs = self._repo.refs self.assertTrue( refs.remove_if_equals( b"refs/heads/packed", b"42d06bd4b77fed026b154d16493e5deab78f02ec", ) ) def test_remove_if_equals_packed(self) -> None: # test removing ref that is only packed self.assertEqual( b"df6800012397fb85c56e7418dd4eb9405dee075c", self._refs[b"refs/tags/refs-0.1"], ) self.assertTrue( self._refs.remove_if_equals( b"refs/tags/refs-0.1", b"df6800012397fb85c56e7418dd4eb9405dee075c", ) ) self.assertRaises(KeyError, lambda: self._refs[b"refs/tags/refs-0.1"]) def test_remove_parent(self) -> None: self._refs[b"refs/heads/foo/bar"] = b"df6800012397fb85c56e7418dd4eb9405dee075c" del self._refs[b"refs/heads/foo/bar"] ref_file = os.path.join( self._refs.path, b"refs", b"heads", b"foo", b"bar", ) self.assertFalse(os.path.exists(ref_file)) ref_file = os.path.join(self._refs.path, b"refs", b"heads", b"foo") self.assertFalse(os.path.exists(ref_file)) ref_file = os.path.join(self._refs.path, b"refs", b"heads") self.assertTrue(os.path.exists(ref_file)) self._refs[b"refs/heads/foo"] = b"df6800012397fb85c56e7418dd4eb9405dee075c" def test_read_ref(self) -> None: self.assertEqual(b"ref: refs/heads/master", self._refs.read_ref(b"HEAD")) self.assertEqual( b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs.read_ref(b"refs/heads/packed"), ) self.assertEqual(None, self._refs.read_ref(b"nonexistent")) def test_read_loose_ref(self) -> None: self._refs[b"refs/heads/foo"] = b"df6800012397fb85c56e7418dd4eb9405dee075c" self.assertEqual(None, self._refs.read_ref(b"refs/heads/foo/bar")) def test_non_ascii(self) -> None: try: encoded_ref = os.fsencode("refs/tags/schön") except UnicodeEncodeError as exc: raise SkipTest( "filesystem encoding doesn't support special character" ) from exc p = os.path.join(os.fsencode(self._repo.path), encoded_ref) with open(p, "w") as f: f.write("00" * 20) expected_refs = dict(_TEST_REFS) expected_refs[encoded_ref] = b"00" * 20 del expected_refs[b"refs/heads/loop"] self.assertEqual(expected_refs, self._repo.get_refs()) def test_cyrillic(self) -> None: if sys.platform in ("darwin", "win32"): raise SkipTest("filesystem encoding doesn't support arbitrary bytes") # reported in https://github.com/dulwich/dulwich/issues/608 name = b"\xcd\xee\xe2\xe0\xff\xe2\xe5\xf2\xea\xe01" encoded_ref = b"refs/heads/" + name with open(os.path.join(os.fsencode(self._repo.path), encoded_ref), "w") as f: f.write("00" * 20) expected_refs = set(_TEST_REFS.keys()) expected_refs.add(encoded_ref) self.assertEqual(expected_refs, set(self._repo.refs.allkeys())) self.assertEqual( {r[len(b"refs/") :] for r in expected_refs if r.startswith(b"refs/")}, set(self._repo.refs.subkeys(b"refs/")), ) expected_refs.remove(b"refs/heads/loop") expected_refs.add(b"HEAD") self.assertEqual(expected_refs, set(self._repo.get_refs().keys())) _TEST_REFS_SERIALIZED = ( b"42d06bd4b77fed026b154d16493e5deab78f02ec\t" b"refs/heads/40-char-ref-aaaaaaaaaaaaaaaaaa\n" b"42d06bd4b77fed026b154d16493e5deab78f02ec\trefs/heads/master\n" b"42d06bd4b77fed026b154d16493e5deab78f02ec\trefs/heads/packed\n" b"df6800012397fb85c56e7418dd4eb9405dee075c\trefs/tags/refs-0.1\n" b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8\trefs/tags/refs-0.2\n" ) class InfoRefsContainerTests(TestCase): def test_invalid_refname(self) -> None: text = _TEST_REFS_SERIALIZED + b"00" * 20 + b"\trefs/stash\n" refs = InfoRefsContainer(BytesIO(text)) expected_refs = dict(_TEST_REFS) del expected_refs[b"HEAD"] expected_refs[b"refs/stash"] = b"00" * 20 del expected_refs[b"refs/heads/loop"] self.assertEqual(expected_refs, refs.as_dict()) def test_keys(self) -> None: refs = InfoRefsContainer(BytesIO(_TEST_REFS_SERIALIZED)) actual_keys = set(refs.keys()) self.assertEqual(set(refs.allkeys()), actual_keys) expected_refs = dict(_TEST_REFS) del expected_refs[b"HEAD"] del expected_refs[b"refs/heads/loop"] self.assertEqual(set(expected_refs.keys()), actual_keys) actual_keys = refs.keys(b"refs/heads") actual_keys.discard(b"loop") self.assertEqual( [b"40-char-ref-aaaaaaaaaaaaaaaaaa", b"master", b"packed"], sorted(actual_keys), ) self.assertEqual([b"refs-0.1", b"refs-0.2"], sorted(refs.keys(b"refs/tags"))) def test_as_dict(self) -> None: refs = InfoRefsContainer(BytesIO(_TEST_REFS_SERIALIZED)) # refs/heads/loop does not show up even if it exists expected_refs = dict(_TEST_REFS) del expected_refs[b"HEAD"] del expected_refs[b"refs/heads/loop"] self.assertEqual(expected_refs, refs.as_dict()) def test_contains(self) -> None: refs = InfoRefsContainer(BytesIO(_TEST_REFS_SERIALIZED)) self.assertIn(b"refs/heads/master", refs) self.assertNotIn(b"refs/heads/bar", refs) def test_get_peeled(self) -> None: refs = InfoRefsContainer(BytesIO(_TEST_REFS_SERIALIZED)) # refs/heads/loop does not show up even if it exists self.assertEqual( _TEST_REFS[b"refs/heads/master"], refs.get_peeled(b"refs/heads/master"), ) class ParseSymrefValueTests(TestCase): def test_valid(self) -> None: self.assertEqual(b"refs/heads/foo", parse_symref_value(b"ref: refs/heads/foo")) def test_invalid(self) -> None: self.assertRaises(ValueError, parse_symref_value, b"foobar") class StripPeeledRefsTests(TestCase): all_refs: ClassVar[dict[bytes, bytes]] = { b"refs/heads/master": b"8843d7f92416211de9ebb963ff4ce28125932878", b"refs/heads/testing": b"186a005b134d8639a58b6731c7c1ea821a6eedba", b"refs/tags/1.0.0": b"a93db4b0360cc635a2b93675010bac8d101f73f0", b"refs/tags/1.0.0^{}": b"a93db4b0360cc635a2b93675010bac8d101f73f0", b"refs/tags/2.0.0": b"0749936d0956c661ac8f8d3483774509c165f89e", b"refs/tags/2.0.0^{}": b"0749936d0956c661ac8f8d3483774509c165f89e", } non_peeled_refs: ClassVar[dict[bytes, bytes]] = { b"refs/heads/master": b"8843d7f92416211de9ebb963ff4ce28125932878", b"refs/heads/testing": b"186a005b134d8639a58b6731c7c1ea821a6eedba", b"refs/tags/1.0.0": b"a93db4b0360cc635a2b93675010bac8d101f73f0", b"refs/tags/2.0.0": b"0749936d0956c661ac8f8d3483774509c165f89e", } def test_strip_peeled_refs(self) -> None: # Simple check of two dicts self.assertEqual(strip_peeled_refs(self.all_refs), self.non_peeled_refs) def test_split_peeled_refs(self) -> None: (regular, peeled) = split_peeled_refs(self.all_refs) self.assertEqual(regular, self.non_peeled_refs) self.assertEqual( peeled, { b"refs/tags/2.0.0": b"0749936d0956c661ac8f8d3483774509c165f89e", b"refs/tags/1.0.0": b"a93db4b0360cc635a2b93675010bac8d101f73f0", }, ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_repository.py0000644000175100002000000016161014731042555017636 0ustar00runnerdocker# test_repository.py -- tests for repository.py # Copyright (C) 2007 James Westby # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for the repository.""" import glob import locale import os import shutil import stat import sys import tempfile import warnings from dulwich import errors, objects, porcelain from dulwich.config import Config from dulwich.errors import NotGitRepository from dulwich.object_store import tree_lookup_path from dulwich.repo import ( InvalidUserIdentity, MemoryRepo, Repo, UnsupportedExtension, UnsupportedVersion, check_user_identity, ) from dulwich.tests.utils import open_repo, setup_warning_catcher, tear_down_repo from . import TestCase, skipIf missing_sha = b"b91fa4d900e17e99b433218e988c4eb4a3e9a097" class CreateRepositoryTests(TestCase): def assertFileContentsEqual(self, expected, repo, path) -> None: f = repo.get_named_file(path) if not f: self.assertEqual(expected, None) else: with f: self.assertEqual(expected, f.read()) def _check_repo_contents(self, repo, expect_bare) -> None: self.assertEqual(expect_bare, repo.bare) self.assertFileContentsEqual(b"Unnamed repository", repo, "description") self.assertFileContentsEqual(b"", repo, os.path.join("info", "exclude")) self.assertFileContentsEqual(None, repo, "nonexistent file") barestr = b"bare = " + str(expect_bare).lower().encode("ascii") with repo.get_named_file("config") as f: config_text = f.read() self.assertIn(barestr, config_text, f"{config_text!r}") expect_filemode = sys.platform != "win32" barestr = b"filemode = " + str(expect_filemode).lower().encode("ascii") with repo.get_named_file("config") as f: config_text = f.read() self.assertIn(barestr, config_text, f"{config_text!r}") if isinstance(repo, Repo): expected_mode = "0o100644" if expect_filemode else "0o100666" expected = { "HEAD": expected_mode, "config": expected_mode, "description": expected_mode, } actual = { f[len(repo._controldir) + 1 :]: oct(os.stat(f).st_mode) for f in glob.glob(os.path.join(repo._controldir, "*")) if os.path.isfile(f) } self.assertEqual(expected, actual) def test_create_memory(self) -> None: repo = MemoryRepo.init_bare([], {}) self._check_repo_contents(repo, True) def test_create_disk_bare(self) -> None: tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) repo = Repo.init_bare(tmp_dir) self.assertEqual(tmp_dir, repo._controldir) self._check_repo_contents(repo, True) def test_create_disk_non_bare(self) -> None: tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) repo = Repo.init(tmp_dir) self.assertEqual(os.path.join(tmp_dir, ".git"), repo._controldir) self._check_repo_contents(repo, False) def test_create_disk_non_bare_mkdir(self) -> None: tmp_dir = tempfile.mkdtemp() target_dir = os.path.join(tmp_dir, "target") self.addCleanup(shutil.rmtree, tmp_dir) repo = Repo.init(target_dir, mkdir=True) self.assertEqual(os.path.join(target_dir, ".git"), repo._controldir) self._check_repo_contents(repo, False) def test_create_disk_bare_mkdir(self) -> None: tmp_dir = tempfile.mkdtemp() target_dir = os.path.join(tmp_dir, "target") self.addCleanup(shutil.rmtree, tmp_dir) repo = Repo.init_bare(target_dir, mkdir=True) self.assertEqual(target_dir, repo._controldir) self._check_repo_contents(repo, True) class MemoryRepoTests(TestCase): def test_set_description(self) -> None: r = MemoryRepo.init_bare([], {}) description = b"Some description" r.set_description(description) self.assertEqual(description, r.get_description()) def test_pull_into(self) -> None: r = MemoryRepo.init_bare([], {}) repo = open_repo("a.git") self.addCleanup(tear_down_repo, repo) repo.fetch(r) class RepositoryRootTests(TestCase): def mkdtemp(self): return tempfile.mkdtemp() def open_repo(self, name): temp_dir = self.mkdtemp() repo = open_repo(name, temp_dir) self.addCleanup(tear_down_repo, repo) return repo def test_simple_props(self) -> None: r = self.open_repo("a.git") self.assertEqual(r.controldir(), r.path) def test_setitem(self) -> None: r = self.open_repo("a.git") r[b"refs/tags/foo"] = b"a90fa2d900a17e99b433217e988c4eb4a2e9a097" self.assertEqual( b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", r[b"refs/tags/foo"].id ) def test_getitem_unicode(self) -> None: r = self.open_repo("a.git") test_keys = [ (b"refs/heads/master", True), (b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", True), (b"11" * 19 + b"--", False), ] for k, contained in test_keys: self.assertEqual(k in r, contained) # Avoid deprecation warning under Py3.2+ if getattr(self, "assertRaisesRegex", None): assertRaisesRegexp = self.assertRaisesRegex else: assertRaisesRegexp = self.assertRaisesRegexp for k, _ in test_keys: assertRaisesRegexp( TypeError, "'name' must be bytestring, not int", r.__getitem__, 12, ) def test_delitem(self) -> None: r = self.open_repo("a.git") del r[b"refs/heads/master"] self.assertRaises(KeyError, lambda: r[b"refs/heads/master"]) del r[b"HEAD"] self.assertRaises(KeyError, lambda: r[b"HEAD"]) self.assertRaises(ValueError, r.__delitem__, b"notrefs/foo") def test_get_refs(self) -> None: r = self.open_repo("a.git") self.assertEqual( { b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50", }, r.get_refs(), ) def test_head(self) -> None: r = self.open_repo("a.git") self.assertEqual(r.head(), b"a90fa2d900a17e99b433217e988c4eb4a2e9a097") def test_get_object(self) -> None: r = self.open_repo("a.git") obj = r.get_object(r.head()) self.assertEqual(obj.type_name, b"commit") def test_get_object_non_existant(self) -> None: r = self.open_repo("a.git") self.assertRaises(KeyError, r.get_object, missing_sha) def test_contains_object(self) -> None: r = self.open_repo("a.git") self.assertIn(r.head(), r) self.assertNotIn(b"z" * 40, r) def test_contains_ref(self) -> None: r = self.open_repo("a.git") self.assertIn(b"HEAD", r) def test_get_no_description(self) -> None: r = self.open_repo("a.git") self.assertIs(None, r.get_description()) def test_get_description(self) -> None: r = self.open_repo("a.git") with open(os.path.join(r.path, "description"), "wb") as f: f.write(b"Some description") self.assertEqual(b"Some description", r.get_description()) def test_set_description(self) -> None: r = self.open_repo("a.git") description = b"Some description" r.set_description(description) self.assertEqual(description, r.get_description()) def test_contains_missing(self) -> None: r = self.open_repo("a.git") self.assertNotIn(b"bar", r) def test_get_peeled(self) -> None: # unpacked ref r = self.open_repo("a.git") tag_sha = b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a" self.assertNotEqual(r[tag_sha].sha().hexdigest(), r.head()) self.assertEqual(r.get_peeled(b"refs/tags/mytag"), r.head()) # packed ref with cached peeled value packed_tag_sha = b"b0931cadc54336e78a1d980420e3268903b57a50" parent_sha = r[r.head()].parents[0] self.assertNotEqual(r[packed_tag_sha].sha().hexdigest(), parent_sha) self.assertEqual(r.get_peeled(b"refs/tags/mytag-packed"), parent_sha) # TODO: add more corner cases to test repo def test_get_peeled_not_tag(self) -> None: r = self.open_repo("a.git") self.assertEqual(r.get_peeled(b"HEAD"), r.head()) def test_get_parents(self) -> None: r = self.open_repo("a.git") self.assertEqual( [b"2a72d929692c41d8554c07f6301757ba18a65d91"], r.get_parents(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"), ) r.update_shallow([b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"], None) self.assertEqual([], r.get_parents(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097")) def test_get_walker(self) -> None: r = self.open_repo("a.git") # include defaults to [r.head()] self.assertEqual( [e.commit.id for e in r.get_walker()], [r.head(), b"2a72d929692c41d8554c07f6301757ba18a65d91"], ) self.assertEqual( [ e.commit.id for e in r.get_walker([b"2a72d929692c41d8554c07f6301757ba18a65d91"]) ], [b"2a72d929692c41d8554c07f6301757ba18a65d91"], ) self.assertEqual( [ e.commit.id for e in r.get_walker(b"2a72d929692c41d8554c07f6301757ba18a65d91") ], [b"2a72d929692c41d8554c07f6301757ba18a65d91"], ) def assertFilesystemHidden(self, path) -> None: if sys.platform != "win32": return import ctypes from ctypes.wintypes import DWORD, LPCWSTR GetFileAttributesW = ctypes.WINFUNCTYPE(DWORD, LPCWSTR)( ("GetFileAttributesW", ctypes.windll.kernel32) ) self.assertTrue(2 & GetFileAttributesW(path)) def test_init_existing(self) -> None: tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) t = Repo.init(tmp_dir) self.addCleanup(t.close) self.assertEqual(os.listdir(tmp_dir), [".git"]) self.assertFilesystemHidden(os.path.join(tmp_dir, ".git")) def test_init_mkdir(self) -> None: tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) repo_dir = os.path.join(tmp_dir, "a-repo") t = Repo.init(repo_dir, mkdir=True) self.addCleanup(t.close) self.assertEqual(os.listdir(repo_dir), [".git"]) self.assertFilesystemHidden(os.path.join(repo_dir, ".git")) def test_init_mkdir_unicode(self) -> None: repo_name = "\xa7" try: os.fsencode(repo_name) except UnicodeEncodeError: self.skipTest("filesystem lacks unicode support") tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) repo_dir = os.path.join(tmp_dir, repo_name) t = Repo.init(repo_dir, mkdir=True) self.addCleanup(t.close) self.assertEqual(os.listdir(repo_dir), [".git"]) self.assertFilesystemHidden(os.path.join(repo_dir, ".git")) @skipIf(sys.platform == "win32", "fails on Windows") def test_fetch(self) -> None: r = self.open_repo("a.git") tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) t = Repo.init(tmp_dir) self.addCleanup(t.close) r.fetch(t) self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t) self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t) self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t) self.assertIn(b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", t) self.assertIn(b"b0931cadc54336e78a1d980420e3268903b57a50", t) @skipIf(sys.platform == "win32", "fails on Windows") def test_fetch_ignores_missing_refs(self) -> None: r = self.open_repo("a.git") missing = b"1234566789123456789123567891234657373833" r.refs[b"refs/heads/blah"] = missing tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) t = Repo.init(tmp_dir) self.addCleanup(t.close) r.fetch(t) self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t) self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t) self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t) self.assertIn(b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", t) self.assertIn(b"b0931cadc54336e78a1d980420e3268903b57a50", t) self.assertNotIn(missing, t) def test_clone(self) -> None: r = self.open_repo("a.git") tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) with r.clone(tmp_dir, mkdir=False) as t: self.assertEqual( { b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", b"refs/remotes/origin/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", b"refs/remotes/origin/HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50", }, t.refs.as_dict(), ) shas = [e.commit.id for e in r.get_walker()] self.assertEqual( shas, [t.head(), b"2a72d929692c41d8554c07f6301757ba18a65d91"] ) c = t.get_config() encoded_path = r.path if not isinstance(encoded_path, bytes): encoded_path = os.fsencode(encoded_path) self.assertEqual(encoded_path, c.get((b"remote", b"origin"), b"url")) self.assertEqual( b"+refs/heads/*:refs/remotes/origin/*", c.get((b"remote", b"origin"), b"fetch"), ) def test_clone_no_head(self) -> None: temp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, temp_dir) repo_dir = os.path.join(os.path.dirname(__file__), "..", "testdata", "repos") dest_dir = os.path.join(temp_dir, "a.git") shutil.copytree(os.path.join(repo_dir, "a.git"), dest_dir, symlinks=True) r = Repo(dest_dir) self.addCleanup(r.close) del r.refs[b"refs/heads/master"] del r.refs[b"HEAD"] t = r.clone(os.path.join(temp_dir, "b.git"), mkdir=True) self.addCleanup(t.close) self.assertEqual( { b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50", }, t.refs.as_dict(), ) def test_clone_empty(self) -> None: """Test clone() doesn't crash if HEAD points to a non-existing ref. This simulates cloning server-side bare repository either when it is still empty or if user renames master branch and pushes private repo to the server. Non-bare repo HEAD always points to an existing ref. """ r = self.open_repo("empty.git") tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) r.clone(tmp_dir, mkdir=False, bare=True) def test_reset_index_symlink_enabled(self) -> None: if sys.platform == "win32": self.skipTest("symlinks are not supported on Windows") tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) o = Repo.init(os.path.join(tmp_dir, "s"), mkdir=True) os.symlink("foo", os.path.join(tmp_dir, "s", "bar")) o.stage("bar") o.do_commit(b"add symlink") t = o.clone(os.path.join(tmp_dir, "t"), symlinks=True) o.close() bar_path = os.path.join(tmp_dir, "t", "bar") if sys.platform == "win32": with open(bar_path) as f: self.assertEqual("foo", f.read()) else: self.assertEqual("foo", os.readlink(bar_path)) t.close() def test_reset_index_symlink_disabled(self) -> None: tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) o = Repo.init(os.path.join(tmp_dir, "s"), mkdir=True) o.close() os.symlink("foo", os.path.join(tmp_dir, "s", "bar")) o.stage("bar") o.do_commit(b"add symlink") t = o.clone(os.path.join(tmp_dir, "t"), symlinks=False) with open(os.path.join(tmp_dir, "t", "bar")) as f: self.assertEqual("foo", f.read()) t.close() def test_clone_bare(self) -> None: r = self.open_repo("a.git") tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) t = r.clone(tmp_dir, mkdir=False) t.close() def test_clone_checkout_and_bare(self) -> None: r = self.open_repo("a.git") tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) self.assertRaises( ValueError, r.clone, tmp_dir, mkdir=False, checkout=True, bare=True ) def test_clone_branch(self) -> None: r = self.open_repo("a.git") r.refs[b"refs/heads/mybranch"] = b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a" tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) with r.clone(tmp_dir, mkdir=False, branch=b"mybranch") as t: # HEAD should point to specified branch and not origin HEAD chain, sha = t.refs.follow(b"HEAD") self.assertEqual(chain[-1], b"refs/heads/mybranch") self.assertEqual(sha, b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a") self.assertEqual( t.refs[b"refs/remotes/origin/HEAD"], b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", ) def test_clone_tag(self) -> None: r = self.open_repo("a.git") tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) with r.clone(tmp_dir, mkdir=False, branch=b"mytag") as t: # HEAD should be detached (and not a symbolic ref) at tag self.assertEqual( t.refs.read_ref(b"HEAD"), b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", ) self.assertEqual( t.refs[b"refs/remotes/origin/HEAD"], b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", ) def test_clone_invalid_branch(self) -> None: r = self.open_repo("a.git") tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) self.assertRaises( ValueError, r.clone, tmp_dir, mkdir=False, branch=b"mybranch", ) def test_merge_history(self) -> None: r = self.open_repo("simple_merge.git") shas = [e.commit.id for e in r.get_walker()] self.assertEqual( shas, [ b"5dac377bdded4c9aeb8dff595f0faeebcc8498cc", b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd", b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6", b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e", b"0d89f20333fbb1d2f3a94da77f4981373d8f4310", ], ) def test_out_of_order_merge(self) -> None: """Test that revision history is ordered by date, not parent order.""" r = self.open_repo("ooo_merge.git") shas = [e.commit.id for e in r.get_walker()] self.assertEqual( shas, [ b"7601d7f6231db6a57f7bbb79ee52e4d462fd44d1", b"f507291b64138b875c28e03469025b1ea20bc614", b"fb5b0425c7ce46959bec94d54b9a157645e114f5", b"f9e39b120c68182a4ba35349f832d0e4e61f485c", ], ) def test_get_tags_empty(self) -> None: r = self.open_repo("ooo_merge.git") self.assertEqual({}, r.refs.as_dict(b"refs/tags")) def test_get_config(self) -> None: r = self.open_repo("ooo_merge.git") self.assertIsInstance(r.get_config(), Config) def test_get_config_stack(self) -> None: r = self.open_repo("ooo_merge.git") self.assertIsInstance(r.get_config_stack(), Config) def test_common_revisions(self) -> None: """This test demonstrates that ``find_common_revisions()`` actually returns common heads, not revisions; dulwich already uses ``find_common_revisions()`` in such a manner (see ``Repo.find_objects()``). """ expected_shas = {b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e"} # Source for objects. r_base = self.open_repo("simple_merge.git") # Re-create each-side of the merge in simple_merge.git. # # Since the trees and blobs are missing, the repository created is # corrupted, but we're only checking for commits for the purpose of # this test, so it's immaterial. r1_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, r1_dir) r1_commits = [ b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd", # HEAD b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e", b"0d89f20333fbb1d2f3a94da77f4981373d8f4310", ] r2_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, r2_dir) r2_commits = [ b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6", # HEAD b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e", b"0d89f20333fbb1d2f3a94da77f4981373d8f4310", ] r1 = Repo.init_bare(r1_dir) for c in r1_commits: r1.object_store.add_object(r_base.get_object(c)) r1.refs[b"HEAD"] = r1_commits[0] r2 = Repo.init_bare(r2_dir) for c in r2_commits: r2.object_store.add_object(r_base.get_object(c)) r2.refs[b"HEAD"] = r2_commits[0] # Finally, the 'real' testing! shas = r2.object_store.find_common_revisions(r1.get_graph_walker()) self.assertEqual(set(shas), expected_shas) shas = r1.object_store.find_common_revisions(r2.get_graph_walker()) self.assertEqual(set(shas), expected_shas) def test_shell_hook_pre_commit(self) -> None: if os.name != "posix": self.skipTest("shell hook tests requires POSIX shell") pre_commit_fail = """#!/bin/sh exit 1 """ pre_commit_success = """#!/bin/sh exit 0 """ repo_dir = os.path.join(self.mkdtemp()) self.addCleanup(shutil.rmtree, repo_dir) r = Repo.init(repo_dir) self.addCleanup(r.close) pre_commit = os.path.join(r.controldir(), "hooks", "pre-commit") with open(pre_commit, "w") as f: f.write(pre_commit_fail) os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) self.assertRaises( errors.CommitError, r.do_commit, b"failed commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0, ) with open(pre_commit, "w") as f: f.write(pre_commit_success) os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) commit_sha = r.do_commit( b"empty commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ) self.assertEqual([], r[commit_sha].parents) def test_shell_hook_commit_msg(self) -> None: if os.name != "posix": self.skipTest("shell hook tests requires POSIX shell") commit_msg_fail = """#!/bin/sh exit 1 """ commit_msg_success = """#!/bin/sh exit 0 """ repo_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) r = Repo.init(repo_dir) self.addCleanup(r.close) commit_msg = os.path.join(r.controldir(), "hooks", "commit-msg") with open(commit_msg, "w") as f: f.write(commit_msg_fail) os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) self.assertRaises( errors.CommitError, r.do_commit, b"failed commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0, ) with open(commit_msg, "w") as f: f.write(commit_msg_success) os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) commit_sha = r.do_commit( b"empty commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ) self.assertEqual([], r[commit_sha].parents) def test_shell_hook_pre_commit_add_files(self) -> None: if os.name != "posix": self.skipTest("shell hook tests requires POSIX shell") pre_commit_contents = """#!{executable} import sys sys.path.extend({path!r}) from dulwich.repo import Repo with open('foo', 'w') as f: f.write('newfile') r = Repo('.') r.stage(['foo']) """.format( executable=sys.executable, path=[os.path.join(os.path.dirname(__file__), "..", ".."), *sys.path], ) repo_dir = os.path.join(self.mkdtemp()) self.addCleanup(shutil.rmtree, repo_dir) r = Repo.init(repo_dir) self.addCleanup(r.close) with open(os.path.join(repo_dir, "blah"), "w") as f: f.write("blah") r.stage(["blah"]) pre_commit = os.path.join(r.controldir(), "hooks", "pre-commit") with open(pre_commit, "w") as f: f.write(pre_commit_contents) os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) commit_sha = r.do_commit( b"new commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ) self.assertEqual([], r[commit_sha].parents) tree = r[r[commit_sha].tree] self.assertEqual({b"blah", b"foo"}, set(tree)) def test_shell_hook_post_commit(self) -> None: if os.name != "posix": self.skipTest("shell hook tests requires POSIX shell") repo_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) r = Repo.init(repo_dir) self.addCleanup(r.close) (fd, path) = tempfile.mkstemp(dir=repo_dir) os.close(fd) post_commit_msg = ( """#!/bin/sh rm """ + path + """ """ ) root_sha = r.do_commit( b"empty commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0, ) self.assertEqual([], r[root_sha].parents) post_commit = os.path.join(r.controldir(), "hooks", "post-commit") with open(post_commit, "wb") as f: f.write(post_commit_msg.encode(locale.getpreferredencoding())) os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) commit_sha = r.do_commit( b"empty commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0, ) self.assertEqual([root_sha], r[commit_sha].parents) self.assertFalse(os.path.exists(path)) post_commit_msg_fail = """#!/bin/sh exit 1 """ with open(post_commit, "w") as f: f.write(post_commit_msg_fail) os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) warnings.simplefilter("always", UserWarning) self.addCleanup(warnings.resetwarnings) warnings_list, restore_warnings = setup_warning_catcher() self.addCleanup(restore_warnings) commit_sha2 = r.do_commit( b"empty commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0, ) expected_warning = UserWarning( "post-commit hook failed: Hook post-commit exited with " "non-zero status 1", ) for w in warnings_list: if type(w) is type(expected_warning) and w.args == expected_warning.args: break else: raise AssertionError( f"Expected warning {expected_warning!r} not in {warnings_list!r}" ) self.assertEqual([commit_sha], r[commit_sha2].parents) def test_as_dict(self) -> None: def check(repo) -> None: self.assertEqual( repo.refs.subkeys(b"refs/tags"), repo.refs.subkeys(b"refs/tags/"), ) self.assertEqual( repo.refs.as_dict(b"refs/tags"), repo.refs.as_dict(b"refs/tags/"), ) self.assertEqual( repo.refs.as_dict(b"refs/heads"), repo.refs.as_dict(b"refs/heads/"), ) bare = self.open_repo("a.git") tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) with bare.clone(tmp_dir, mkdir=False) as nonbare: check(nonbare) check(bare) def test_working_tree(self) -> None: temp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, temp_dir) worktree_temp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, worktree_temp_dir) r = Repo.init(temp_dir) self.addCleanup(r.close) root_sha = r.do_commit( b"empty commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0, ) r.refs[b"refs/heads/master"] = root_sha w = Repo._init_new_working_directory(worktree_temp_dir, r) self.addCleanup(w.close) new_sha = w.do_commit( b"new commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0, ) w.refs[b"HEAD"] = new_sha self.assertEqual( os.path.abspath(r.controldir()), os.path.abspath(w.commondir()) ) self.assertEqual(r.refs.keys(), w.refs.keys()) self.assertNotEqual(r.head(), w.head()) class BuildRepoRootTests(TestCase): """Tests that build on-disk repos from scratch. Repos live in a temp dir and are torn down after each test. They start with a single commit in master having single file named 'a'. """ def get_repo_dir(self): return os.path.join(tempfile.mkdtemp(), "test") def setUp(self) -> None: super().setUp() self._repo_dir = self.get_repo_dir() os.makedirs(self._repo_dir) r = self._repo = Repo.init(self._repo_dir) self.addCleanup(tear_down_repo, r) self.assertFalse(r.bare) self.assertEqual(b"ref: refs/heads/master", r.refs.read_ref(b"HEAD")) self.assertRaises(KeyError, lambda: r.refs[b"refs/heads/master"]) with open(os.path.join(r.path, "a"), "wb") as f: f.write(b"file contents") r.stage(["a"]) commit_sha = r.do_commit( b"msg", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0, ) self.assertEqual([], r[commit_sha].parents) self._root_commit = commit_sha def test_get_shallow(self) -> None: self.assertEqual(set(), self._repo.get_shallow()) with open(os.path.join(self._repo.path, ".git", "shallow"), "wb") as f: f.write(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097\n") self.assertEqual( {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"}, self._repo.get_shallow(), ) def test_update_shallow(self) -> None: self._repo.update_shallow(None, None) # no op self.assertEqual(set(), self._repo.get_shallow()) self._repo.update_shallow([b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"], None) self.assertEqual( {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"}, self._repo.get_shallow(), ) self._repo.update_shallow( [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"], [b"f9e39b120c68182a4ba35349f832d0e4e61f485c"], ) self.assertEqual( {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"}, self._repo.get_shallow(), ) self._repo.update_shallow(None, [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"]) self.assertEqual(set(), self._repo.get_shallow()) self.assertEqual( False, os.path.exists(os.path.join(self._repo.controldir(), "shallow")), ) def test_build_repo(self) -> None: r = self._repo self.assertEqual(b"ref: refs/heads/master", r.refs.read_ref(b"HEAD")) self.assertEqual(self._root_commit, r.refs[b"refs/heads/master"]) expected_blob = objects.Blob.from_string(b"file contents") self.assertEqual(expected_blob.data, r[expected_blob.id].data) actual_commit = r[self._root_commit] self.assertEqual(b"msg", actual_commit.message) def test_commit_modified(self) -> None: r = self._repo with open(os.path.join(r.path, "a"), "wb") as f: f.write(b"new contents") r.stage(["a"]) commit_sha = r.do_commit( b"modified a", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ) self.assertEqual([self._root_commit], r[commit_sha].parents) a_mode, a_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b"a") self.assertEqual(stat.S_IFREG | 0o644, a_mode) self.assertEqual(b"new contents", r[a_id].data) @skipIf(not getattr(os, "symlink", None), "Requires symlink support") def test_commit_symlink(self) -> None: r = self._repo os.symlink("a", os.path.join(r.path, "b")) r.stage(["a", "b"]) commit_sha = r.do_commit( b"Symlink b", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ) self.assertEqual([self._root_commit], r[commit_sha].parents) b_mode, b_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b"b") self.assertTrue(stat.S_ISLNK(b_mode)) self.assertEqual(b"a", r[b_id].data) def test_commit_merge_heads_file(self) -> None: tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) r = Repo.init(tmp_dir) with open(os.path.join(r.path, "a"), "w") as f: f.write("initial text") c1 = r.do_commit( b"initial commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ) with open(os.path.join(r.path, "a"), "w") as f: f.write("merged text") with open(os.path.join(r.path, ".git", "MERGE_HEAD"), "w") as f: f.write("c27a2d21dd136312d7fa9e8baabb82561a1727d0\n") r.stage(["a"]) commit_sha = r.do_commit( b"deleted a", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ) self.assertEqual( [c1, b"c27a2d21dd136312d7fa9e8baabb82561a1727d0"], r[commit_sha].parents, ) def test_commit_deleted(self) -> None: r = self._repo os.remove(os.path.join(r.path, "a")) r.stage(["a"]) commit_sha = r.do_commit( b"deleted a", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ) self.assertEqual([self._root_commit], r[commit_sha].parents) self.assertEqual([], list(r.open_index())) tree = r[r[commit_sha].tree] self.assertEqual([], list(tree.iteritems())) def test_commit_follows(self) -> None: r = self._repo r.refs.set_symbolic_ref(b"HEAD", b"refs/heads/bla") commit_sha = r.do_commit( b"commit with strange character", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ref=b"HEAD", ) self.assertEqual(commit_sha, r[b"refs/heads/bla"].id) def test_commit_encoding(self) -> None: r = self._repo commit_sha = r.do_commit( b"commit with strange character \xee", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, encoding=b"iso8859-1", ) self.assertEqual(b"iso8859-1", r[commit_sha].encoding) def test_compression_level(self) -> None: r = self._repo c = r.get_config() c.set(("core",), "compression", "3") c.set(("core",), "looseCompression", "4") c.write_to_path() r = Repo(self._repo_dir) self.assertEqual(r.object_store.loose_compression_level, 4) def test_repositoryformatversion_unsupported(self) -> None: r = self._repo c = r.get_config() c.set(("core",), "repositoryformatversion", "2") c.write_to_path() self.assertRaises(UnsupportedVersion, Repo, self._repo_dir) def test_repositoryformatversion_1(self) -> None: r = self._repo c = r.get_config() c.set(("core",), "repositoryformatversion", "1") c.write_to_path() Repo(self._repo_dir) def test_worktreeconfig_extension(self) -> None: r = self._repo c = r.get_config() c.set(("core",), "repositoryformatversion", "1") c.set(("extensions",), "worktreeconfig", True) c.write_to_path() c = r.get_worktree_config() c.set(("user",), "repositoryformatversion", "1") c.set((b"user",), b"name", b"Jelmer") c.write_to_path() cs = r.get_config_stack() self.assertEqual(cs.get(("user",), "name"), b"Jelmer") def test_worktreeconfig_extension_case(self) -> None: """Test that worktree code does not error for alternate case format.""" r = self._repo c = r.get_config() c.set(("core",), "repositoryformatversion", "1") # Capitalize "Config" c.set(("extensions",), "worktreeConfig", True) c.write_to_path() c = r.get_worktree_config() c.set(("user",), "repositoryformatversion", "1") c.set((b"user",), b"name", b"Jelmer") c.write_to_path() # The following line errored before # https://github.com/jelmer/dulwich/issues/1285 was addressed Repo(self._repo_dir) def test_repositoryformatversion_1_extension(self) -> None: r = self._repo c = r.get_config() c.set(("core",), "repositoryformatversion", "1") c.set(("extensions",), "unknownextension", True) c.write_to_path() self.assertRaises(UnsupportedExtension, Repo, self._repo_dir) def test_commit_encoding_from_config(self) -> None: r = self._repo c = r.get_config() c.set(("i18n",), "commitEncoding", "iso8859-1") c.write_to_path() commit_sha = r.do_commit( b"commit with strange character \xee", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ) self.assertEqual(b"iso8859-1", r[commit_sha].encoding) def test_commit_config_identity(self) -> None: # commit falls back to the users' identity if it wasn't specified r = self._repo c = r.get_config() c.set((b"user",), b"name", b"Jelmer") c.set((b"user",), b"email", b"jelmer@apache.org") c.write_to_path() commit_sha = r.do_commit(b"message") self.assertEqual(b"Jelmer ", r[commit_sha].author) self.assertEqual(b"Jelmer ", r[commit_sha].committer) def test_commit_config_identity_strips_than(self) -> None: # commit falls back to the users' identity if it wasn't specified, # and strips superfluous <> r = self._repo c = r.get_config() c.set((b"user",), b"name", b"Jelmer") c.set((b"user",), b"email", b"") c.write_to_path() commit_sha = r.do_commit(b"message") self.assertEqual(b"Jelmer ", r[commit_sha].author) self.assertEqual(b"Jelmer ", r[commit_sha].committer) def test_commit_config_identity_in_memoryrepo(self) -> None: # commit falls back to the users' identity if it wasn't specified r = MemoryRepo.init_bare([], {}) c = r.get_config() c.set((b"user",), b"name", b"Jelmer") c.set((b"user",), b"email", b"jelmer@apache.org") commit_sha = r.do_commit(b"message", tree=objects.Tree().id) self.assertEqual(b"Jelmer ", r[commit_sha].author) self.assertEqual(b"Jelmer ", r[commit_sha].committer) def test_commit_config_identity_from_env(self) -> None: # commit falls back to the users' identity if it wasn't specified self.overrideEnv("GIT_COMMITTER_NAME", "joe") self.overrideEnv("GIT_COMMITTER_EMAIL", "joe@example.com") r = self._repo c = r.get_config() c.set((b"user",), b"name", b"Jelmer") c.set((b"user",), b"email", b"jelmer@apache.org") c.write_to_path() commit_sha = r.do_commit(b"message") self.assertEqual(b"Jelmer ", r[commit_sha].author) self.assertEqual(b"joe ", r[commit_sha].committer) def test_commit_fail_ref(self) -> None: r = self._repo def set_if_equals(name, old_ref, new_ref, **kwargs) -> bool: return False r.refs.set_if_equals = set_if_equals def add_if_new(name, new_ref, **kwargs) -> None: self.fail("Unexpected call to add_if_new") r.refs.add_if_new = add_if_new old_shas = set(r.object_store) self.assertRaises( errors.CommitError, r.do_commit, b"failed commit", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0, ) new_shas = set(r.object_store) - old_shas self.assertEqual(1, len(new_shas)) # Check that the new commit (now garbage) was added. new_commit = r[new_shas.pop()] self.assertEqual(r[self._root_commit].tree, new_commit.tree) self.assertEqual(b"failed commit", new_commit.message) def test_commit_branch(self) -> None: r = self._repo commit_sha = r.do_commit( b"commit to branch", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ref=b"refs/heads/new_branch", ) self.assertEqual(self._root_commit, r[b"HEAD"].id) self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id) self.assertEqual([], r[commit_sha].parents) self.assertIn(b"refs/heads/new_branch", r) new_branch_head = commit_sha commit_sha = r.do_commit( b"commit to branch 2", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ref=b"refs/heads/new_branch", ) self.assertEqual(self._root_commit, r[b"HEAD"].id) self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id) self.assertEqual([new_branch_head], r[commit_sha].parents) def test_commit_merge_heads(self) -> None: r = self._repo merge_1 = r.do_commit( b"commit to branch 2", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ref=b"refs/heads/new_branch", ) commit_sha = r.do_commit( b"commit with merge", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, merge_heads=[merge_1], ) self.assertEqual([self._root_commit, merge_1], r[commit_sha].parents) def test_commit_dangling_commit(self) -> None: r = self._repo old_shas = set(r.object_store) old_refs = r.get_refs() commit_sha = r.do_commit( b"commit with no ref", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ref=None, ) new_shas = set(r.object_store) - old_shas # New sha is added, but no new refs self.assertEqual(1, len(new_shas)) new_commit = r[new_shas.pop()] self.assertEqual(r[self._root_commit].tree, new_commit.tree) self.assertEqual([], r[commit_sha].parents) self.assertEqual(old_refs, r.get_refs()) def test_commit_dangling_commit_with_parents(self) -> None: r = self._repo old_shas = set(r.object_store) old_refs = r.get_refs() commit_sha = r.do_commit( b"commit with no ref", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ref=None, merge_heads=[self._root_commit], ) new_shas = set(r.object_store) - old_shas # New sha is added, but no new refs self.assertEqual(1, len(new_shas)) new_commit = r[new_shas.pop()] self.assertEqual(r[self._root_commit].tree, new_commit.tree) self.assertEqual([self._root_commit], r[commit_sha].parents) self.assertEqual(old_refs, r.get_refs()) def test_stage_absolute(self) -> None: r = self._repo os.remove(os.path.join(r.path, "a")) self.assertRaises(ValueError, r.stage, [os.path.join(r.path, "a")]) def test_stage_deleted(self) -> None: r = self._repo os.remove(os.path.join(r.path, "a")) r.stage(["a"]) r.stage(["a"]) # double-stage a deleted path self.assertEqual([], list(r.open_index())) def test_stage_directory(self) -> None: r = self._repo os.mkdir(os.path.join(r.path, "c")) r.stage(["c"]) self.assertEqual([b"a"], list(r.open_index())) def test_stage_submodule(self) -> None: r = self._repo s = Repo.init(os.path.join(r.path, "sub"), mkdir=True) s.do_commit(b"message") r.stage(["sub"]) self.assertEqual([b"a", b"sub"], list(r.open_index())) def test_unstage_midify_file_with_dir(self) -> None: os.mkdir(os.path.join(self._repo.path, "new_dir")) full_path = os.path.join(self._repo.path, "new_dir", "foo") with open(full_path, "w") as f: f.write("hello") porcelain.add(self._repo, paths=[full_path]) porcelain.commit( self._repo, message=b"unitest", committer=b"Jane ", author=b"John ", ) with open(full_path, "a") as f: f.write("something new") self._repo.unstage(["new_dir/foo"]) status = list(porcelain.status(self._repo)) self.assertEqual( [{"add": [], "delete": [], "modify": []}, [b"new_dir/foo"], []], status ) def test_unstage_while_no_commit(self) -> None: file = "foo" full_path = os.path.join(self._repo.path, file) with open(full_path, "w") as f: f.write("hello") porcelain.add(self._repo, paths=[full_path]) self._repo.unstage([file]) status = list(porcelain.status(self._repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["foo"]], status) def test_unstage_add_file(self) -> None: file = "foo" full_path = os.path.join(self._repo.path, file) porcelain.commit( self._repo, message=b"unitest", committer=b"Jane ", author=b"John ", ) with open(full_path, "w") as f: f.write("hello") porcelain.add(self._repo, paths=[full_path]) self._repo.unstage([file]) status = list(porcelain.status(self._repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["foo"]], status) def test_unstage_modify_file(self) -> None: file = "foo" full_path = os.path.join(self._repo.path, file) with open(full_path, "w") as f: f.write("hello") porcelain.add(self._repo, paths=[full_path]) porcelain.commit( self._repo, message=b"unitest", committer=b"Jane ", author=b"John ", ) with open(full_path, "a") as f: f.write("broken") porcelain.add(self._repo, paths=[full_path]) self._repo.unstage([file]) status = list(porcelain.status(self._repo)) self.assertEqual( [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status ) def test_unstage_remove_file(self) -> None: file = "foo" full_path = os.path.join(self._repo.path, file) with open(full_path, "w") as f: f.write("hello") porcelain.add(self._repo, paths=[full_path]) porcelain.commit( self._repo, message=b"unitest", committer=b"Jane ", author=b"John ", ) os.remove(full_path) self._repo.unstage([file]) status = list(porcelain.status(self._repo)) self.assertEqual( [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status ) def test_reset_index(self) -> None: r = self._repo with open(os.path.join(r.path, "a"), "wb") as f: f.write(b"changed") with open(os.path.join(r.path, "b"), "wb") as f: f.write(b"added") r.stage(["a", "b"]) status = list(porcelain.status(self._repo)) self.assertEqual( [{"add": [b"b"], "delete": [], "modify": [b"a"]}, [], []], status ) r.reset_index() status = list(porcelain.status(self._repo)) self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["b"]], status) @skipIf( sys.platform in ("win32", "darwin"), "tries to implicitly decode as utf8", ) def test_commit_no_encode_decode(self) -> None: r = self._repo repo_path_bytes = os.fsencode(r.path) encodings = ("utf8", "latin1") names = ["À".encode(encoding) for encoding in encodings] for name, encoding in zip(names, encodings): full_path = os.path.join(repo_path_bytes, name) with open(full_path, "wb") as f: f.write(encoding.encode("ascii")) # These files are break tear_down_repo, so cleanup these files # ourselves. self.addCleanup(os.remove, full_path) r.stage(names) commit_sha = r.do_commit( b"Files with different encodings", committer=b"Test Committer ", author=b"Test Author ", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ref=None, merge_heads=[self._root_commit], ) for name, encoding in zip(names, encodings): mode, id = tree_lookup_path(r.get_object, r[commit_sha].tree, name) self.assertEqual(stat.S_IFREG | 0o644, mode) self.assertEqual(encoding.encode("ascii"), r[id].data) def test_discover_intended(self) -> None: path = os.path.join(self._repo_dir, "b/c") r = Repo.discover(path) self.assertEqual(r.head(), self._repo.head()) def test_discover_isrepo(self) -> None: r = Repo.discover(self._repo_dir) self.assertEqual(r.head(), self._repo.head()) def test_discover_notrepo(self) -> None: with self.assertRaises(NotGitRepository): Repo.discover("/") class CheckUserIdentityTests(TestCase): def test_valid(self) -> None: check_user_identity(b"Me ") def test_invalid(self) -> None: self.assertRaises(InvalidUserIdentity, check_user_identity, b"No Email") self.assertRaises( InvalidUserIdentity, check_user_identity, b"Fullname " ) self.assertRaises( InvalidUserIdentity, check_user_identity, b"Fullname >order<>" ) self.assertRaises( InvalidUserIdentity, check_user_identity, b"Contains\0null byte <>" ) self.assertRaises( InvalidUserIdentity, check_user_identity, b"Contains\nnewline byte <>" ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_server.py0000644000175100002000000011272514731042555016730 0ustar00runnerdocker# test_server.py -- Tests for the git server # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for the smart protocol server.""" import os import shutil import sys import tempfile from io import BytesIO from dulwich.errors import ( GitProtocolError, HangupException, NotGitRepository, UnexpectedCommandError, ) from dulwich.object_store import MemoryObjectStore from dulwich.objects import Tree from dulwich.protocol import ZERO_SHA, format_capability_line from dulwich.repo import MemoryRepo, Repo from dulwich.server import ( Backend, DictBackend, FileSystemBackend, MultiAckDetailedGraphWalkerImpl, MultiAckGraphWalkerImpl, PackHandler, ReceivePackHandler, SingleAckGraphWalkerImpl, UploadPackHandler, _find_shallow, _ProtocolGraphWalker, _split_proto_line, serve_command, update_server_info, ) from dulwich.tests.utils import make_commit, make_tag from . import TestCase ONE = b"1" * 40 TWO = b"2" * 40 THREE = b"3" * 40 FOUR = b"4" * 40 FIVE = b"5" * 40 SIX = b"6" * 40 class TestProto: def __init__(self) -> None: self._output: list[bytes] = [] self._received: dict[int, list[bytes]] = {0: [], 1: [], 2: [], 3: []} def set_output(self, output_lines) -> None: self._output = output_lines def read_pkt_line(self): if self._output: data = self._output.pop(0) if data is not None: return data.rstrip() + b"\n" else: # flush-pkt ('0000'). return None else: raise HangupException def write_sideband(self, band, data) -> None: self._received[band].append(data) def write_pkt_line(self, data) -> None: self._received[0].append(data) def get_received_line(self, band=0): lines = self._received[band] return lines.pop(0) class TestGenericPackHandler(PackHandler): def __init__(self) -> None: PackHandler.__init__(self, Backend(), None) @classmethod def capabilities(cls): return [b"cap1", b"cap2", b"cap3"] @classmethod def required_capabilities(cls): return [b"cap2"] class HandlerTestCase(TestCase): def setUp(self) -> None: super().setUp() self._handler = TestGenericPackHandler() def assertSucceeds(self, func, *args, **kwargs) -> None: try: func(*args, **kwargs) except GitProtocolError as e: self.fail(e) def test_capability_line(self) -> None: self.assertEqual( b" cap1 cap2 cap3", format_capability_line([b"cap1", b"cap2", b"cap3"]), ) def test_set_client_capabilities(self) -> None: set_caps = self._handler.set_client_capabilities self.assertSucceeds(set_caps, [b"cap2"]) self.assertSucceeds(set_caps, [b"cap1", b"cap2"]) # different order self.assertSucceeds(set_caps, [b"cap3", b"cap1", b"cap2"]) # error cases self.assertRaises(GitProtocolError, set_caps, [b"capxxx", b"cap2"]) self.assertRaises(GitProtocolError, set_caps, [b"cap1", b"cap3"]) # ignore innocuous but unknown capabilities self.assertRaises(GitProtocolError, set_caps, [b"cap2", b"ignoreme"]) self.assertNotIn(b"ignoreme", self._handler.capabilities()) self._handler.innocuous_capabilities = lambda: (b"ignoreme",) self.assertSucceeds(set_caps, [b"cap2", b"ignoreme"]) def test_has_capability(self) -> None: self.assertRaises(GitProtocolError, self._handler.has_capability, b"cap") caps = self._handler.capabilities() self._handler.set_client_capabilities(caps) for cap in caps: self.assertTrue(self._handler.has_capability(cap)) self.assertFalse(self._handler.has_capability(b"capxxx")) class UploadPackHandlerTestCase(TestCase): def setUp(self) -> None: super().setUp() self.path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.path) self.repo = Repo.init(self.path) self._repo = Repo.init_bare(self.path) backend = DictBackend({b"/": self._repo}) self._handler = UploadPackHandler( backend, [b"/", b"host=lolcathost"], TestProto() ) def test_progress(self) -> None: caps = self._handler.required_capabilities() self._handler.set_client_capabilities(caps) self._handler._start_pack_send_phase() self._handler.progress(b"first message") self._handler.progress(b"second message") self.assertEqual(b"first message", self._handler.proto.get_received_line(2)) self.assertEqual(b"second message", self._handler.proto.get_received_line(2)) self.assertRaises(IndexError, self._handler.proto.get_received_line, 2) def test_no_progress(self) -> None: caps = [*list(self._handler.required_capabilities()), b"no-progress"] self._handler.set_client_capabilities(caps) self._handler.progress(b"first message") self._handler.progress(b"second message") self.assertRaises(IndexError, self._handler.proto.get_received_line, 2) def test_get_tagged(self) -> None: refs = { b"refs/tags/tag1": ONE, b"refs/tags/tag2": TWO, b"refs/heads/master": FOUR, # not a tag, no peeled value } # repo needs to peel this object self._repo.object_store.add_object(make_commit(id=FOUR)) for name, sha in refs.items(): self._repo.refs[name] = sha peeled = { b"refs/tags/tag1": b"1234" * 10, b"refs/tags/tag2": b"5678" * 10, } self._repo.refs._peeled_refs = peeled self._repo.refs.add_packed_refs(refs) caps = [*list(self._handler.required_capabilities()), b"include-tag"] self._handler.set_client_capabilities(caps) self.assertEqual( {b"1234" * 10: ONE, b"5678" * 10: TWO}, self._handler.get_tagged(refs, repo=self._repo), ) # non-include-tag case caps = self._handler.required_capabilities() self._handler.set_client_capabilities(caps) self.assertEqual({}, self._handler.get_tagged(refs, repo=self._repo)) def test_nothing_to_do_but_wants(self) -> None: # Just the fact that the client claims to want an object is enough # for sending a pack. Even if there turns out to be nothing. refs = {b"refs/tags/tag1": ONE} tree = Tree() self._repo.object_store.add_object(tree) self._repo.object_store.add_object(make_commit(id=ONE, tree=tree)) for name, sha in refs.items(): self._repo.refs[name] = sha self._handler.proto.set_output( [ b"want " + ONE + b" side-band-64k thin-pack ofs-delta", None, b"have " + ONE, b"done", None, ] ) self._handler.handle() # The server should always send a pack, even if it's empty. self.assertTrue(self._handler.proto.get_received_line(1).startswith(b"PACK")) def test_nothing_to_do_no_wants(self) -> None: # Don't send a pack if the client didn't ask for anything. refs = {b"refs/tags/tag1": ONE} tree = Tree() self._repo.object_store.add_object(tree) self._repo.object_store.add_object(make_commit(id=ONE, tree=tree)) for ref, sha in refs.items(): self._repo.refs[ref] = sha self._handler.proto.set_output([None]) self._handler.handle() # The server should not send a pack, since the client didn't ask for # anything. self.assertEqual([], self._handler.proto._received[1]) class FindShallowTests(TestCase): def setUp(self) -> None: super().setUp() self._store = MemoryObjectStore() def make_commit(self, **attrs): commit = make_commit(**attrs) self._store.add_object(commit) return commit def make_linear_commits(self, n, message=b""): commits = [] parents = [] for _ in range(n): commits.append(self.make_commit(parents=parents, message=message)) parents = [commits[-1].id] return commits def assertSameElements(self, expected, actual) -> None: self.assertEqual(set(expected), set(actual)) def test_linear(self) -> None: c1, c2, c3 = self.make_linear_commits(3) self.assertEqual(({c3.id}, set()), _find_shallow(self._store, [c3.id], 1)) self.assertEqual( ({c2.id}, {c3.id}), _find_shallow(self._store, [c3.id], 2), ) self.assertEqual( ({c1.id}, {c2.id, c3.id}), _find_shallow(self._store, [c3.id], 3), ) self.assertEqual( (set(), {c1.id, c2.id, c3.id}), _find_shallow(self._store, [c3.id], 4), ) def test_multiple_independent(self) -> None: a = self.make_linear_commits(2, message=b"a") b = self.make_linear_commits(2, message=b"b") c = self.make_linear_commits(2, message=b"c") heads = [a[1].id, b[1].id, c[1].id] self.assertEqual( ({a[0].id, b[0].id, c[0].id}, set(heads)), _find_shallow(self._store, heads, 2), ) def test_multiple_overlapping(self) -> None: # Create the following commit tree: # 1--2 # \ # 3--4 c1, c2 = self.make_linear_commits(2) c3 = self.make_commit(parents=[c1.id]) c4 = self.make_commit(parents=[c3.id]) # 1 is shallow along the path from 4, but not along the path from 2. self.assertEqual( ({c1.id}, {c1.id, c2.id, c3.id, c4.id}), _find_shallow(self._store, [c2.id, c4.id], 3), ) def test_merge(self) -> None: c1 = self.make_commit() c2 = self.make_commit() c3 = self.make_commit(parents=[c1.id, c2.id]) self.assertEqual( ({c1.id, c2.id}, {c3.id}), _find_shallow(self._store, [c3.id], 2), ) def test_tag(self) -> None: c1, c2 = self.make_linear_commits(2) tag = make_tag(c2, name=b"tag") self._store.add_object(tag) self.assertEqual( ({c1.id}, {c2.id}), _find_shallow(self._store, [tag.id], 2), ) class TestUploadPackHandler(UploadPackHandler): @classmethod def required_capabilities(self): return [] class ReceivePackHandlerTestCase(TestCase): def setUp(self) -> None: super().setUp() self._repo = MemoryRepo.init_bare([], {}) backend = DictBackend({b"/": self._repo}) self._handler = ReceivePackHandler( backend, [b"/", b"host=lolcathost"], TestProto() ) def test_apply_pack_del_ref(self) -> None: refs = {b"refs/heads/master": TWO, b"refs/heads/fake-branch": ONE} self._repo.refs._update(refs) update_refs = [ [ONE, ZERO_SHA, b"refs/heads/fake-branch"], ] self._handler.set_client_capabilities([b"delete-refs"]) status = self._handler._apply_pack(update_refs) self.assertEqual(status[0][0], b"unpack") self.assertEqual(status[0][1], b"ok") self.assertEqual(status[1][0], b"refs/heads/fake-branch") self.assertEqual(status[1][1], b"ok") class ProtocolGraphWalkerEmptyTestCase(TestCase): def setUp(self) -> None: super().setUp() self._repo = MemoryRepo.init_bare([], {}) backend = DictBackend({b"/": self._repo}) self._walker = _ProtocolGraphWalker( TestUploadPackHandler(backend, [b"/", b"host=lolcats"], TestProto()), self._repo.object_store, self._repo.get_peeled, self._repo.refs.get_symrefs, ) def test_empty_repository(self) -> None: # The server should wait for a flush packet. self._walker.proto.set_output([]) self.assertRaises(HangupException, self._walker.determine_wants, {}) self.assertEqual(None, self._walker.proto.get_received_line()) self._walker.proto.set_output([None]) self.assertEqual([], self._walker.determine_wants({})) self.assertEqual(None, self._walker.proto.get_received_line()) class ProtocolGraphWalkerTestCase(TestCase): def setUp(self) -> None: super().setUp() # Create the following commit tree: # 3---5 # / # 1---2---4 commits = [ make_commit(id=ONE, parents=[], commit_time=111), make_commit(id=TWO, parents=[ONE], commit_time=222), make_commit(id=THREE, parents=[ONE], commit_time=333), make_commit(id=FOUR, parents=[TWO], commit_time=444), make_commit(id=FIVE, parents=[THREE], commit_time=555), ] self._repo = MemoryRepo.init_bare(commits, {}) backend = DictBackend({b"/": self._repo}) self._walker = _ProtocolGraphWalker( TestUploadPackHandler(backend, [b"/", b"host=lolcats"], TestProto()), self._repo.object_store, self._repo.get_peeled, self._repo.refs.get_symrefs, ) def test_all_wants_satisfied_no_haves(self) -> None: self._walker.set_wants([ONE]) self.assertFalse(self._walker.all_wants_satisfied([])) self._walker.set_wants([TWO]) self.assertFalse(self._walker.all_wants_satisfied([])) self._walker.set_wants([THREE]) self.assertFalse(self._walker.all_wants_satisfied([])) def test_all_wants_satisfied_have_root(self) -> None: self._walker.set_wants([ONE]) self.assertTrue(self._walker.all_wants_satisfied([ONE])) self._walker.set_wants([TWO]) self.assertTrue(self._walker.all_wants_satisfied([ONE])) self._walker.set_wants([THREE]) self.assertTrue(self._walker.all_wants_satisfied([ONE])) def test_all_wants_satisfied_have_branch(self) -> None: self._walker.set_wants([TWO]) self.assertTrue(self._walker.all_wants_satisfied([TWO])) # wrong branch self._walker.set_wants([THREE]) self.assertFalse(self._walker.all_wants_satisfied([TWO])) def test_all_wants_satisfied(self) -> None: self._walker.set_wants([FOUR, FIVE]) # trivial case: wants == haves self.assertTrue(self._walker.all_wants_satisfied([FOUR, FIVE])) # cases that require walking the commit tree self.assertTrue(self._walker.all_wants_satisfied([ONE])) self.assertFalse(self._walker.all_wants_satisfied([TWO])) self.assertFalse(self._walker.all_wants_satisfied([THREE])) self.assertTrue(self._walker.all_wants_satisfied([TWO, THREE])) def test_split_proto_line(self) -> None: allowed = (b"want", b"done", None) self.assertEqual( (b"want", ONE), _split_proto_line(b"want " + ONE + b"\n", allowed) ) self.assertEqual( (b"want", TWO), _split_proto_line(b"want " + TWO + b"\n", allowed) ) self.assertRaises(GitProtocolError, _split_proto_line, b"want xxxx\n", allowed) self.assertRaises( UnexpectedCommandError, _split_proto_line, b"have " + THREE + b"\n", allowed, ) self.assertRaises( GitProtocolError, _split_proto_line, b"foo " + FOUR + b"\n", allowed, ) self.assertRaises(GitProtocolError, _split_proto_line, b"bar", allowed) self.assertEqual((b"done", None), _split_proto_line(b"done\n", allowed)) self.assertEqual((None, None), _split_proto_line(b"", allowed)) def test_determine_wants(self) -> None: self._walker.proto.set_output([None]) self.assertEqual([], self._walker.determine_wants({})) self.assertEqual(None, self._walker.proto.get_received_line()) self._walker.proto.set_output( [ b"want " + ONE + b" multi_ack", b"want " + TWO, None, ] ) heads = { b"refs/heads/ref1": ONE, b"refs/heads/ref2": TWO, b"refs/heads/ref3": THREE, } self._repo.refs._update(heads) self.assertEqual([ONE, TWO], self._walker.determine_wants(heads)) self._walker.advertise_refs = True self.assertEqual([], self._walker.determine_wants(heads)) self._walker.advertise_refs = False self._walker.proto.set_output([b"want " + FOUR + b" multi_ack", None]) self.assertRaises(GitProtocolError, self._walker.determine_wants, heads) self._walker.proto.set_output([None]) self.assertEqual([], self._walker.determine_wants(heads)) self._walker.proto.set_output([b"want " + ONE + b" multi_ack", b"foo", None]) self.assertRaises(GitProtocolError, self._walker.determine_wants, heads) self._walker.proto.set_output([b"want " + FOUR + b" multi_ack", None]) self.assertRaises(GitProtocolError, self._walker.determine_wants, heads) def test_determine_wants_advertisement(self) -> None: self._walker.proto.set_output([None]) # advertise branch tips plus tag heads = { b"refs/heads/ref4": FOUR, b"refs/heads/ref5": FIVE, b"refs/heads/tag6": SIX, } self._repo.refs._update(heads) self._repo.refs._update_peeled(heads) self._repo.refs._update_peeled({b"refs/heads/tag6": FIVE}) self._walker.determine_wants(heads) lines = [] while True: line = self._walker.proto.get_received_line() if line is None: break # strip capabilities list if present if b"\x00" in line: line = line[: line.index(b"\x00")] lines.append(line.rstrip()) self.assertEqual( [ FOUR + b" refs/heads/ref4", FIVE + b" refs/heads/ref5", FIVE + b" refs/heads/tag6^{}", SIX + b" refs/heads/tag6", ], sorted(lines), ) # ensure peeled tag was advertised immediately following tag for i, line in enumerate(lines): if line.endswith(b" refs/heads/tag6"): self.assertEqual(FIVE + b" refs/heads/tag6^{}", lines[i + 1]) # TODO: test commit time cutoff def _handle_shallow_request(self, lines, heads) -> None: self._walker.proto.set_output([*lines, None]) self._walker._handle_shallow_request(heads) def assertReceived(self, expected) -> None: self.assertEqual( expected, list(iter(self._walker.proto.get_received_line, None)) ) def test_handle_shallow_request_no_client_shallows(self) -> None: self._handle_shallow_request([b"deepen 2\n"], [FOUR, FIVE]) self.assertEqual({TWO, THREE}, self._walker.shallow) self.assertReceived( [ b"shallow " + TWO, b"shallow " + THREE, ] ) def test_handle_shallow_request_no_new_shallows(self) -> None: lines = [ b"shallow " + TWO + b"\n", b"shallow " + THREE + b"\n", b"deepen 2\n", ] self._handle_shallow_request(lines, [FOUR, FIVE]) self.assertEqual({TWO, THREE}, self._walker.shallow) self.assertReceived([]) def test_handle_shallow_request_unshallows(self) -> None: lines = [ b"shallow " + TWO + b"\n", b"deepen 3\n", ] self._handle_shallow_request(lines, [FOUR, FIVE]) self.assertEqual({ONE}, self._walker.shallow) self.assertReceived( [ b"shallow " + ONE, b"unshallow " + TWO, # THREE is unshallow but was is not shallow in the client ] ) class TestProtocolGraphWalker: def __init__(self) -> None: self.acks: list[bytes] = [] self.lines: list[bytes] = [] self.wants_satisified = False self.stateless_rpc = None self.advertise_refs = False self._impl = None self.done_required = True self.done_received = False self._empty = False self.pack_sent = False def read_proto_line(self, allowed): command, sha = self.lines.pop(0) if allowed is not None: assert command in allowed return command, sha def send_ack(self, sha, ack_type=b"") -> None: self.acks.append((sha, ack_type)) def send_nak(self) -> None: self.acks.append((None, b"nak")) def all_wants_satisfied(self, haves): if haves: return self.wants_satisified def pop_ack(self): if not self.acks: return None return self.acks.pop(0) def handle_done(self): if not self._impl: return # Whether or not PACK is sent after is determined by this, so # record this value. self.pack_sent = self._impl.handle_done(self.done_required, self.done_received) return self.pack_sent def notify_done(self) -> None: self.done_received = True class AckGraphWalkerImplTestCase(TestCase): """Base setup and asserts for AckGraphWalker tests.""" def setUp(self) -> None: super().setUp() self._walker = TestProtocolGraphWalker() self._walker.lines = [ (b"have", TWO), (b"have", ONE), (b"have", THREE), (b"done", None), ] self._impl = self.impl_cls(self._walker) self._walker._impl = self._impl def assertNoAck(self) -> None: self.assertEqual(None, self._walker.pop_ack()) def assertAcks(self, acks) -> None: for sha, ack_type in acks: self.assertEqual((sha, ack_type), self._walker.pop_ack()) self.assertNoAck() def assertAck(self, sha, ack_type=b"") -> None: self.assertAcks([(sha, ack_type)]) def assertNak(self) -> None: self.assertAck(None, b"nak") def assertNextEquals(self, sha) -> None: self.assertEqual(sha, next(self._impl)) def assertNextEmpty(self) -> None: # This is necessary because of no-done - the assumption that it # it safe to immediately send out the final ACK is no longer # true but the test is still needed for it. TestProtocolWalker # does implement the handle_done which will determine whether # the final confirmation can be sent. self.assertRaises(IndexError, next, self._impl) self._walker.handle_done() class SingleAckGraphWalkerImplTestCase(AckGraphWalkerImplTestCase): impl_cls = SingleAckGraphWalkerImpl def test_single_ack(self) -> None: self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE) self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNoAck() def test_single_ack_flush(self) -> None: # same as ack test but ends with a flush-pkt instead of done self._walker.lines[-1] = (None, None) self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE) self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNoAck() def test_single_ack_nak(self) -> None: self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertNak() def test_single_ack_nak_flush(self) -> None: # same as nak test but ends with a flush-pkt instead of done self._walker.lines[-1] = (None, None) self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertNak() class MultiAckGraphWalkerImplTestCase(AckGraphWalkerImplTestCase): impl_cls = MultiAckGraphWalkerImpl def test_multi_ack(self) -> None: self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b"continue") self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b"continue") self.assertNextEquals(None) self.assertNextEmpty() self.assertAck(THREE) def test_multi_ack_partial(self) -> None: self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b"continue") self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertAck(ONE) def test_multi_ack_flush(self) -> None: self._walker.lines = [ (b"have", TWO), (None, None), (b"have", ONE), (b"have", THREE), (b"done", None), ] self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNak() # nak the flush-pkt self._impl.ack(ONE) self.assertAck(ONE, b"continue") self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b"continue") self.assertNextEquals(None) self.assertNextEmpty() self.assertAck(THREE) def test_multi_ack_nak(self) -> None: self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertNak() class MultiAckDetailedGraphWalkerImplTestCase(AckGraphWalkerImplTestCase): impl_cls = MultiAckDetailedGraphWalkerImpl def test_multi_ack(self) -> None: self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b"common") self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b"common") # done is read. self._walker.wants_satisified = True self.assertNextEquals(None) self._walker.lines.append((None, None)) self.assertNextEmpty() self.assertAcks([(THREE, b"ready"), (None, b"nak"), (THREE, b"")]) # PACK is sent self.assertTrue(self._walker.pack_sent) def test_multi_ack_nodone(self) -> None: self._walker.done_required = False self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b"common") self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b"common") # done is read. self._walker.wants_satisified = True self.assertNextEquals(None) self._walker.lines.append((None, None)) self.assertNextEmpty() self.assertAcks([(THREE, b"ready"), (None, b"nak"), (THREE, b"")]) # PACK is sent self.assertTrue(self._walker.pack_sent) def test_multi_ack_flush_end(self) -> None: # transmission ends with a flush-pkt without a done but no-done is # assumed. self._walker.lines[-1] = (None, None) self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b"common") self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b"common") # no done is read self._walker.wants_satisified = True self.assertNextEmpty() self.assertAcks([(THREE, b"ready"), (None, b"nak")]) # PACK is NOT sent self.assertFalse(self._walker.pack_sent) def test_multi_ack_flush_end_nodone(self) -> None: # transmission ends with a flush-pkt without a done but no-done is # assumed. self._walker.lines[-1] = (None, None) self._walker.done_required = False self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b"common") self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b"common") # no done is read, but pretend it is (last 'ACK 'commit_id' '') self._walker.wants_satisified = True self.assertNextEmpty() self.assertAcks([(THREE, b"ready"), (None, b"nak"), (THREE, b"")]) # PACK is sent self.assertTrue(self._walker.pack_sent) def test_multi_ack_partial(self) -> None: self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self._impl.ack(ONE) self.assertAck(ONE, b"common") self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertAck(ONE) def test_multi_ack_flush(self) -> None: # same as ack test but contains a flush-pkt in the middle self._walker.lines = [ (b"have", TWO), (None, None), (b"have", ONE), (b"have", THREE), (b"done", None), (None, None), ] self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNak() # nak the flush-pkt self._impl.ack(ONE) self.assertAck(ONE, b"common") self.assertNextEquals(THREE) self._impl.ack(THREE) self.assertAck(THREE, b"common") self._walker.wants_satisified = True self.assertNextEquals(None) self.assertNextEmpty() self.assertAcks([(THREE, b"ready"), (None, b"nak"), (THREE, b"")]) def test_multi_ack_nak(self) -> None: self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() # Done is sent here. self.assertNextEquals(None) self.assertNextEmpty() self.assertNak() self.assertNextEmpty() self.assertTrue(self._walker.pack_sent) def test_multi_ack_nak_nodone(self) -> None: self._walker.done_required = False self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() # Done is sent here. self.assertFalse(self._walker.pack_sent) self.assertNextEquals(None) self.assertNextEmpty() self.assertTrue(self._walker.pack_sent) self.assertNak() self.assertNextEmpty() def test_multi_ack_nak_flush(self) -> None: # same as nak test but contains a flush-pkt in the middle self._walker.lines = [ (b"have", TWO), (None, None), (b"have", ONE), (b"have", THREE), (b"done", None), ] self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNak() self.assertNextEquals(THREE) self.assertNoAck() self.assertNextEquals(None) self.assertNextEmpty() self.assertNak() def test_multi_ack_stateless(self) -> None: # transmission ends with a flush-pkt self._walker.lines[-1] = (None, None) self._walker.stateless_rpc = True self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() self.assertFalse(self._walker.pack_sent) self.assertNextEquals(None) self.assertNak() self.assertNextEmpty() self.assertNoAck() self.assertFalse(self._walker.pack_sent) def test_multi_ack_stateless_nodone(self) -> None: self._walker.done_required = False # transmission ends with a flush-pkt self._walker.lines[-1] = (None, None) self._walker.stateless_rpc = True self.assertNextEquals(TWO) self.assertNoAck() self.assertNextEquals(ONE) self.assertNoAck() self.assertNextEquals(THREE) self.assertNoAck() self.assertFalse(self._walker.pack_sent) self.assertNextEquals(None) self.assertNak() self.assertNextEmpty() self.assertNoAck() # PACK will still not be sent. self.assertFalse(self._walker.pack_sent) class FileSystemBackendTests(TestCase): """Tests for FileSystemBackend.""" def setUp(self) -> None: super().setUp() self.path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.path) self.repo = Repo.init(self.path) if sys.platform == "win32": self.backend = FileSystemBackend(self.path[0] + ":" + os.sep) else: self.backend = FileSystemBackend() def test_nonexistant(self) -> None: self.assertRaises( NotGitRepository, self.backend.open_repository, "/does/not/exist/unless/foo", ) def test_absolute(self) -> None: repo = self.backend.open_repository(self.path) self.assertTrue( os.path.samefile( os.path.abspath(repo.path), os.path.abspath(self.repo.path) ) ) def test_child(self) -> None: self.assertRaises( NotGitRepository, self.backend.open_repository, os.path.join(self.path, "foo"), ) def test_bad_repo_path(self) -> None: backend = FileSystemBackend() self.assertRaises(NotGitRepository, lambda: backend.open_repository("/ups")) class DictBackendTests(TestCase): """Tests for DictBackend.""" def test_nonexistant(self) -> None: repo = MemoryRepo.init_bare([], {}) backend = DictBackend({b"/": repo}) self.assertRaises( NotGitRepository, backend.open_repository, "/does/not/exist/unless/foo", ) def test_bad_repo_path(self) -> None: repo = MemoryRepo.init_bare([], {}) backend = DictBackend({b"/": repo}) self.assertRaises(NotGitRepository, lambda: backend.open_repository("/ups")) class ServeCommandTests(TestCase): """Tests for serve_command.""" def setUp(self) -> None: super().setUp() self.backend = DictBackend({}) def serve_command(self, handler_cls, args, inf, outf): return serve_command( handler_cls, [b"test", *args], backend=self.backend, inf=inf, outf=outf, ) def test_receive_pack(self) -> None: commit = make_commit(id=ONE, parents=[], commit_time=111) self.backend.repos[b"/"] = MemoryRepo.init_bare( [commit], {b"refs/heads/master": commit.id} ) outf = BytesIO() exitcode = self.serve_command( ReceivePackHandler, [b"/"], BytesIO(b"0000"), outf ) outlines = outf.getvalue().splitlines() self.assertEqual(2, len(outlines)) self.assertEqual( b"1111111111111111111111111111111111111111 refs/heads/master", outlines[0][4:].split(b"\x00")[0], ) self.assertEqual(b"0000", outlines[-1]) self.assertEqual(0, exitcode) class UpdateServerInfoTests(TestCase): """Tests for update_server_info.""" def setUp(self) -> None: super().setUp() self.path = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.path) self.repo = Repo.init(self.path) def test_empty(self) -> None: update_server_info(self.repo) with open(os.path.join(self.path, ".git", "info", "refs"), "rb") as f: self.assertEqual(b"", f.read()) p = os.path.join(self.path, ".git", "objects", "info", "packs") with open(p, "rb") as f: self.assertEqual(b"", f.read()) def test_simple(self) -> None: commit_id = self.repo.do_commit( message=b"foo", committer=b"Joe Example ", ref=b"refs/heads/foo", ) update_server_info(self.repo) with open(os.path.join(self.path, ".git", "info", "refs"), "rb") as f: self.assertEqual(f.read(), commit_id + b"\trefs/heads/foo\n") p = os.path.join(self.path, ".git", "objects", "info", "packs") with open(p, "rb") as f: self.assertEqual(f.read(), b"") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_stash.py0000644000175100002000000000245614731042555016543 0ustar00runnerdocker# test_stash.py -- tests for stash # Copyright (C) 2018 Jelmer Vernooij # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for stashes.""" from dulwich.repo import MemoryRepo from dulwich.stash import Stash from . import TestCase class StashTests(TestCase): """Tests for stash.""" def test_obtain(self) -> None: repo = MemoryRepo() stash = Stash.from_repo(repo) self.assertIsInstance(stash, Stash) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_utils.py0000644000175100002000000000641014731042555016553 0ustar00runnerdocker# test_utils.py -- Tests for git test utilities. # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for git test utilities.""" from dulwich.object_store import MemoryObjectStore from dulwich.objects import Blob from dulwich.tests.utils import build_commit_graph, make_object from . import TestCase class BuildCommitGraphTest(TestCase): def setUp(self) -> None: super().setUp() self.store = MemoryObjectStore() def test_linear(self) -> None: c1, c2 = build_commit_graph(self.store, [[1], [2, 1]]) for obj_id in [c1.id, c2.id, c1.tree, c2.tree]: self.assertIn(obj_id, self.store) self.assertEqual([], c1.parents) self.assertEqual([c1.id], c2.parents) self.assertEqual(c1.tree, c2.tree) self.assertEqual([], self.store[c1.tree].items()) self.assertGreater(c2.commit_time, c1.commit_time) def test_merge(self) -> None: c1, c2, c3, c4 = build_commit_graph( self.store, [[1], [2, 1], [3, 1], [4, 2, 3]] ) self.assertEqual([c2.id, c3.id], c4.parents) self.assertGreater(c4.commit_time, c2.commit_time) self.assertGreater(c4.commit_time, c3.commit_time) def test_missing_parent(self) -> None: self.assertRaises( ValueError, build_commit_graph, self.store, [[1], [3, 2], [2, 1]] ) def test_trees(self) -> None: a1 = make_object(Blob, data=b"aaa1") a2 = make_object(Blob, data=b"aaa2") c1, c2 = build_commit_graph( self.store, [[1], [2, 1]], trees={1: [(b"a", a1)], 2: [(b"a", a2, 0o100644)]}, ) self.assertEqual((0o100644, a1.id), self.store[c1.tree][b"a"]) self.assertEqual((0o100644, a2.id), self.store[c2.tree][b"a"]) def test_attrs(self) -> None: c1, c2 = build_commit_graph( self.store, [[1], [2, 1]], attrs={1: {"message": b"Hooray!"}} ) self.assertEqual(b"Hooray!", c1.message) self.assertEqual(b"Commit 2", c2.message) def test_commit_time(self) -> None: c1, c2, c3 = build_commit_graph( self.store, [[1], [2, 1], [3, 2]], attrs={1: {"commit_time": 124}, 2: {"commit_time": 123}}, ) self.assertEqual(124, c1.commit_time) self.assertEqual(123, c2.commit_time) self.assertTrue(c2.commit_time < c1.commit_time < c3.commit_time) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_walk.py0000644000175100002000000005741114731042555016360 0ustar00runnerdocker# test_walk.py -- Tests for commit walking functionality. # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for commit walking functionality.""" from itertools import permutations from unittest import expectedFailure from dulwich.diff_tree import CHANGE_MODIFY, CHANGE_RENAME, RenameDetector, TreeChange from dulwich.errors import MissingCommitError from dulwich.object_store import MemoryObjectStore from dulwich.objects import Blob, Commit from dulwich.tests.utils import F, build_commit_graph, make_object, make_tag from dulwich.walk import ORDER_TOPO, WalkEntry, Walker, _topo_reorder from . import TestCase class TestWalkEntry: def __init__(self, commit, changes) -> None: self.commit = commit self.changes = changes def __repr__(self) -> str: return f"" def __eq__(self, other): if not isinstance(other, WalkEntry) or self.commit != other.commit: return False if self.changes is None: return True return self.changes == other.changes() class WalkerTest(TestCase): def setUp(self) -> None: super().setUp() self.store = MemoryObjectStore() def make_commits(self, commit_spec, **kwargs): times = kwargs.pop("times", []) attrs = kwargs.pop("attrs", {}) for i, t in enumerate(times): attrs.setdefault(i + 1, {})["commit_time"] = t return build_commit_graph(self.store, commit_spec, attrs=attrs, **kwargs) def make_linear_commits(self, num_commits, **kwargs): commit_spec = [] for i in range(1, num_commits + 1): c = [i] if i > 1: c.append(i - 1) commit_spec.append(c) return self.make_commits(commit_spec, **kwargs) def assertWalkYields(self, expected, *args, **kwargs) -> None: walker = Walker(self.store, *args, **kwargs) expected = list(expected) for i, entry in enumerate(expected): if isinstance(entry, Commit): expected[i] = TestWalkEntry(entry, None) actual = list(walker) self.assertEqual(expected, actual) def test_tag(self) -> None: c1, c2, c3 = self.make_linear_commits(3) t2 = make_tag(target=c2) self.store.add_object(t2) self.assertWalkYields([c2, c1], [t2.id]) def test_linear(self) -> None: c1, c2, c3 = self.make_linear_commits(3) self.assertWalkYields([c1], [c1.id]) self.assertWalkYields([c2, c1], [c2.id]) self.assertWalkYields([c3, c2, c1], [c3.id]) self.assertWalkYields([c3, c2, c1], [c3.id, c1.id]) self.assertWalkYields([c3, c2], [c3.id], exclude=[c1.id]) self.assertWalkYields([c3, c2], [c3.id, c1.id], exclude=[c1.id]) self.assertWalkYields([c3], [c3.id, c1.id], exclude=[c2.id]) def test_missing(self) -> None: cs = list(reversed(self.make_linear_commits(20))) self.assertWalkYields(cs, [cs[0].id]) # Exactly how close we can get to a missing commit depends on our # implementation (in particular the choice of _MAX_EXTRA_COMMITS), but # we should at least be able to walk some history in a broken repo. del self.store[cs[-1].id] for i in range(1, 11): self.assertWalkYields(cs[:i], [cs[0].id], max_entries=i) self.assertRaises(MissingCommitError, Walker, self.store, [cs[-1].id]) def test_branch(self) -> None: c1, x2, x3, y4 = self.make_commits([[1], [2, 1], [3, 2], [4, 1]]) self.assertWalkYields([x3, x2, c1], [x3.id]) self.assertWalkYields([y4, c1], [y4.id]) self.assertWalkYields([y4, x2, c1], [y4.id, x2.id]) self.assertWalkYields([y4, x2], [y4.id, x2.id], exclude=[c1.id]) self.assertWalkYields([y4, x3], [y4.id, x3.id], exclude=[x2.id]) self.assertWalkYields([y4], [y4.id], exclude=[x3.id]) self.assertWalkYields([x3, x2], [x3.id], exclude=[y4.id]) def test_merge(self) -> None: c1, c2, c3, c4 = self.make_commits([[1], [2, 1], [3, 1], [4, 2, 3]]) self.assertWalkYields([c4, c3, c2, c1], [c4.id]) self.assertWalkYields([c3, c1], [c3.id]) self.assertWalkYields([c2, c1], [c2.id]) self.assertWalkYields([c4, c3], [c4.id], exclude=[c2.id]) self.assertWalkYields([c4, c2], [c4.id], exclude=[c3.id]) def test_merge_of_new_branch_from_old_base(self) -> None: # The commit on the branch was made at a time after any of the # commits on master, but the branch was from an older commit. # See also test_merge_of_old_branch self.maxDiff = None c1, c2, c3, c4, c5 = self.make_commits( [[1], [2, 1], [3, 2], [4, 1], [5, 3, 4]], times=[1, 2, 3, 4, 5], ) self.assertWalkYields([c5, c4, c3, c2, c1], [c5.id]) self.assertWalkYields([c3, c2, c1], [c3.id]) self.assertWalkYields([c2, c1], [c2.id]) @expectedFailure def test_merge_of_old_branch(self) -> None: # The commit on the branch was made at a time before any of # the commits on master, but it was merged into master after # those commits. # See also test_merge_of_new_branch_from_old_base self.maxDiff = None c1, c2, c3, c4, c5 = self.make_commits( [[1], [2, 1], [3, 2], [4, 1], [5, 3, 4]], times=[1, 3, 4, 2, 5], ) self.assertWalkYields([c5, c4, c3, c2, c1], [c5.id]) self.assertWalkYields([c3, c2, c1], [c3.id]) self.assertWalkYields([c2, c1], [c2.id]) def test_reverse(self) -> None: c1, c2, c3 = self.make_linear_commits(3) self.assertWalkYields([c1, c2, c3], [c3.id], reverse=True) def test_max_entries(self) -> None: c1, c2, c3 = self.make_linear_commits(3) self.assertWalkYields([c3, c2, c1], [c3.id], max_entries=3) self.assertWalkYields([c3, c2], [c3.id], max_entries=2) self.assertWalkYields([c3], [c3.id], max_entries=1) def test_reverse_after_max_entries(self) -> None: c1, c2, c3 = self.make_linear_commits(3) self.assertWalkYields([c1, c2, c3], [c3.id], max_entries=3, reverse=True) self.assertWalkYields([c2, c3], [c3.id], max_entries=2, reverse=True) self.assertWalkYields([c3], [c3.id], max_entries=1, reverse=True) def test_changes_one_parent(self) -> None: blob_a1 = make_object(Blob, data=b"a1") blob_a2 = make_object(Blob, data=b"a2") blob_b2 = make_object(Blob, data=b"b2") c1, c2 = self.make_linear_commits( 2, trees={ 1: [(b"a", blob_a1)], 2: [(b"a", blob_a2), (b"b", blob_b2)], }, ) e1 = TestWalkEntry(c1, [TreeChange.add((b"a", F, blob_a1.id))]) e2 = TestWalkEntry( c2, [ TreeChange(CHANGE_MODIFY, (b"a", F, blob_a1.id), (b"a", F, blob_a2.id)), TreeChange.add((b"b", F, blob_b2.id)), ], ) self.assertWalkYields([e2, e1], [c2.id]) def test_changes_multiple_parents(self) -> None: blob_a1 = make_object(Blob, data=b"a1") blob_b2 = make_object(Blob, data=b"b2") blob_a3 = make_object(Blob, data=b"a3") c1, c2, c3 = self.make_commits( [[1], [2], [3, 1, 2]], trees={ 1: [(b"a", blob_a1)], 2: [(b"b", blob_b2)], 3: [(b"a", blob_a3), (b"b", blob_b2)], }, ) # a is a modify/add conflict and b is not conflicted. changes = [ [ TreeChange(CHANGE_MODIFY, (b"a", F, blob_a1.id), (b"a", F, blob_a3.id)), TreeChange.add((b"a", F, blob_a3.id)), ] ] self.assertWalkYields( [TestWalkEntry(c3, changes)], [c3.id], exclude=[c1.id, c2.id] ) def test_path_matches(self) -> None: walker = Walker(None, [], paths=[b"foo", b"bar", b"baz/quux"]) self.assertTrue(walker._path_matches(b"foo")) self.assertTrue(walker._path_matches(b"foo/a")) self.assertTrue(walker._path_matches(b"foo/a/b")) self.assertTrue(walker._path_matches(b"bar")) self.assertTrue(walker._path_matches(b"baz/quux")) self.assertTrue(walker._path_matches(b"baz/quux/a")) self.assertFalse(walker._path_matches(None)) self.assertFalse(walker._path_matches(b"oops")) self.assertFalse(walker._path_matches(b"fool")) self.assertFalse(walker._path_matches(b"baz")) self.assertFalse(walker._path_matches(b"baz/quu")) def test_paths(self) -> None: blob_a1 = make_object(Blob, data=b"a1") blob_b2 = make_object(Blob, data=b"b2") blob_a3 = make_object(Blob, data=b"a3") blob_b3 = make_object(Blob, data=b"b3") c1, c2, c3 = self.make_linear_commits( 3, trees={ 1: [(b"a", blob_a1)], 2: [(b"a", blob_a1), (b"x/b", blob_b2)], 3: [(b"a", blob_a3), (b"x/b", blob_b3)], }, ) self.assertWalkYields([c3, c2, c1], [c3.id]) self.assertWalkYields([c3, c1], [c3.id], paths=[b"a"]) self.assertWalkYields([c3, c2], [c3.id], paths=[b"x/b"]) # All changes are included, not just for requested paths. changes = [ TreeChange(CHANGE_MODIFY, (b"a", F, blob_a1.id), (b"a", F, blob_a3.id)), TreeChange(CHANGE_MODIFY, (b"x/b", F, blob_b2.id), (b"x/b", F, blob_b3.id)), ] self.assertWalkYields( [TestWalkEntry(c3, changes)], [c3.id], max_entries=1, paths=[b"a"] ) def test_paths_subtree(self) -> None: blob_a = make_object(Blob, data=b"a") blob_b = make_object(Blob, data=b"b") c1, c2, c3 = self.make_linear_commits( 3, trees={ 1: [(b"x/a", blob_a)], 2: [(b"b", blob_b), (b"x/a", blob_a)], 3: [(b"b", blob_b), (b"x/a", blob_a), (b"x/b", blob_b)], }, ) self.assertWalkYields([c2], [c3.id], paths=[b"b"]) self.assertWalkYields([c3, c1], [c3.id], paths=[b"x"]) def test_paths_max_entries(self) -> None: blob_a = make_object(Blob, data=b"a") blob_b = make_object(Blob, data=b"b") c1, c2 = self.make_linear_commits( 2, trees={1: [(b"a", blob_a)], 2: [(b"a", blob_a), (b"b", blob_b)]} ) self.assertWalkYields([c2], [c2.id], paths=[b"b"], max_entries=1) self.assertWalkYields([c1], [c1.id], paths=[b"a"], max_entries=1) def test_paths_merge(self) -> None: blob_a1 = make_object(Blob, data=b"a1") blob_a2 = make_object(Blob, data=b"a2") blob_a3 = make_object(Blob, data=b"a3") x1, y2, m3, m4 = self.make_commits( [[1], [2], [3, 1, 2], [4, 1, 2]], trees={ 1: [(b"a", blob_a1)], 2: [(b"a", blob_a2)], 3: [(b"a", blob_a3)], 4: [(b"a", blob_a1)], }, ) # Non-conflicting self.assertWalkYields([m3, y2, x1], [m3.id], paths=[b"a"]) self.assertWalkYields([y2, x1], [m4.id], paths=[b"a"]) def test_changes_with_renames(self) -> None: blob = make_object(Blob, data=b"blob") c1, c2 = self.make_linear_commits( 2, trees={1: [(b"a", blob)], 2: [(b"b", blob)]} ) entry_a = (b"a", F, blob.id) entry_b = (b"b", F, blob.id) changes_without_renames = [ TreeChange.delete(entry_a), TreeChange.add(entry_b), ] changes_with_renames = [TreeChange(CHANGE_RENAME, entry_a, entry_b)] self.assertWalkYields( [TestWalkEntry(c2, changes_without_renames)], [c2.id], max_entries=1, ) detector = RenameDetector(self.store) self.assertWalkYields( [TestWalkEntry(c2, changes_with_renames)], [c2.id], max_entries=1, rename_detector=detector, ) def test_follow_rename(self) -> None: blob = make_object(Blob, data=b"blob") names = [b"a", b"a", b"b", b"b", b"c", b"c"] trees = {i + 1: [(n, blob, F)] for i, n in enumerate(names)} c1, c2, c3, c4, c5, c6 = self.make_linear_commits(6, trees=trees) self.assertWalkYields([c5], [c6.id], paths=[b"c"]) def e(n): return (n, F, blob.id) self.assertWalkYields( [ TestWalkEntry(c5, [TreeChange(CHANGE_RENAME, e(b"b"), e(b"c"))]), TestWalkEntry(c3, [TreeChange(CHANGE_RENAME, e(b"a"), e(b"b"))]), TestWalkEntry(c1, [TreeChange.add(e(b"a"))]), ], [c6.id], paths=[b"c"], follow=True, ) def test_follow_rename_remove_path(self) -> None: blob = make_object(Blob, data=b"blob") _, _, _, c4, c5, c6 = self.make_linear_commits( 6, trees={ 1: [(b"a", blob), (b"c", blob)], 2: [], 3: [], 4: [(b"b", blob)], 5: [(b"a", blob)], 6: [(b"c", blob)], }, ) def e(n): return (n, F, blob.id) # Once the path changes to b, we aren't interested in a or c anymore. self.assertWalkYields( [ TestWalkEntry(c6, [TreeChange(CHANGE_RENAME, e(b"a"), e(b"c"))]), TestWalkEntry(c5, [TreeChange(CHANGE_RENAME, e(b"b"), e(b"a"))]), TestWalkEntry(c4, [TreeChange.add(e(b"b"))]), ], [c6.id], paths=[b"c"], follow=True, ) def test_since(self) -> None: c1, c2, c3 = self.make_linear_commits(3) self.assertWalkYields([c3, c2, c1], [c3.id], since=-1) self.assertWalkYields([c3, c2, c1], [c3.id], since=0) self.assertWalkYields([c3, c2], [c3.id], since=1) self.assertWalkYields([c3, c2], [c3.id], since=99) self.assertWalkYields([c3, c2], [c3.id], since=100) self.assertWalkYields([c3], [c3.id], since=101) self.assertWalkYields([c3], [c3.id], since=199) self.assertWalkYields([c3], [c3.id], since=200) self.assertWalkYields([], [c3.id], since=201) self.assertWalkYields([], [c3.id], since=300) def test_until(self) -> None: c1, c2, c3 = self.make_linear_commits(3) self.assertWalkYields([], [c3.id], until=-1) self.assertWalkYields([c1], [c3.id], until=0) self.assertWalkYields([c1], [c3.id], until=1) self.assertWalkYields([c1], [c3.id], until=99) self.assertWalkYields([c2, c1], [c3.id], until=100) self.assertWalkYields([c2, c1], [c3.id], until=101) self.assertWalkYields([c2, c1], [c3.id], until=199) self.assertWalkYields([c3, c2, c1], [c3.id], until=200) self.assertWalkYields([c3, c2, c1], [c3.id], until=201) self.assertWalkYields([c3, c2, c1], [c3.id], until=300) def test_since_until(self) -> None: c1, c2, c3 = self.make_linear_commits(3) self.assertWalkYields([], [c3.id], since=100, until=99) self.assertWalkYields([c3, c2, c1], [c3.id], since=-1, until=201) self.assertWalkYields([c2], [c3.id], since=100, until=100) self.assertWalkYields([c2], [c3.id], since=50, until=150) def test_since_over_scan(self) -> None: commits = self.make_linear_commits(11, times=[9, 0, 1, 2, 3, 4, 5, 8, 6, 7, 9]) c8, _, c10, c11 = commits[-4:] del self.store[commits[0].id] # c9 is older than we want to walk, but is out of order with its # parent, so we need to walk past it to get to c8. # c1 would also match, but we've deleted it, and it should get pruned # even with over-scanning. self.assertWalkYields([c11, c10, c8], [c11.id], since=7) def assertTopoOrderEqual(self, expected_commits, commits) -> None: entries = [TestWalkEntry(c, None) for c in commits] actual_ids = [e.commit.id for e in list(_topo_reorder(entries))] self.assertEqual([c.id for c in expected_commits], actual_ids) def test_topo_reorder_linear(self) -> None: commits = self.make_linear_commits(5) commits.reverse() for perm in permutations(commits): self.assertTopoOrderEqual(commits, perm) def test_topo_reorder_multiple_parents(self) -> None: c1, c2, c3 = self.make_commits([[1], [2], [3, 1, 2]]) # Already sorted, so totally FIFO. self.assertTopoOrderEqual([c3, c2, c1], [c3, c2, c1]) self.assertTopoOrderEqual([c3, c1, c2], [c3, c1, c2]) # c3 causes one parent to be yielded. self.assertTopoOrderEqual([c3, c2, c1], [c2, c3, c1]) self.assertTopoOrderEqual([c3, c1, c2], [c1, c3, c2]) # c3 causes both parents to be yielded. self.assertTopoOrderEqual([c3, c2, c1], [c1, c2, c3]) self.assertTopoOrderEqual([c3, c2, c1], [c2, c1, c3]) def test_topo_reorder_multiple_children(self) -> None: c1, c2, c3 = self.make_commits([[1], [2, 1], [3, 1]]) # c2 and c3 are FIFO but c1 moves to the end. self.assertTopoOrderEqual([c3, c2, c1], [c3, c2, c1]) self.assertTopoOrderEqual([c3, c2, c1], [c3, c1, c2]) self.assertTopoOrderEqual([c3, c2, c1], [c1, c3, c2]) self.assertTopoOrderEqual([c2, c3, c1], [c2, c3, c1]) self.assertTopoOrderEqual([c2, c3, c1], [c2, c1, c3]) self.assertTopoOrderEqual([c2, c3, c1], [c1, c2, c3]) def test_out_of_order_children(self) -> None: c1, c2, c3, c4, c5 = self.make_commits( [[1], [2, 1], [3, 2], [4, 1], [5, 3, 4]], times=[2, 1, 3, 4, 5] ) self.assertWalkYields([c5, c4, c3, c1, c2], [c5.id]) self.assertWalkYields([c5, c4, c3, c2, c1], [c5.id], order=ORDER_TOPO) def test_out_of_order_with_exclude(self) -> None: # Create the following graph: # c1-------x2---m6 # \ / # \-y3--y4-/--y5 # Due to skew, y5 is the oldest commit. c1, x2, y3, y4, y5, m6 = self.make_commits( [[1], [2, 1], [3, 1], [4, 3], [5, 4], [6, 2, 4]], times=[2, 3, 4, 5, 1, 6], ) self.assertWalkYields([m6, y4, y3, x2, c1], [m6.id]) # Ensure that c1..y4 get excluded even though they're popped from the # priority queue long before y5. self.assertWalkYields([m6, x2], [m6.id], exclude=[y5.id]) def test_empty_walk(self) -> None: c1, c2, c3 = self.make_linear_commits(3) self.assertWalkYields([], [c3.id], exclude=[c3.id]) class WalkEntryTest(TestCase): def setUp(self) -> None: super().setUp() self.store = MemoryObjectStore() def make_commits(self, commit_spec, **kwargs): times = kwargs.pop("times", []) attrs = kwargs.pop("attrs", {}) for i, t in enumerate(times): attrs.setdefault(i + 1, {})["commit_time"] = t return build_commit_graph(self.store, commit_spec, attrs=attrs, **kwargs) def make_linear_commits(self, num_commits, **kwargs): commit_spec = [] for i in range(1, num_commits + 1): c = [i] if i > 1: c.append(i - 1) commit_spec.append(c) return self.make_commits(commit_spec, **kwargs) def test_all_changes(self) -> None: # Construct a commit with 2 files in different subdirectories. blob_a = make_object(Blob, data=b"a") blob_b = make_object(Blob, data=b"b") c1 = self.make_linear_commits( 1, trees={1: [(b"x/a", blob_a), (b"y/b", blob_b)]}, )[0] # Get the WalkEntry for the commit. walker = Walker(self.store, c1.id) walker_entry = next(iter(walker)) changes = walker_entry.changes() # Compare the changes with the expected values. entry_a = (b"x/a", F, blob_a.id) entry_b = (b"y/b", F, blob_b.id) self.assertEqual( [TreeChange.add(entry_a), TreeChange.add(entry_b)], changes, ) def test_all_with_merge(self) -> None: blob_a = make_object(Blob, data=b"a") blob_a2 = make_object(Blob, data=b"a2") blob_b = make_object(Blob, data=b"b") blob_b2 = make_object(Blob, data=b"b2") x1, y2, m3 = self.make_commits( [[1], [2], [3, 1, 2]], trees={ 1: [(b"x/a", blob_a)], 2: [(b"y/b", blob_b)], 3: [(b"x/a", blob_a2), (b"y/b", blob_b2)], }, ) # Get the WalkEntry for the merge commit. walker = Walker(self.store, m3.id) entries = list(walker) walker_entry = entries[0] self.assertEqual(walker_entry.commit.id, m3.id) changes = walker_entry.changes() self.assertEqual(2, len(changes)) entry_a = (b"x/a", F, blob_a.id) entry_a2 = (b"x/a", F, blob_a2.id) entry_b = (b"y/b", F, blob_b.id) entry_b2 = (b"y/b", F, blob_b2.id) self.assertEqual( [ [ TreeChange(CHANGE_MODIFY, entry_a, entry_a2), TreeChange.add(entry_a2), ], [ TreeChange.add(entry_b2), TreeChange(CHANGE_MODIFY, entry_b, entry_b2), ], ], changes, ) def test_filter_changes(self) -> None: # Construct a commit with 2 files in different subdirectories. blob_a = make_object(Blob, data=b"a") blob_b = make_object(Blob, data=b"b") c1 = self.make_linear_commits( 1, trees={1: [(b"x/a", blob_a), (b"y/b", blob_b)]}, )[0] # Get the WalkEntry for the commit. walker = Walker(self.store, c1.id) walker_entry = next(iter(walker)) changes = walker_entry.changes(path_prefix=b"x") # Compare the changes with the expected values. entry_a = (b"a", F, blob_a.id) self.assertEqual( [TreeChange.add(entry_a)], changes, ) def test_filter_with_merge(self) -> None: blob_a = make_object(Blob, data=b"a") blob_a2 = make_object(Blob, data=b"a2") blob_b = make_object(Blob, data=b"b") blob_b2 = make_object(Blob, data=b"b2") x1, y2, m3 = self.make_commits( [[1], [2], [3, 1, 2]], trees={ 1: [(b"x/a", blob_a)], 2: [(b"y/b", blob_b)], 3: [(b"x/a", blob_a2), (b"y/b", blob_b2)], }, ) # Get the WalkEntry for the merge commit. walker = Walker(self.store, m3.id) entries = list(walker) walker_entry = entries[0] self.assertEqual(walker_entry.commit.id, m3.id) changes = walker_entry.changes(b"x") self.assertEqual(1, len(changes)) entry_a = (b"a", F, blob_a.id) entry_a2 = (b"a", F, blob_a2.id) self.assertEqual( [[TreeChange(CHANGE_MODIFY, entry_a, entry_a2)]], changes, ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tests/test_web.py0000644000175100002000000004767314731042555016210 0ustar00runnerdocker# test_web.py -- Tests for the git HTTP server # Copyright (C) 2010 Google, Inc. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # for a copy of the GNU General Public License # and for a copy of the Apache # License, Version 2.0. # """Tests for the Git HTTP server.""" import gzip import os import re from io import BytesIO from typing import NoReturn from dulwich.object_store import MemoryObjectStore from dulwich.objects import Blob from dulwich.repo import BaseRepo, MemoryRepo from dulwich.server import DictBackend from dulwich.tests.utils import make_object, make_tag from dulwich.web import ( HTTP_ERROR, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_OK, GunzipFilter, HTTPGitApplication, HTTPGitRequest, _LengthLimitedFile, get_idx_file, get_info_packs, get_info_refs, get_loose_object, get_pack_file, get_text_file, handle_service_request, send_file, ) from . import TestCase class MinimalistWSGIInputStream: """WSGI input stream with no 'seek()' and 'tell()' methods.""" def __init__(self, data) -> None: self.data = data self.pos = 0 def read(self, howmuch): start = self.pos end = self.pos + howmuch if start >= len(self.data): return b"" self.pos = end return self.data[start:end] class MinimalistWSGIInputStream2(MinimalistWSGIInputStream): """WSGI input stream with no *working* 'seek()' and 'tell()' methods.""" def seek(self, pos) -> NoReturn: raise NotImplementedError def tell(self) -> NoReturn: raise NotImplementedError class TestHTTPGitRequest(HTTPGitRequest): """HTTPGitRequest with overridden methods to help test caching.""" def __init__(self, *args, **kwargs) -> None: HTTPGitRequest.__init__(self, *args, **kwargs) self.cached = None def nocache(self) -> None: self.cached = False def cache_forever(self) -> None: self.cached = True class WebTestCase(TestCase): """Base TestCase with useful instance vars and utility functions.""" _req_class: type[HTTPGitRequest] = TestHTTPGitRequest def setUp(self) -> None: super().setUp() self._environ = {} self._req = self._req_class( self._environ, self._start_response, handlers=self._handlers() ) self._status = None self._headers = [] self._output = BytesIO() def _start_response(self, status, headers): self._status = status self._headers = list(headers) return self._output.write def _handlers(self) -> None: return None def assertContentTypeEquals(self, expected) -> None: self.assertIn(("Content-Type", expected), self._headers) def _test_backend(objects, refs=None, named_files=None): if not refs: refs = {} if not named_files: named_files = {} repo = MemoryRepo.init_bare(objects, refs) for path, contents in named_files.items(): repo._put_named_file(path, contents) return DictBackend({"/": repo}) class DumbHandlersTestCase(WebTestCase): def test_send_file_not_found(self) -> None: list(send_file(self._req, None, "text/plain")) self.assertEqual(HTTP_NOT_FOUND, self._status) def test_send_file(self) -> None: f = BytesIO(b"foobar") output = b"".join(send_file(self._req, f, "some/thing")) self.assertEqual(b"foobar", output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals("some/thing") self.assertTrue(f.closed) def test_send_file_buffered(self) -> None: bufsize = 10240 xs = b"x" * bufsize f = BytesIO(2 * xs) self.assertEqual([xs, xs], list(send_file(self._req, f, "some/thing"))) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals("some/thing") self.assertTrue(f.closed) def test_send_file_error(self) -> None: class TestFile: def __init__(self, exc_class) -> None: self.closed = False self._exc_class = exc_class def read(self, size=-1) -> NoReturn: raise self._exc_class def close(self) -> None: self.closed = True f = TestFile(IOError) list(send_file(self._req, f, "some/thing")) self.assertEqual(HTTP_ERROR, self._status) self.assertTrue(f.closed) self.assertFalse(self._req.cached) # non-IOErrors are reraised f = TestFile(AttributeError) self.assertRaises(AttributeError, list, send_file(self._req, f, "some/thing")) self.assertTrue(f.closed) self.assertFalse(self._req.cached) def test_get_text_file(self) -> None: backend = _test_backend([], named_files={"description": b"foo"}) mat = re.search(".*", "description") output = b"".join(get_text_file(self._req, backend, mat)) self.assertEqual(b"foo", output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals("text/plain") self.assertFalse(self._req.cached) def test_get_loose_object(self) -> None: blob = make_object(Blob, data=b"foo") backend = _test_backend([blob]) mat = re.search("^(..)(.{38})$", blob.id.decode("ascii")) output = b"".join(get_loose_object(self._req, backend, mat)) self.assertEqual(blob.as_legacy_object(), output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals("application/x-git-loose-object") self.assertTrue(self._req.cached) def test_get_loose_object_missing(self) -> None: mat = re.search("^(..)(.{38})$", "1" * 40) list(get_loose_object(self._req, _test_backend([]), mat)) self.assertEqual(HTTP_NOT_FOUND, self._status) def test_get_loose_object_error(self) -> None: blob = make_object(Blob, data=b"foo") backend = _test_backend([blob]) mat = re.search("^(..)(.{38})$", blob.id.decode("ascii")) def as_legacy_object_error(self) -> NoReturn: raise OSError self.addCleanup(setattr, Blob, "as_legacy_object", Blob.as_legacy_object) Blob.as_legacy_object = as_legacy_object_error list(get_loose_object(self._req, backend, mat)) self.assertEqual(HTTP_ERROR, self._status) def test_get_pack_file(self) -> None: pack_name = os.path.join("objects", "pack", "pack-%s.pack" % ("1" * 40)) backend = _test_backend([], named_files={pack_name: b"pack contents"}) mat = re.search(".*", pack_name) output = b"".join(get_pack_file(self._req, backend, mat)) self.assertEqual(b"pack contents", output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals("application/x-git-packed-objects") self.assertTrue(self._req.cached) def test_get_idx_file(self) -> None: idx_name = os.path.join("objects", "pack", "pack-%s.idx" % ("1" * 40)) backend = _test_backend([], named_files={idx_name: b"idx contents"}) mat = re.search(".*", idx_name) output = b"".join(get_idx_file(self._req, backend, mat)) self.assertEqual(b"idx contents", output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals("application/x-git-packed-objects-toc") self.assertTrue(self._req.cached) def test_get_info_refs(self) -> None: self._environ["QUERY_STRING"] = "" blob1 = make_object(Blob, data=b"1") blob2 = make_object(Blob, data=b"2") blob3 = make_object(Blob, data=b"3") tag1 = make_tag(blob2, name=b"tag-tag") objects = [blob1, blob2, blob3, tag1] refs = { b"HEAD": b"000", b"refs/heads/master": blob1.id, b"refs/tags/tag-tag": tag1.id, b"refs/tags/blob-tag": blob3.id, } backend = _test_backend(objects, refs=refs) mat = re.search(".*", "//info/refs") self.assertEqual( [ blob1.id + b"\trefs/heads/master\n", blob3.id + b"\trefs/tags/blob-tag\n", tag1.id + b"\trefs/tags/tag-tag\n", blob2.id + b"\trefs/tags/tag-tag^{}\n", ], list(get_info_refs(self._req, backend, mat)), ) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals("text/plain") self.assertFalse(self._req.cached) def test_get_info_refs_not_found(self) -> None: self._environ["QUERY_STRING"] = "" objects = [] refs = {} backend = _test_backend(objects, refs=refs) mat = re.search("info/refs", "/foo/info/refs") self.assertEqual( [b"No git repository was found at /foo"], list(get_info_refs(self._req, backend, mat)), ) self.assertEqual(HTTP_NOT_FOUND, self._status) self.assertContentTypeEquals("text/plain") def test_get_info_packs(self) -> None: class TestPackData: def __init__(self, sha) -> None: self.filename = f"pack-{sha}.pack" class TestPack: def __init__(self, sha) -> None: self.data = TestPackData(sha) packs = [TestPack(str(i) * 40) for i in range(1, 4)] class TestObjectStore(MemoryObjectStore): # property must be overridden, can't be assigned @property def packs(self): return packs store = TestObjectStore() repo = BaseRepo(store, None) backend = DictBackend({"/": repo}) mat = re.search(".*", "//info/packs") output = b"".join(get_info_packs(self._req, backend, mat)) expected = b"".join( [(b"P pack-" + s + b".pack\n") for s in [b"1" * 40, b"2" * 40, b"3" * 40]] ) self.assertEqual(expected, output) self.assertEqual(HTTP_OK, self._status) self.assertContentTypeEquals("text/plain") self.assertFalse(self._req.cached) class SmartHandlersTestCase(WebTestCase): class _TestUploadPackHandler: def __init__( self, backend, args, proto, stateless_rpc=None, advertise_refs=False, ) -> None: self.args = args self.proto = proto self.stateless_rpc = stateless_rpc self.advertise_refs = advertise_refs def handle(self) -> None: self.proto.write(b"handled input: " + self.proto.recv(1024)) def _make_handler(self, *args, **kwargs): self._handler = self._TestUploadPackHandler(*args, **kwargs) return self._handler def _handlers(self): return {b"git-upload-pack": self._make_handler} def test_handle_service_request_unknown(self) -> None: mat = re.search(".*", "/git-evil-handler") content = list(handle_service_request(self._req, "backend", mat)) self.assertEqual(HTTP_FORBIDDEN, self._status) self.assertNotIn(b"git-evil-handler", b"".join(content)) self.assertFalse(self._req.cached) def _run_handle_service_request(self, content_length=None) -> None: self._environ["wsgi.input"] = BytesIO(b"foo") if content_length is not None: self._environ["CONTENT_LENGTH"] = content_length mat = re.search(".*", "/git-upload-pack") class Backend: def open_repository(self, path) -> None: return None handler_output = b"".join(handle_service_request(self._req, Backend(), mat)) write_output = self._output.getvalue() # Ensure all output was written via the write callback. self.assertEqual(b"", handler_output) self.assertEqual(b"handled input: foo", write_output) self.assertContentTypeEquals("application/x-git-upload-pack-result") self.assertFalse(self._handler.advertise_refs) self.assertTrue(self._handler.stateless_rpc) self.assertFalse(self._req.cached) def test_handle_service_request(self) -> None: self._run_handle_service_request() def test_handle_service_request_with_length(self) -> None: self._run_handle_service_request(content_length="3") def test_handle_service_request_empty_length(self) -> None: self._run_handle_service_request(content_length="") def test_get_info_refs_unknown(self) -> None: self._environ["QUERY_STRING"] = "service=git-evil-handler" class Backend: def open_repository(self, url) -> None: return None mat = re.search(".*", "/git-evil-pack") content = list(get_info_refs(self._req, Backend(), mat)) self.assertNotIn(b"git-evil-handler", b"".join(content)) self.assertEqual(HTTP_FORBIDDEN, self._status) self.assertFalse(self._req.cached) def test_get_info_refs(self) -> None: self._environ["wsgi.input"] = BytesIO(b"foo") self._environ["QUERY_STRING"] = "service=git-upload-pack" class Backend: def open_repository(self, url) -> None: return None mat = re.search(".*", "/git-upload-pack") handler_output = b"".join(get_info_refs(self._req, Backend(), mat)) write_output = self._output.getvalue() self.assertEqual( ( b"001e# service=git-upload-pack\n" b"0000" # input is ignored by the handler b"handled input: " ), write_output, ) # Ensure all output was written via the write callback. self.assertEqual(b"", handler_output) self.assertTrue(self._handler.advertise_refs) self.assertTrue(self._handler.stateless_rpc) self.assertFalse(self._req.cached) class LengthLimitedFileTestCase(TestCase): def test_no_cutoff(self) -> None: f = _LengthLimitedFile(BytesIO(b"foobar"), 1024) self.assertEqual(b"foobar", f.read()) def test_cutoff(self) -> None: f = _LengthLimitedFile(BytesIO(b"foobar"), 3) self.assertEqual(b"foo", f.read()) self.assertEqual(b"", f.read()) def test_multiple_reads(self) -> None: f = _LengthLimitedFile(BytesIO(b"foobar"), 3) self.assertEqual(b"fo", f.read(2)) self.assertEqual(b"o", f.read(2)) self.assertEqual(b"", f.read()) class HTTPGitRequestTestCase(WebTestCase): # This class tests the contents of the actual cache headers _req_class = HTTPGitRequest def test_not_found(self) -> None: self._req.cache_forever() # cache headers should be discarded message = "Something not found" self.assertEqual(message.encode("ascii"), self._req.not_found(message)) self.assertEqual(HTTP_NOT_FOUND, self._status) self.assertEqual({("Content-Type", "text/plain")}, set(self._headers)) def test_forbidden(self) -> None: self._req.cache_forever() # cache headers should be discarded message = "Something not found" self.assertEqual(message.encode("ascii"), self._req.forbidden(message)) self.assertEqual(HTTP_FORBIDDEN, self._status) self.assertEqual({("Content-Type", "text/plain")}, set(self._headers)) def test_respond_ok(self) -> None: self._req.respond() self.assertEqual([], self._headers) self.assertEqual(HTTP_OK, self._status) def test_respond(self) -> None: self._req.nocache() self._req.respond( status=402, content_type="some/type", headers=[("X-Foo", "foo"), ("X-Bar", "bar")], ) self.assertEqual( { ("X-Foo", "foo"), ("X-Bar", "bar"), ("Content-Type", "some/type"), ("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"), ("Pragma", "no-cache"), ("Cache-Control", "no-cache, max-age=0, must-revalidate"), }, set(self._headers), ) self.assertEqual(402, self._status) class HTTPGitApplicationTestCase(TestCase): def setUp(self) -> None: super().setUp() self._app = HTTPGitApplication("backend") self._environ = { "PATH_INFO": "/foo", "REQUEST_METHOD": "GET", } def _test_handler(self, req, backend, mat) -> str: # tests interface used by all handlers self.assertEqual(self._environ, req.environ) self.assertEqual("backend", backend) self.assertEqual("/foo", mat.group(0)) return "output" def _add_handler(self, app) -> None: req = self._environ["REQUEST_METHOD"] app.services = { (req, re.compile("/foo$")): self._test_handler, } def test_call(self) -> None: self._add_handler(self._app) self.assertEqual("output", self._app(self._environ, None)) def test_fallback_app(self) -> None: def test_app(environ, start_response) -> str: return "output" app = HTTPGitApplication("backend", fallback_app=test_app) self.assertEqual("output", app(self._environ, None)) class GunzipTestCase(HTTPGitApplicationTestCase): __doc__ = """TestCase for testing the GunzipFilter, ensuring the wsgi.input is correctly decompressed and headers are corrected. """ example_text = __doc__.encode("ascii") def setUp(self) -> None: super().setUp() self._app = GunzipFilter(self._app) self._environ["HTTP_CONTENT_ENCODING"] = "gzip" self._environ["REQUEST_METHOD"] = "POST" def _get_zstream(self, text): zstream = BytesIO() zfile = gzip.GzipFile(fileobj=zstream, mode="wb") zfile.write(text) zfile.close() zlength = zstream.tell() zstream.seek(0) return zstream, zlength def _test_call(self, orig, zstream, zlength) -> None: self._add_handler(self._app.app) self.assertLess(zlength, len(orig)) self.assertEqual(self._environ["HTTP_CONTENT_ENCODING"], "gzip") self._environ["CONTENT_LENGTH"] = zlength self._environ["wsgi.input"] = zstream self._app(self._environ, None) buf = self._environ["wsgi.input"] self.assertIsNot(buf, zstream) buf.seek(0) self.assertEqual(orig, buf.read()) self.assertIs(None, self._environ.get("CONTENT_LENGTH")) self.assertNotIn("HTTP_CONTENT_ENCODING", self._environ) def test_call(self) -> None: self._test_call(self.example_text, *self._get_zstream(self.example_text)) def test_call_no_seek(self) -> None: """This ensures that the gunzipping code doesn't require any methods on 'wsgi.input' except for '.read()'. (In particular, it shouldn't require '.seek()'. See https://github.com/jelmer/dulwich/issues/140.). """ zstream, zlength = self._get_zstream(self.example_text) self._test_call( self.example_text, MinimalistWSGIInputStream(zstream.read()), zlength, ) def test_call_no_working_seek(self) -> None: """Similar to 'test_call_no_seek', but this time the methods are available (but defunct). See https://github.com/jonashaag/klaus/issues/154. """ zstream, zlength = self._get_zstream(self.example_text) self._test_call( self.example_text, MinimalistWSGIInputStream2(zstream.read()), zlength, ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734624621.0 dulwich-0.22.7/tox.ini0000644000175100002000000000025314731042555014152 0ustar00runnerdocker[tox] downloadcache = {toxworkdir}/cache/ [testenv] commands = make check recreate = True whitelist_externals = make [testenv:noext] commands = make check-noextensions