pax_global_header00006660000000000000000000000064143537270270014524gustar00rootroot0000000000000052 comment=a42a069bc755f0fa81316965335cb33dbf22a968 git-tools-2022.12/000077500000000000000000000000001435372702700136155ustar00rootroot00000000000000git-tools-2022.12/.editorconfig000066400000000000000000000005751435372702700163010ustar00rootroot00000000000000# EditorConfig is awesome: https://EditorConfig.org # top-most EditorConfig file root = true # Unix-style newlines with a newline ending every file # Use TAB for shell files [*] end_of_line = lf insert_final_newline = true charset = utf-8 indent_style = tab indent_size = 8 # 4 space indentation for python files [{git-restore-mtime, *.py}] indent_style = space indent_size = 4 git-tools-2022.12/.gitignore000066400000000000000000000000701435372702700156020ustar00rootroot00000000000000.* !.gitignore !.editorconfig ref/ git_restore_mtime.py git-tools-2022.12/LICENSE.txt000066400000000000000000001045131435372702700154440ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . git-tools-2022.12/README.md000066400000000000000000000155201435372702700150770ustar00rootroot00000000000000Git Tools ========= Assorted git-related scripts and tools Requirements ------------ - **Git** (duh!). Tested in v2.17.1 and prior versions since 2010 - **Python** (for `git-restore-mtime`). Tested in Python 3.6, also works in Python 3.1+ - **Bash** (for all other tools). Tested in Bash 4, some may work in Bash 3 or even `sh` Bash and Python are already installed by default in virtually all GNU/Linux distros. And you probably already have Git if you are interested in these tools. If needed, the command to install dependencies for Debian-like distros (like Ubuntu/Mint) is: sudo apt install bash python3 git Install ------- For [Debian](https://tracker.debian.org/pkg/git-mestrelion-tools), [Ubuntu](https://launchpad.net/ubuntu/+source/git-mestrelion-tools), LinuxMint, and their derivatives, in official repositories as `git-restore-mtime`: sudo apt install git-restore-mtime For [Fedora](https://src.fedoraproject.org/rpms/git-tools) and in EPEL repository for CentOS, Red Hat Enterprise Linux (RHEL), Oracle Linux and others, as root: dnf install git-tools # 'yum' if using older CentOS/RHEL releases [Gentoo](https://packages.gentoo.org/packages/dev-vcs/git-tools) and Funtoo, also as root: emerge dev-vcs/git-tools [MacPorts](https://ports.macports.org/port/git-tools/details/): sudo port install git-tools Also available in Kali Linux, MidnightBDS _mports_, Mageia, and possibly other distributions. **Manual install**: to run from the repository tree, just clone and add the installation directory to your `$PATH`: ```sh cd ~/some/dir git clone https://github.com/MestreLion/git-tools.git echo 'PATH=$PATH:~/some/dir/git-tools' >> ~/.profile # or ~/.bashrc ``` Usage ----- If you installed using your operating system package manager, or if you added the cloned repository to your `$PATH`, you can simply run the tools as if they were regular `git` subcommands! For example: git restore-mtime --test The magic? Git considers any executable named `git-*` in either `/usr/lib/git-core` or in `$PATH` to be a subcommand! It also integrates with `man`, triggering the manual pages if they're installed, such as when installing using your package manager: git restore-mtime --help git help strip-merge In case the manual pages are not installed in the system, such as when running from the cloned repository, you can still read the built-in help by directly invoking the tool: git-clone-subset --help Uninstall --------- For the packaged versions, use your repository tools such as `apt`, `yum`, `emerge`. For the manual installation, just delete the directory and remove it from your `$PATH`. ```sh rm -rf ~/some/dir/git-tools sed -i '/git-tools/d' ~/.profile ``` --- Tools ===== This is a brief description of the tools. For more detailed instructions, see `--help` of each tool. git-branches-rename ------------------- *Batch renames branches with a matching prefix to another prefix* Examples: ```console $ git-rename-branches bug bugfix bug/128 -> bugfix/128 bug_test -> bugfix_test $ git-rename-branches ma backup/ma master -> backup/master main -> backup/main ``` git-clone-subset ---------------- *Clones a subset of a git repository* Uses `git clone` and `git filter-branch` to remove from the clone all but the requested files, along with their associated commit history. Clones a `repository` into a `destination` directory and runs `git filter-branch --prune-empty --tree-filter 'git rm ...' -- --all` on the clone to prune from history all files except the ones matching a `pattern`, effectively creating a clone with a subset of files (and history) of the original repository. Useful for creating a new repository out of a set of files from another repository, migrating (only) their associated history. Very similar to what `git filter-branch --subdirectory-filter` does, but for a file pattern instead of just a single directory. git-find-uncommitted-repos -------------------------- *Recursively list repos with uncommitted changes* Recursively finds all git repositories in the given directory(es), runs `git status` on them, and prints the location of repositories with uncommitted changes. The tool I definitely use the most. git-rebase-theirs ----------------- *Resolve rebase conflicts and failed cherry-picks by favoring 'theirs' version* When using `git rebase`, conflicts are usually wanted to be resolved by favoring the `working branch` version (the branch being rebased, *'theirs'* side in a rebase), instead of the `upstream` version (the base branch, *'ours'* side). But `git rebase --strategy -X theirs` is only available from git 1.7.3. For older versions, `git-rebase-theirs` is the solution. Despite the name, it's also useful for fixing failed cherry-picks. git-restore-mtime ----------------- *Restore original modification time of files based on the date of the most recent commit that modified them* Probably the most popular and useful tool, and the reason this repository was packaged into distros. Git, unlike other version control systems, does not preserve the original timestamp of committed files. Whenever repositories are cloned, or branches/files are checked out, file timestamps are reset to the current date. While this behavior has its justifications (notably when using `make` to compile software), sometimes it is desirable to restore the original modification date of a file (for example, when generating release tarballs). As git does not provide any way to do that, `git-restore-mtime` tries to work around this limitation. For more information and background, see http://stackoverflow.com/a/13284229/624066 For TravisCI users, simply add this setting to `.travis.yml` so it clones the full repository history: ```yaml git: depth: false ``` Similarly, when using GitHub Actions, make sure to include `fetch-depth: 0` in your checkout workflow, as described in its [documentation](https://github.com/actions/checkout#Fetch-all-history-for-all-tags-and-branches): ```yaml - uses: actions/checkout@v2 with: fetch-depth: 0 ``` git-strip-merge --------------- *A `git-merge` wrapper that delete files on a "foreign" branch before merging* Answer for "*How to set up a git driver to ignore a folder on merge?*", see http://stackoverflow.com/questions/3111515 Example: ```console $ git checkout master $ git-strip-merge design photoshop/*.psd ``` --- Contributing ------------ Patches are welcome! Fork, hack, request pull! If you find a bug or have any enhancement request, please open a [new issue](https://github.com/MestreLion/git-tools/issues/new) Author ------ Rodrigo Silva (MestreLion) License and Copyright --------------------- ``` Copyright (C) 2012 Rodrigo Silva (MestreLion) . License GPLv3+: GNU GPL version 3 or later . This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. ``` git-tools-2022.12/git-branches-rename000077500000000000000000000047521435372702700173660ustar00rootroot00000000000000#!/usr/bin/env bash # # git-rename-branches - rename multiple branches that start with a given name # # Copyright (C) 2012 Rodrigo Silva (MestreLion) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see usage() { cat <<- USAGE Usage: $self [options] BRANCH_PREFIX NEW_PREFIX USAGE if [[ "$1" ]] ; then cat <<- USAGE Try '$self --help' for more information. USAGE exit 1 fi cat <<-USAGE Batch renames branches with a matching prefix to another prefix Options: -h|--help - show this page. -v|--verbose - print more details about what is being done. -n|--dry-run - do not actually renames the branches. BRANCH_PREFIX - a prefix that matches the start of branch names NEW_PREFIX - the new prefix for the branch names Examples: $ git-rename-branches bug bugfix bug/128 -> bugfix/128 bug_test -> bugfix_test $ git-rename-branches ma backup/ma master -> backup/master main -> backup/main Copyright (C) 2012 Rodrigo Silva (MestreLion) License: GPLv3 or later. See USAGE exit 0 } invalid() { echo "$self: invalid option $1" ; usage 1 ; } missing() { echo "$self: missing ${1:+$1 }operand" ; usage 1 ; } self="${0##*/}" verbose=0 dry_run=0 # Loop options while (( $# )); do case "$1" in -h|--help ) usage ;; -v|--verbose ) verbose=1 ;; -n|--dry-run ) dry_run=1 ;; -- ) shift ; break ;; -* ) invalid "$1" ; break ;; * ) break ;; esac shift done [[ "$1" && "$2" ]] || missing 'a PREFIX' while read -r branch; do if ((dry_run)) ; then ((verbose)) && echo "$branch -> ${2}${branch#$1}" else git branch -m "$branch" "${2}${branch#$1}" && ((verbose)) && echo "$branch -> ${2}${branch#$1}" fi done < <(git branch | awk -v branches="${1/\\/\\\\}" '$NF ~ "^" branches {print $NF}') git-tools-2022.12/git-clone-subset000077500000000000000000000130231435372702700167260ustar00rootroot00000000000000#!/usr/bin/env bash # # git-clone-subset - clones a subset of a git repository # # Copyright (C) 2012 Rodrigo Silva (MestreLion) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not see # # Uses git clone and git filter-branch to remove from the clone all files but # the ones requested, along with their associated commit history. usage() { cat <<- USAGE Usage: $myname [options] USAGE if [[ "$1" ]] ; then cat >&2 <<- USAGE Try '$myname --help' for more information. USAGE exit 1 fi cat <<-USAGE Clones a into a and prune from history all files except the ones matching by running on the clone: git filter-branch --prune-empty --tree-filter 'git rm ...' -- --all This effectively creates a clone with a subset of files (and history) of the original repository. The original repository is not modified. Useful for creating a new repository out of a set of files from another repository, migrating (only) their associated history. Very similar to: git filter-branch --subdirectory-filter But $myname works on a path pattern instead of just a single directory. Options: -h, --help show this page. URL or local path to the git repository to be cloned. Directory to create the clone. Same rules for git-clone applies: it will be created if it does not exist and it must be empty otherwise. But, unlike git-clone, this argument is not optional: git-clone uses several rules to determine the "friendly" basename of a cloned repo, and $myname will not risk parse its output, let alone predict the chosen name. Glob pattern to match the desired files/dirs. It will be ultimately evaluated by a call to bash, NOT git or sh, using extended glob '!()' rule. Quote it or escape it on command line, so it does not get evaluated prematurely by your current shell. Only a single pattern is allowed: if more are required, use extglob's "|" syntax. Globs will be evaluated with bash's shopt dotglob set, so beware. Patterns should not contain spaces or special chars like " ' \$ ( ) { } \`, not even quoted or escaped, since that might interfere with the !() syntax after pattern expansion. Pattern Examples: "*.png" "*.png|*icon*" "*.h|src/|lib" Limitations: - Renames are NOT followed. As a workaround, list the rename history with 'git log --follow --name-status --format='%H' -- file | grep "^[RAD]"' and include all multiple names of a file in the pattern, as in "current_name|old_name|initial_name". As a side effect, if a different file has taken place of an old name, it will be preserved too, and there is no way around this using this tool. - There is no (easy) way to keep some files in a dir: using 'dir/foo*' as pattern will not work. So keep the whole dir and remove files afterwards, using git filter-branch and a (quite complex) combination of cloning, remote add, rebase, etc. - Pattern matching is quite limited, and many of bash's escaping and quoting does not work properly when pattern is expanded inside !(). Copyright (C) 2013 Rodrigo Silva (MestreLion) License: GPLv3 or later. See USAGE exit 0 } # Helper functions myname="${0##*/}" argerr() { printf "%s: %s\n" "${0##*/}" "${1:-error}" >&2 ; usage 1 ; } invalid() { argerr "invalid option: $1" ; } missing() { argerr "missing ${2:+$2 }operand${1:+ from $1}." ; } # Argument handling for arg in "$@"; do case "$arg" in -h|--help) usage ;; esac; done repo=$1 dir=$2 pattern=$3 [[ "$repo" ]] || missing "" "" [[ "$dir" ]] || missing "" "" [[ "$pattern" ]] || missing "" "" (($# > 3)) && argerr "too many arguments: $4" # Clone the repo and enter it git clone --no-hardlinks "$repo" "$dir" && cd "$dir" && # Remove remotes (a clone is meant to be a different repository) while read -r remote; do git remote rm "$remote" || break done < <(git remote) && # The heart of the script git filter-branch --prune-empty --tree-filter \ "bash -O dotglob -O extglob -c 'git rm -rf --ignore-unmatch -- !($pattern)'" \ -- --all && # fix a bug in filter-branch where empty root commits are not removed # even with --prune-empty. First we loop each root commit while read -r root; do # Test if it's an non-empty commit if [[ "$(git ls-tree "$root")" ]]; then continue; fi # Now "remove" it by deleting its child's parent reference git filter-branch --force --parent-filter "sed 's/-p $root//'" -- --all done < <(git rev-list --max-parents=0 HEAD) && # Delete backups and the reflog, not needed in a clone if [[ -e .git/refs/original/ ]] ; then git "for-each-ref" --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d fi && git reflog expire --expire=now --all && git gc --prune=now git-tools-2022.12/git-find-uncommitted-repos000077500000000000000000000045511435372702700207250ustar00rootroot00000000000000#!/usr/bin/env bash # # git-find-uncommitted-repos - recursively list repos with uncommitted changes # # Copyright (C) 2012 Rodrigo Silva (MestreLion) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. See # # Recursively finds all git repositories in each PATH argument, runs git status # on them, and prints the location of repositories with uncommitted changes # Only works for conventional repositories where git dir is "/.git" myname="${0##*/}" untracked=no invalid() { printf "%s: invalid option: %s\n" "$myname" "$1" >&2 ; usage 1 ; } usage() { cat <<-USAGE Usage: $myname [-u] [DIR...] USAGE if [[ "$1" ]] ; then cat >&2 <<- USAGE Try '$myname --help' for more information. USAGE exit 1 fi cat <<-USAGE Recursively list repositories with uncommitted changes Options: -h|--help - show this page. -u|--untracked - count untracked files as 'uncommitted' DIR... - the directories to scan, or current directory if none is specified. Copyright (C) 2012 Rodrigo Silva (MestreLion) License: GPLv3 or later. See USAGE exit 0 } # Option handling dirs=() for arg in "$@"; do [[ "$arg" == "-h" || "$arg" == "--help" ]] && usage ; done while (( $# )); do case "$1" in -u|--untracked) untracked=normal ;; -- ) shift ; break ;; -* ) invalid "$1" ;; * ) dirs+=( "$1" ) ;; esac shift done dirs+=( "$@" ) while read -r repo; do repo="$(dirname "$repo")" uncommitted=$(cd "$repo" && git status --short --untracked-files="$untracked") if [[ "$uncommitted" ]]; then echo "$repo"; fi done < <(find "${dirs[@]}" -name .git -type d) git-tools-2022.12/git-rebase-theirs000077500000000000000000000077741435372702700171000ustar00rootroot00000000000000#!/usr/bin/env bash # # git-rebase-theirs - Resolve rebase conflicts by favoring 'theirs' version # # Copyright (C) 2012 Rodrigo Silva (MestreLion) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not see #Defaults: verbose=0 backup=1 inplace=0 ext=".bak" message() { printf "%s\n" "$1" >&2 ; } argerr() { printf "%s: %s\n" "$myname" "${1:-error}" >&2 ; usage 1 ; } invalid() { argerr "invalid option: $1" ; } missing() { argerr "missing${1:+ $1} operand." ; } # Bash 4.4 does not allow 'continue' inside functions to operate on outer loops # See https://stackoverflow.com/a/52497694/624066 skip() { message "skipping ${2:-$file}${1:+: $1}"; } usage() { cat <<- USAGE Usage: $myname [options] [--] FILE... USAGE if [[ "$1" ]] ; then cat >&2 <<- USAGE Try '$myname --help' for more information. USAGE exit 1 fi cat <<-USAGE Resolve git rebase conflicts in FILE(s) by favoring 'theirs' version When using git rebase, one may want to automatically resolve conflicts by favoring the version, which is the branch being rebased, 'theirs' side in a rebase, instead of the version, the base branch, 'ours' side in the rebase. The solution is 'git rebase --strategy recursive -X theirs', which is only available since git 1.7.3. For older versions, $myname solves that problem. And despite its name it's also useful for fixing failed cherry-picks. It works by discarding all lines between '<<<<<<< ' and '========', inclusive, and also the '>>>>>> commit' marker. By default it outputs to stdout, but files can be edited in-place using --in-place, which, unlike sed, creates a backup by default. Options: -h|--help show this page. -v|--verbose print more details in stderr. --in-place[=SUFFIX] edit files in place, creating a backup with SUFFIX extension. Default if blank is "$ext" --no-backup disables backup Copyright (C) 2012 Rodrigo Silva (MestreLion) License: GPLv3 or later. See USAGE exit 0 } myname="${0##*/}" # Option handling files=() while (( $# )); do case "$1" in -h|--help ) usage ;; -v|--verbose ) verbose=1 ;; --no-backup ) backup=0 ;; --in-place ) inplace=1 ;; --in-place=* ) inplace=1 suffix="${1#*=}" ;; -- ) shift ; break ;; -* ) invalid "$1" ;; * ) files+=( "$1" ) ;; esac shift done files+=( "$@" ) if ! (( "${#files[@]}" )); then missing "FILE"; fi ext=${suffix:-$ext} for file in "${files[@]}"; do if ! [[ -f "$file" ]]; then skip "not a valid file"; continue; fi if ((inplace)); then outfile=$(mktemp) || { skip "could not create temporary file"; continue; } # shellcheck disable=SC2064 trap "rm -f -- '$outfile'" EXIT cp "$file" "$outfile" || { skip; continue; } exec 3>"$outfile" else exec 3>&1 fi # Do the magic :) awk '/^<<<<<<<+ .+$/,/^=+$/{next} /^>>>>>>>+ /{next} 1' "$file" >&3 exec 3>&- if ! ((inplace)); then continue; fi diff "$file" "$outfile" >/dev/null && { skip "no conflict markers found"; continue; } if ((backup)); then cp "$file" "$file$ext" || { skip "could not backup"; continue; } fi cp "$outfile" "$file" || { skip "could not edit in-place"; continue; } rm -f -- "$outfile" trap - EXIT if ((verbose)); then message "resolved ${file}"; fi done git-tools-2022.12/git-restore-mtime000077500000000000000000000572671435372702700171410ustar00rootroot00000000000000#!/usr/bin/env python3 # # git-restore-mtime - Change mtime of files based on commit date of last change # # Copyright (C) 2012 Rodrigo Silva (MestreLion) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. See # """ Change the modification time (mtime) of files in work tree, based on the date of the most recent commit that modified the file, including renames. Ignores untracked files and uncommitted deletions, additions and renames, and by default modifications too. --- Useful prior to generating release tarballs, so each file is archived with a date that is similar to the date when the file was actually last modified, assuming the actual modification date and its commit date are close. """ # TODO: # - Add -z on git whatchanged/ls-files, so we don't deal with filename decoding # - When Python is bumped to 3.7, use text instead of universal_newlines on subprocess # - Update "Statistics for some large projects" with modern hardware and repositories. # - Create a README.md for git-restore-mtime alone. It deserves extensive documentation # - Move Statistics there # - See git-extras as a good example on project structure and documentation # FIXME: # - When current dir is outside the worktree, e.g. using --work-tree, `git ls-files` # assume any relative pathspecs are to worktree root, not the current dir. As such, # relative pathspecs may not work. # - Renames are tricky: # - R100 should not change mtime, but original name is not on filelist. Should # track renames until a valid (A, M) mtime found and then set on current name. # - Should set mtime for both current and original directories. # - Check mode changes with unchanged blobs? # - Check file (A, D) for the directory mtime is not sufficient: # - Renames also change dir mtime, unless rename was on a parent dir # - If most recent change of all files in a dir was a Modification (M), # dir might not be touched at all. # - Dirs containing only subdirectories but no direct files will also # not be touched. They're files' [grand]parent dir, but never their dirname(). # - Some solutions: # - After files done, perform some dir processing for missing dirs, finding latest # file (A, D, R) # - Simple approach: dir mtime is the most recent child (dir or file) mtime # - Use a virtual concept of "created at most at" to fill missing info, bubble up # to parents and grandparents # - When handling [grand]parent dirs, stay inside # - Better handling of merge commits. `-m` is plain *wrong*. `-c/--cc` is perfect, but # painfully slow. First pass without merge commits is not accurate. Maybe add a new # `--accurate` mode for `--cc`? if __name__ != "__main__": raise ImportError("{} should not be used as a module.".format(__name__)) import argparse import datetime import logging import os.path import shlex import signal import subprocess import sys import time __version__ = "2022.12" # Update symlinks only if the platform supports not following them UPDATE_SYMLINKS = bool(os.utime in getattr(os, 'supports_follow_symlinks', [])) # Call os.path.normpath() only if not in a POSIX platform (Windows) NORMALIZE_PATHS = (os.path.sep != '/') # How many files to process in each batch when re-trying merge commits STEPMISSING = 100 # (Extra) keywords for the os.utime() call performed by touch() UTIME_KWS = {} if not UPDATE_SYMLINKS else {'follow_symlinks': False} # Command-line interface ###################################################### def parse_args(): parser = argparse.ArgumentParser( description=__doc__.split('\n---')[0]) group = parser.add_mutually_exclusive_group() group.add_argument('--quiet', '-q', dest='loglevel', action="store_const", const=logging.WARNING, default=logging.INFO, help="Suppress informative messages and summary statistics.") group.add_argument('--verbose', '-v', action="count", help=""" Print additional information for each processed file. Specify twice to further increase verbosity. """) parser.add_argument('--cwd', '-C', metavar="DIRECTORY", help=""" Run as if %(prog)s was started in directory %(metavar)s. This affects how --work-tree, --git-dir and PATHSPEC arguments are handled. See 'man 1 git' or 'git --help' for more information. """) parser.add_argument('--git-dir', dest='gitdir', metavar="GITDIR", help=""" Path to the git repository, by default auto-discovered by searching the current directory and its parents for a .git/ subdirectory. """) parser.add_argument('--work-tree', dest='workdir', metavar="WORKTREE", help=""" Path to the work tree root, by default the parent of GITDIR if it's automatically discovered, or the current directory if GITDIR is set. """) parser.add_argument('--force', '-f', default=False, action="store_true", help=""" Force updating files with uncommitted modifications. Untracked files and uncommitted deletions, renames and additions are always ignored. """) parser.add_argument('--merge', '-m', default=False, action="store_true", help=""" Include merge commits. Leads to more recent times and more files per commit, thus with the same time, which may or may not be what you want. Including merge commits may lead to fewer commits being evaluated as files are found sooner, which can improve performance, sometimes substantially. But as merge commits are usually huge, processing them may also take longer. By default, merge commits are only used for files missing from regular commits. """) parser.add_argument('--first-parent', default=False, action="store_true", help=""" Consider only the first parent, the "main branch", when evaluating merge commits. Only effective when merge commits are processed, either when --merge is used or when finding missing files after the first regular log search. See --skip-missing. """) parser.add_argument('--skip-missing', '-s', dest="missing", default=True, action="store_false", help=""" Do not try to find missing files. If merge commits were not evaluated with --merge and some files were not found in regular commits, by default %(prog)s searches for these files again in the merge commits. This option disables this retry, so files found only in merge commits will not have their timestamp updated. """) parser.add_argument('--no-directories', '-D', dest='dirs', default=True, action="store_false", help=""" Do not update directory timestamps. By default, use the time of its most recently created, renamed or deleted file. Note that just modifying a file will NOT update its directory time. """) parser.add_argument('--test', '-t', default=False, action="store_true", help="Test run: do not actually update any file timestamp.") parser.add_argument('--commit-time', '-c', dest='commit_time', default=False, action='store_true', help="Use commit time instead of author time.") parser.add_argument('--oldest-time', '-o', dest='reverse_order', default=False, action='store_true', help=""" Update times based on the oldest, instead of the most recent commit of a file. This reverses the order in which the git log is processed to emulate a file "creation" date. Note this will be inaccurate for files deleted and re-created at later dates. """) parser.add_argument('--skip-older-than', metavar='SECONDS', type=int, help=""" Ignore files that are currently older than %(metavar)s. Useful in workflows that assume such files already have a correct timestamp, as it may improve performance by processing fewer files. """) parser.add_argument('--skip-older-than-commit', '-N', default=False, action='store_true', help=""" Ignore files older than the timestamp it would be updated to. Such files may be considered "original", likely in the author's repository. """) parser.add_argument('--unique-times', default=False, action="store_true", help=""" Set the microseconds to a unique value per commit. Allows telling apart changes that would otherwise have identical timestamps, as git's time accuracy is in seconds. """) parser.add_argument('pathspec', nargs='*', metavar='PATHSPEC', help=""" Only modify paths matching %(metavar)s, relative to current directory. By default, update all but untracked files and submodules. """) parser.add_argument('--version', '-V', action='version', version='%(prog)s version {version}'.format(version=get_version())) args_ = parser.parse_args() if args_.verbose: args_.loglevel = max(logging.TRACE, logging.DEBUG // args_.verbose) args_.debug = args_.loglevel <= logging.DEBUG return args_ def get_version(version=__version__): if not version.endswith('+dev'): return version try: cwd = os.path.dirname(os.path.realpath(__file__)) return Git(cwd=cwd, errors=False).describe().lstrip('v') except Git.Error: return '-'.join((version, "unknown")) # Helper functions ############################################################ def setup_logging(): """Add TRACE logging level and corresponding method, return the root logger""" logging.TRACE = TRACE = logging.DEBUG // 2 logging.Logger.trace = lambda _, m, *a, **k: _.log(TRACE, m, *a, **k) return logging.getLogger() def normalize(path): r"""Normalize paths from git, handling non-ASCII characters. Git stores paths as UTF-8 normalization form C. If path contains non-ASCII or non-printable characters, git outputs the UTF-8 in octal-escaped notation, escaping double-quotes and backslashes, and then double-quoting the whole path. https://git-scm.com/docs/git-config#Documentation/git-config.txt-corequotePath This function reverts this encoding, so: normalize(r'"Back\\slash_double\"quote_a\303\247a\303\255"') => r'Back\slash_double"quote_açaí') See notes on `windows/non-ascii-paths.txt` about path encodings on non-UTF-8 platforms and filesystems. """ if path and path[0] == '"': # Python 2: path = path[1:-1].decode("string-escape") # Python 3: https://stackoverflow.com/a/46650050/624066 path = (path[1:-1] # Remove enclosing double quotes .encode('latin1') # Convert to bytes, required by 'unicode-escape' .decode('unicode-escape') # Perform the actual octal-escaping decode .encode('latin1') # 1:1 mapping to bytes, forming UTF-8 encoding .decode('utf8')) # Decode from UTF-8 if NORMALIZE_PATHS: # Make sure the slash matches the OS; for Windows we need a backslash path = os.path.normpath(path) return path def dummy(*_args, **_kwargs): """No-op function used in dry-run tests""" def touch(path, mtime): """The actual mtime update""" os.utime(path, (mtime, mtime), **UTIME_KWS) def touch_ns(path, mtime_ns): """The actual mtime update, using nanoseconds for unique timestamps""" os.utime(path, None, ns=(mtime_ns, mtime_ns), **UTIME_KWS) def isodate(secs: int): # time.localtime() accepts floats, but discards fractional part return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(secs)) def isodate_ns(ns: int): # for integers fromtimestamp() is equivalent and ~16% slower than isodate() return datetime.datetime.fromtimestamp(ns / 1000000000).isoformat(sep=' ') def get_mtime_ns(secs: int, idx: int): # Time resolution for filesystems and functions: # ext-4 and other POSIX filesystems: 1 nanosecond # NTFS (Windows default): 100 nanoseconds # datetime.datetime() (due to 64-bit float epoch): 1 microsecond us = idx % 1000000 # 10**6 return 1000 * (1000000 * secs + us) def get_mtime_path(path): return os.path.getmtime(path) # Git class and parse_log(), the heart of the script ########################## class Git: def __init__(self, workdir=None, gitdir=None, cwd=None, errors=True): self.gitcmd = ['git'] self.errors = errors self._proc = None if workdir: self.gitcmd.extend(('--work-tree', workdir)) if gitdir: self.gitcmd.extend(('--git-dir', gitdir)) if cwd: self.gitcmd.extend(('-C', cwd)) self.workdir, self.gitdir = self._get_repo_dirs() def ls_files(self, paths: list = None): return (normalize(_) for _ in self._run('ls-files --full-name', paths)) def ls_dirty(self, force=False): return (normalize(_[3:].split(' -> ', 1)[-1]) for _ in self._run('status --porcelain') if _[:2] != '??' and (not force or (_[0] in ('R', 'A') or _[1] == 'D'))) def log(self, merge=False, first_parent=False, commit_time=False, reverse_order=False, paths: list = None): cmd = 'whatchanged --pretty={}'.format('%ct' if commit_time else '%at') if merge: cmd += ' -m' if first_parent: cmd += ' --first-parent' if reverse_order: cmd += ' --reverse' return self._run(cmd, paths) def describe(self): return self._run('describe --tags', check=True)[0] def terminate(self): if self._proc is None: return try: self._proc.terminate() except OSError: # Avoid errors on OpenBSD pass def _get_repo_dirs(self): return (os.path.normpath(_) for _ in self._run('rev-parse --show-toplevel --absolute-git-dir', check=True)) def _run(self, cmdstr: str, paths: list = None, output=True, check=False): cmdlist = self.gitcmd + shlex.split(cmdstr) if paths: cmdlist.append('--') cmdlist.extend(paths) popen_args = dict(universal_newlines=True, encoding='utf8') if not self.errors: popen_args['stderr'] = subprocess.DEVNULL log.trace("Executing: %s", ' '.join(cmdlist)) if not output: return subprocess.call(cmdlist, **popen_args) if check: try: stdout: str = subprocess.check_output(cmdlist, **popen_args) return stdout.splitlines() except subprocess.CalledProcessError as e: raise self.Error(e.returncode, e.cmd, e.output, e.stderr) self._proc = subprocess.Popen(cmdlist, stdout=subprocess.PIPE, **popen_args) return (_.rstrip() for _ in self._proc.stdout) def __del__(self): self.terminate() class Error(subprocess.CalledProcessError): """Error from git executable""" def parse_log(filelist, dirlist, stats, git, merge=False, filterlist=None): mtime = 0 datestr = isodate(0) for line in git.log( merge, args.first_parent, args.commit_time, args.reverse_order, filterlist ): stats['loglines'] += 1 # Blank line between Date and list of files if not line: continue # Date line if line[0] != ':': # Faster than `not line.startswith(':')` stats['commits'] += 1 mtime = int(line) if args.unique_times: mtime = get_mtime_ns(mtime, stats['commits']) if args.debug: datestr = isodate(mtime) continue # File line: three tokens if it describes a renaming, otherwise two tokens = line.split('\t') # Possible statuses: # M: Modified (content changed) # A: Added (created) # D: Deleted # T: Type changed: to/from regular file, symlinks, submodules # R099: Renamed (moved), with % of unchanged content. 100 = pure rename # Not possible in log: C=Copied, U=Unmerged, X=Unknown, B=pairing Broken status = tokens[0].split(' ')[-1] file = tokens[-1] # Handles non-ASCII chars and OS path separator file = normalize(file) def do_file(): if args.skip_older_than_commit and get_mtime_path(file) <= mtime: stats['skip'] += 1 return if args.debug: log.debug("%d\t%d\t%d\t%s\t%s", stats['loglines'], stats['commits'], stats['files'], datestr, file) try: touch(os.path.join(git.workdir, file), mtime) stats['touches'] += 1 except Exception as e: log.error("ERROR: %s: %s", e, file) stats['errors'] += 1 def do_dir(): if args.debug: log.debug("%d\t%d\t-\t%s\t%s", stats['loglines'], stats['commits'], datestr, "{}/".format(dirname or '.')) try: touch(os.path.join(git.workdir, dirname), mtime) stats['dirtouches'] += 1 except Exception as e: log.error("ERROR: %s: %s", e, dirname) stats['direrrors'] += 1 if file in filelist: stats['files'] -= 1 filelist.remove(file) do_file() if args.dirs and status in ('A', 'D'): dirname = os.path.dirname(file) if dirname in dirlist: dirlist.remove(dirname) do_dir() # All files done? if not stats['files']: git.terminate() return # Main Logic ################################################################## def main(): start = time.time() # yes, Wall time. CPU time is not realistic for users. stats = {_: 0 for _ in ('loglines', 'commits', 'touches', 'skip', 'errors', 'dirtouches', 'direrrors')} logging.basicConfig(level=args.loglevel, format='%(message)s') log.trace("Arguments: %s", args) # First things first: Where and Who are we? if args.cwd: log.debug("Changing directory: %s", args.cwd) try: os.chdir(args.cwd) except OSError as e: log.critical(e) return e.errno # Using both os.chdir() and `git -C` is redundant, but might prevent side effects # `git -C` alone could be enough if we make sure that: # - all paths, including args.pathspec, are processed by git: ls-files, rev-parse # - touch() / os.utime() path argument is always prepended with git.workdir try: git = Git(workdir=args.workdir, gitdir=args.gitdir, cwd=args.cwd) except Git.Error as e: # Not in a git repository, and git already informed user on stderr. So we just... return e.returncode # Get the files managed by git and build file list to be processed if UPDATE_SYMLINKS and not args.skip_older_than: filelist = set(git.ls_files(args.pathspec)) else: filelist = set() for path in git.ls_files(args.pathspec): fullpath = os.path.join(git.workdir, path) # Symlink (to file, to dir or broken - git handles the same way) if not UPDATE_SYMLINKS and os.path.islink(fullpath): log.warning("WARNING: Skipping symlink, no OS support for updates: %s", path) continue # skip files which are older than given threshold if (args.skip_older_than and start - get_mtime_path(fullpath) > args.skip_older_than): continue # Always add files relative to worktree root filelist.add(path) # If --force, silently ignore uncommitted deletions (not in the filesystem) # and renames / additions (will not be found in log anyway) if args.force: filelist -= set(git.ls_dirty(force=True)) # Otherwise, ignore any dirty files else: dirty = set(git.ls_dirty()) if dirty: log.warning("WARNING: Modified files in the working directory were ignored." "\nTo include such files, commit your changes or use --force.") filelist -= dirty # Build dir list to be processed dirlist = set(os.path.dirname(_) for _ in filelist) if args.dirs else set() stats['totalfiles'] = stats['files'] = len(filelist) log.info("{0:,} files to be processed in work dir".format(stats['totalfiles'])) if not filelist: # Nothing to do. Exit silently and without errors, just like git does return # Process the log until all files are 'touched' log.debug("Line #\tLog #\tF.Left\tModification Time\tFile Name") parse_log(filelist, dirlist, stats, git, args.merge, args.pathspec) # Missing files if filelist: # Try to find them in merge logs, if not done already # (usually HUGE, thus MUCH slower!) if args.missing and not args.merge: filterlist = list(filelist) missing = len(filterlist) log.info("{0:,} files not found in log, trying merge commits".format(missing)) for i in range(0, missing, STEPMISSING): parse_log(filelist, dirlist, stats, git, merge=True, filterlist=filterlist[i:i + STEPMISSING]) # Still missing some? for file in filelist: log.warning("WARNING: not found in the log: %s", file) # Final statistics # Suggestion: use git-log --before=mtime to brag about skipped log entries def log_info(msg, *a, width=13): ifmt = '{:%d,}' % (width,) # not using 'n' for consistency with ffmt ffmt = '{:%d,.2f}' % (width,) # %-formatting lacks a thousand separator, must pre-render with .format() log.info(msg.replace('%d', ifmt).replace('%f', ffmt).format(*a)) log_info( "Statistics:\n" "%f seconds\n" "%d log lines processed\n" "%d commits evaluated", time.time() - start, stats['loglines'], stats['commits']) if args.dirs: if stats['direrrors']: log_info("%d directory update errors", stats['direrrors']) log_info("%d directories updated", stats['dirtouches']) if stats['touches'] != stats['totalfiles']: log_info("%d files", stats['totalfiles']) if stats['skip']: log_info("%d files skipped", stats['skip']) if stats['files']: log_info("%d files missing", stats['files']) if stats['errors']: log_info("%d file update errors", stats['errors']) log_info("%d files updated", stats['touches']) if args.test: log.info("TEST RUN - No files modified!") # Keep only essential, global assignments here. Any other logic must be in main() log = setup_logging() args = parse_args() # Set the actual touch() and other functions based on command-line arguments if args.unique_times: touch = touch_ns isodate = isodate_ns # Make sure this is always set last to ensure --test behaves as intended if args.test: touch = dummy # UI done, it's showtime! try: sys.exit(main()) except KeyboardInterrupt: log.info("\nAborting") signal.signal(signal.SIGINT, signal.SIG_DFL) os.kill(os.getpid(), signal.SIGINT) git-tools-2022.12/git-strip-merge000077500000000000000000000110771435372702700165700ustar00rootroot00000000000000#!/usr/bin/env bash # # git-strip-merge - a git-merge that delete files on branch before merging # # Copyright (C) 2012 Rodrigo Silva (MestreLion) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not see # # Answer for "How to setup a git driver to ignore a folder on merge?" # See http://stackoverflow.com/questions/3111515 #Defaults: msgcommit="remove files from '' before merge" msgmerge="Merge stripped branch ''" verbose=0 quiet=(--quiet) usage() { cat <<- USAGE Usage: $myname [git-merge options] [-M ] FILE... USAGE if [[ "$1" ]] ; then cat >&2 <<- USAGE Try '$myname --help' for more information. USAGE exit 1 fi cat <<-USAGE git-merge that delete files on "foreign" before merging Useful for ignoring a folder in before merging it with current branch. Works by deleting FILE(S) in a detached commit based on , and then performing the merge of this new commit in the current branch. Note that is not changed by this procedure. Also note that may actually be any reference, like a tag, or a remote branch, or even a commit SHA. For more information, see Options: -h, --help show this page. -v, --verbose do not use -q to suppress normal output of internal steps from git checkout, rm, commit. By default, only git merge output is shown. Errors, however, are never suppressed -M , --msgcommit= message for the removal commit in . Not to be confused with the message of the merge commit, which is set by -m. Default message is: "$msgcommit" -m , --message= message for the merge commit. Since we are not merging directly, but rather a detached commit based on it, we forge a message similar to git's default for a branch merge. Otherwise git would use in message the full and ugly SHA1 of our commit. Default message is: "$msgmerge" For both commit messages, the token "" is replaced for the actual name. Additional options are passed unchecked to git merge. All options must precede and FILE(s), except -h and --help that may appear anywhere on the command line. Example: $myname design "photoshop/*" Copyright (C) 2012 Rodrigo Silva (MestreLion) License: GPLv3 or later. See USAGE exit 0 } # Helper functions myname="${0##*/}" argerr() { printf "%s: %s\n" "${0##*/}" "${1:-error}" >&2 ; usage 1 ; } invalid() { argerr "invalid option: $1" ; } missing() { argerr "missing ${2:+$2 }operand${1:+ from $1}." ; } # Option handling files=() mergeopts=() for arg in "$@"; do case "$arg" in -h|--help) usage ;; esac; done while (( $# )); do case "$1" in -v|--verbose ) verbose=1 ;; -M ) shift ; msgcommit=$1 ;; -m ) shift ; msgmerge=$1 ;; --msgcommit=* ) msgcommit=${1#*=} ;; --message=* ) msgmerge=${1#*=} ;; -* ) mergeopts+=( "$1" ) ;; * ) branch="$1" shift ; break ;; esac shift done files+=( "$@" ) # Argument handling msgcommit=${msgcommit///$branch} msgmerge=${msgmerge///$branch} [[ "$msgcommit" ]] || missing "msgcommit" "MSG" [[ "$branch" ]] || missing "" "" (( ${#files[@]} )) || missing "" "FILE" ((verbose)) && quiet=() # Here the fun begins... gitsha() { git rev-parse "$1" ; } gitbranch() { git symbolic-ref "$1" 2> /dev/null | sed 's/refs\/heads\///' || gitsha "$1" } original=$(gitbranch HEAD) branchsha=$(gitsha "$branch") trap 'git checkout --quiet "$original"' EXIT git checkout "$branchsha" "${quiet[@]}" && git rm -rf "${files[@]}" "${quiet[@]}" && git commit -m "$msgcommit" "${quiet[@]}" && newsha=$(gitsha HEAD) && git checkout "$original" "${quiet[@]}" && git merge -m "$msgmerge" "${mergeopts[@]}" "$newsha" git-tools-2022.12/man1/000077500000000000000000000000001435372702700144515ustar00rootroot00000000000000git-tools-2022.12/man1/TODO.md000066400000000000000000000013211435372702700155350ustar00rootroot00000000000000# Manual pages TO-DO - Write man pages source files in _Markdown_ and use `pandoc` to convert to _groff_: ``` for doc in *.1.md; do pandoc --standalone --target man --output "${doc%.md}" -- "$doc" fi ``` ## Testing ``` pandoc --standalone --target man -- git-restore-mtime.1.md | man -l - man -l git-restore-mtime.1 manpath # default search path for manpages ``` ## References * https://www.howtogeek.com/682871/how-to-create-a-man-page-on-linux/ ## Also worth considering - help2man - http://www.gnu.org/software/help2man - `sudo apt install help2man` - txt2man - https://github.com/mvertes/txt2man - `sudo apt install txt2man` - ronn - https://github.com/rtomayko/ronn - `sudo apt install ruby-ronn` git-tools-2022.12/man1/git-branches-rename.1000066400000000000000000000020601435372702700203440ustar00rootroot00000000000000.TH GIT-BRANCHES-RENAME 1 2016-01-31 .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME git-branches-rename \- Batch renames branches with a matching prefix to another prefix .SH SYNOPSIS .B git-branches-rename .RI [ options ] .I BRANCH_PREFIX NEW_PREFIX .SH DESCRIPTION Batch renames branches with a matching prefix to another prefix. .SH OPTIONS .TP 8 .BR \-h , \ \-\-help show usage information. .TP 8 .BR \-v , \ \-\-verbose print more details about what is being done. .TP 8 .BR \-n , \ \-\-dry-run do not actually rename the branches. .TP 8 .I BRANCH_PREFIX a prefix that matches the start of branch names. .TP 8 .I NEW_PREFIX the new prefix for the branch names. .SH EXAMPLES .nf $ git-rename-branches bug bugfix bug/128 -> bugfix/128 bug_test -> bugfix_test $ git-rename-branches ma backup/ma master -> backup/master main -> backup/main .fi .SH SEE ALSO .B https://github.com/MestreLion/git-tools .SH AUTHOR Rodrigo Silva (MestreLion) linux@rodrigosilva.com git-tools-2022.12/man1/git-clone-subset.1000066400000000000000000000060151435372702700177210ustar00rootroot00000000000000.TH GIT-CLONE-SUBSET 1 2021-02-11 .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME git-clone-subset \- Clones a subset of a git repository .SH SYNOPSIS .B git-clone-subset .RI [ options ] .I repository destination-dir pattern .SH DESCRIPTION Clones a .I repository into a .I destination-dir and prune from history all files except the ones matching .I pattern by running on the clone: .br .B git filter-branch --prune-empty --tree-filter 'git rm ...' -- --all .br This effectively creates a clone with a subset of files (and history) of the original repository. The original repository is not modified. .sp Useful for creating a new repository out of a set of files from another repository, migrating (only) their associated history. Very similar to: .br .B git filter-branch --subdirectory-filter .br But git-clone-subset works on a path pattern instead of just a single directory. .SH OPTIONS .TP 8 .BR \-h , \ \-\-help show usage information. .TP 8 .I repository URL or local path to the git repository to be cloned. .TP 8 .I destination-dir Directory to create the clone. Same rules for git-clone applies: it will be created if it does not exist and it must be empty otherwise. But, unlike git-clone, this argument is not optional: git-clone uses several rules to determine the "friendly" basename of a cloned repo, and git-clone-subset will not risk parse its output, let alone predict the chosen name. .TP 8 .I pattern Glob pattern to match the desired files/dirs. It will be ultimately evaluated by a call to bash, NOT git or sh, using extended glob '!()' rule. Quote it or escape it on command line, so it does not get evaluated prematurely by your current shell. Only a single pattern is allowed: if more are required, use extglob's "|" syntax. Globs will be evaluated with bash's shopt dotglob set, so beware. Patterns should not contain spaces or special chars like " ' $ ( ) { } `, not even quoted or escaped, since that might interfere with the !() syntax after pattern expansion. .sp Pattern Examples: .sp "*.png" .br "*.png|*icon*" .br "*.h|src/|lib" .SH LIMITATIONS Renames are NOT followed. As a workaround, list the rename history with 'git log --follow --name-status --format='%H' -- file | grep "^[RAD]"' and include all multiple names of a file in the pattern, as in "current_name|old_name|initial_name". As a side effect, if a different file has taken place of an old name, it will be preserved too, and there is no way around this using this tool. .sp There is no (easy) way to keep some files in a dir: using 'dir/foo*' as pattern will not work. So keep the whole dir and remove files afterwards, using git filter-branch and a (quite complex) combination of cloning, remote add, rebase, etc. .sp Pattern matching is quite limited, and many of bash's escaping and quoting does not work properly when pattern is expanded inside !(). .SH SEE ALSO .B https://github.com/MestreLion/git-tools .SH AUTHOR Rodrigo Silva (MestreLion) linux@rodrigosilva.com git-tools-2022.12/man1/git-find-uncommitted-repos.1000066400000000000000000000014701435372702700217120ustar00rootroot00000000000000.TH GIT-FIND-UNCOMMITTED-REPOS 1 2016-01-31 .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME git-find-uncommitted-repos \- Recursively list repositories with uncommitted changes .SH SYNOPSIS .B git-find-uncommitted-repos .RI [ DIR ...] .SH DESCRIPTION Recursively list repositories with uncommitted changes. .SH OPTIONS .TP 8 .BR \-h , \ \-\-help show usage information. .TP 8 .BR \-v , \ \-\-verbose print more details about what is being done. .TP 8 .BR \-u , \ \-\-untracked count untracked files as 'uncommitted' .TP 8 .IR DIR ... the directories to scan, or current directory if none is specified. .SH SEE ALSO .B https://github.com/MestreLion/git-tools .SH AUTHOR Rodrigo Silva (MestreLion) linux@rodrigosilva.com git-tools-2022.12/man1/git-rebase-theirs.1000066400000000000000000000027711435372702700200600ustar00rootroot00000000000000.TH GIT-REBASE-THEIRS 1 2016-01-31 .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME git-rebase-theirs \- Resolve rebase conflicts and failed cherry-picks by favoring 'theirs' version .SH SYNOPSIS .B git-rebase-theirs .RI [ options ] .RI [ -- ] .IR FILE ... .SH DESCRIPTION Resolve git rebase conflicts in FILE(s) by favoring 'theirs' version. When using git rebase, conflicts are usually wanted to be resolved by favoring the version (the branch being rebased, 'theirs' side in a rebase), instead of the version (the base branch, 'ours' side) But git rebase --strategy -X theirs is only available from git 1.7.3 For older versions, git-rebase-theirs is the solution. And Despite the name, it's also useful for fixing failed cherry-picks. It works by discarding all lines between '<<<<<<< ' and '========' inclusive, and also the the '>>>>>> commit' marker. By default it outputs to stdout, but files can be edited in-place using --in-place, which, unlike sed, creates a backup by default. .SH OPTIONS .TP 8 .BR \-h , \ \-\-help show usage information. .TP 8 .BR \-v , \ \-\-verbose print more details in stderr. .TP 8 .BI \-\-in-place [=SUFFIX] edit files in place, creating a backup with .I SUFFIX extension. Default if blank is ".bak" .TP 8 .B \-\-no-backup disables backup .SH SEE ALSO .B https://github.com/MestreLion/git-tools .SH AUTHOR Rodrigo Silva (MestreLion) linux@rodrigosilva.com git-tools-2022.12/man1/git-restore-mtime.1000066400000000000000000000126471435372702700201220ustar00rootroot00000000000000.TH GIT-RESTORE-MTIME 1 2022-07-27 .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME git-restore-mtime \- Restore original modification time of files based on the date of the most recent commit that modified them .SH SYNOPSIS .TP 18 .B git-restore-mtime .RB [ -h ] .RB [ --quiet | --verbose ] .br .RB [ -C .IR DIRECTORY ] .RB [ --work-tree .IR WORKDIR ] .RB [ --git-dir .IR GITDIR ] .br .RB [ --force ] .RB [ --merge ] .RB [ --first-parent ] .RB [ --skip-missing ] .br .RB [ --no-directories ] .RB [ --test ] .RB [ --commit-time ] .RB [ --oldest-time ] .br .RB [ --skip-older-than .IR SECONDS ] .RB [ --unique-times ] .RB [ --version ] .br .RI [ PATHSPEC .RI [ PATHSPEC ...]] .SH DESCRIPTION Change the modification time (mtime) of files in the work tree based on the date of the most recent commit that modified the file, as an attempt to restore the original modification time. Useful when generating release tarballs. Ignore untracked files and uncommitted deletions, additions and renames, and by default modifications too. .SH OPTIONS .SS Positional arguments: .TP 8 .I PATHSPEC Only modify paths matching \fIPATHSPEC\fR, relative to current directory. By default, update all but untracked files and submodules. .SS Optional arguments: .TP 8 .BR \-h ,\ \-\-help show help message and exit .TP 8 .BR \-\-quiet , \-q Suppress informative messages and summary statistics. .TP 8 .BR \-\-verbose , \-v Print additional information for each processed file. Specify twice to further increase verbosity. .TP 8 .BI \-C\ DIRECTORY\fR,\ \-\-cwd\ DIRECTORY Run as if \fBrestore-mtime\fR was started in directory \fIDIRECTORY\fR. This affects how \fB--work-tree\fR, \fB--git-dir\fR and \fIPATHSPEC\fR arguments are handled. See \fBgit\fR(1) for more information. .TP 8 .BI \-\-git-dir\ GITDIR Path to the git repository, by default auto-discovered by searching the current directory and its parents for a \fI.git/\fR subdirectory. .TP 8 .BI \-\-work-tree\ WORKDIR Path to the work tree root, by default the parent of \fIGITDIR\fR if it's automatically discovered, or the current directory if \fIGITDIR\fR is set. .TP 8 .BR \-\-force ,\ \-f Force updating files with uncommitted modifications. Untracked files and uncommitted deletions, renames and additions are always ignored. .TP 8 .BR \-\-merge ,\ \-m Include merge commits. Leads to more recent times and more files per commit, thus with the same time, which may or may not be what you want. Including merge commits may lead to fewer commits being evaluated as files are found sooner, which can improve performance, sometimes substantially. But as merge commits are usually huge, processing them may also take longer. By default, merge commits are only used for files missing from regular commits. .TP 8 .BR \-\-first-parent Consider only the first parent, the "main branch", when evaluating merge commits. Only effective when merge commits are processed, either when \fB--merge\fR is used or when finding missing files after the first regular log search. See \fB--skip-missing\fR. .TP 8 .BR \-\-skip-missing ,\ \-s Do not try to find missing files. If merge commits were not evaluated with \fB--merge\fR and some files were not found in regular commits, by default \fBrestore-mtime\fR searches for these files again in the merge commits. This option disables this retry, so files found only in merge commits will not have their timestamp updated. .TP 8 .BR \-\-no-directories ,\ \-D Do not update directory timestamps. By default, use the time of its most recently created, renamed or deleted file. Note that just modifying a file will NOT update its directory time. .TP 8 .BR \-\-test ,\ \-t Test run: do not actually update any file timestamp. .TP 8 .BR \-\-commit-time ,\ \-c Use commit time instead of author time. .TP 8 .BR \-\-oldest-time ,\ \-o Update times based on the oldest, instead of the most recent commit of a file. This reverses the order in which the git log is processed to emulate a file "creation" date. Note this will be inaccurate for files deleted and re-created at later dates. .TP 8 .BI \-\-skip-older-than\ SECONDS Ignore files that are currently older than \fISECONDS\fR. Useful in workflows that assume such files already have a correct timestamp, as it may improve performance by processing fewer files. .TP 8 .BR \-\-skip-older-than-commit ,\ \-N Ignore files older than the timestamp it would be updated to. Such files may be considered "original", likely in the author's repository. .TP 8 .BR \-\-unique-times Set the microseconds to a unique value per commit. Allows telling apart changes that would otherwise have identical timestamps, as git's time accuracy is in seconds. .TP 8 .BR \-\-version ,\ \-V show program's version number and exit .SH KNOWN ISSUES Renames are poorly handled: it always changes the timestamps of files, even if no content was modified. .br Directory timestamps are also limited to being modified only when files are added (created) or deleted in them. .br In very large repositories, after running \fBrestore-mtime\fR to modify the timestamp of several files, further git operations may emit the error: .br .B \ \ fatal: mmap failed: Cannot allocate memory. .br This is harmless, and can be fixed by running \fBgit-status\fR(1). .SH SEE ALSO .BR git (1),\ git-log (1),\ git-ls-files (1),\ git-status (1) .br .B https://github.com/MestreLion/git-tools .SH AUTHOR Rodrigo Silva (MestreLion) linux@rodrigosilva.com git-tools-2022.12/man1/git-strip-merge.1000066400000000000000000000043061435372702700175550ustar00rootroot00000000000000.TH GIT-STRIP-MERGE 1 2016-01-31 .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME git-strip-merge \- A git-merge wrapper that deletes files on a "foreign" branch before merging .SH SYNOPSIS .B git-strip-merge .RI [ git-merge\ options ] .RB [ -M .IR ] .I .IR FILE ... .SH DESCRIPTION git-merge that deletes files on "foreign" before merging. .sp Useful for ignoring a folder in before merging it with current branch. Works by deleting FILE(S) in a detached commit based on , and then performing the merge of this new commit in the current branch. Note that is not changed by this procedure. Also note that may actually be any reference, like a tag, or a remote branch, or even a commit SHA. .sp For more information, see .SH OPTIONS .TP 8 .BR \-h , \ \-\-help show help message and exit .TP 8 .BR \-v , \ \-\-verbose do not use -q to suppress normal output of internal steps from git checkout, rm, commit. By default, only git merge output is shown. Errors, however, are never suppressed. .TP 8 .BR \-M\ , \ \-\-msgcommit = message for the removal commit in . Not to be confused with the message of the merge commit, which is set by -m. Default message is: "remove files from '' before merge". .TP 8 .BR \-m\ , \ \-\-message = message for the merge commit. Since we are not merging directly, but rather a detached commit based on it, we forge a message similar to git's default for a branch merge. Otherwise git would use in message the full and ugly SHA1 of our commit. Default message is: "Merge stripped branch ''". .PP For both commit messages, the token "" is replaced for the actual name. .sp Additional options are passed unchecked to git merge. .sp All options must precede and FILE(s), except -h and --help that may appear anywhere on the command line. .SH EXAMPLE .nf git-strip-merge design "photoshop/*" .fi .SH SEE ALSO .B https://github.com/MestreLion/git-tools .SH AUTHOR Rodrigo Silva (MestreLion) linux@rodrigosilva.com git-tools-2022.12/misc/000077500000000000000000000000001435372702700145505ustar00rootroot00000000000000git-tools-2022.12/misc/.gitignore000066400000000000000000000000311435372702700165320ustar00rootroot00000000000000data/ git-utimes timing* git-tools-2022.12/misc/benchmark000077500000000000000000000022461435372702700164340ustar00rootroot00000000000000#!/usr/bin/env bash # # benchmark - benchmarking git-restore-mtime # # This file is part of git-tools, see # Copyright (C) 2022 Rodrigo Silva (MestreLion) # License: GPLv3 or later, at your choice. See #------------------------------------------------------------------------------ here="${0%/*}" case "${1:-}" in touch) cmd=( touch-all );; min) cmd=( "$here"/git-restore-mtime-min );; utimes) cmd=( "$here"/git-utimes );; *) cmd=( "$here"/../git-restore-mtime "$@" );; esac # flush() could be more complete: https://stackoverflow.com/a/44266604/624066 flush() { sync; echo 3 | sudo tee /proc/sys/vm/drop_caches > /dev/null; } touch-all() { i=0; while IFS= read -r file; do ((i++)); touch "$file"; done < <(git ls-files); echo "$i files"; } # touch variations, only works if [[ $(find . -name '* *' | wc -l) == 0 ]] touch-for() ( i=0; for file in $(git ls-files); do ((i++)); touch "$file"; done; echo "$i files"; ) touch-min() ( for file in $(git ls-files); do touch "$file"; done; ) touch-all git status >/dev/null 2>&1 # for the linux kernel flush time { "${cmd[@]}"; } git-tools-2022.12/misc/cprofile000077500000000000000000000047001435372702700163020ustar00rootroot00000000000000#!/usr/bin/env bash # # cprofile - profiling git-restore-mtime # # This file is part of git-tools, see # Copyright (C) 2022 Rodrigo Silva (MestreLion) # License: GPLv3 or later, at your choice. See #------------------------------------------------------------------------------ myself="${0##*/}" here="${0%/*}" #------------------------------------------------------------------------------ now() { date +%Y%m%d%H%M%S; } exists() { type "$@" >/dev/null 2>&1; } command-latest() { local prefix=$1 compgen -c "$prefix" | grep -P "^${prefix}\d[.\d]*\$" | sort -ruV | head -n1 } pip-install() { local packages=( "$@" ) local pip; pip=$(command-latest pip) local python; python=${python:-$(command-latest python)} if exists "${packages[@]}"; then return; fi if exists pipx; then pipx install -- "${packages[@]}" return fi if ! exists "$pip"; then sudo apt install python3-pip fi "$python" -m pip install --user "${packages[@]}" } #------------------------------------------------------------------------------ outdir=${here}/data repo=${PWD##*/} pstats=${outdir}/${repo}.$(now).pstats python=$(command-latest python) #------------------------------------------------------------------------------ usage() { cat <<- USAGE Usage: $myself [options] USAGE if [[ "$1" ]] ; then cat <<- USAGE Try '$myself --help' for more information. USAGE exit 1 fi cat <<-USAGE Profiling git-restore-mtime. Run from a repository root Options: -h|--help - show this page. Copyright (C) 2022 Rodrigo Silva (MestreLion) License: GPLv3 or later. See USAGE exit 0 } invalid() { echo "$myself: invalid option $1" ; usage 1 ; } missing() { echo "$myself: missing ${1:+$1 }operand" ; usage 1 ; } # Loop options while (( $# )); do case "$1" in -h|--help ) usage;; -P|--python ) shift; python=${1:-};; --python=* ) python=${1#*=};; -- ) shift ; break;; -* ) invalid "$1" ; break;; * ) break;; esac shift done [[ "$python" ]] || missing --python if ! exists "$python"; then "$python"; usage 1; fi #------------------------------------------------------------------------------ pip-install gprof2dot mkdir -p -- "$outdir" "$python" -m cProfile -o "$pstats" "$here"/../git-restore-mtime gprof2dot -f pstats -o "$pstats".dot -- "$pstats" xdg-open "$pstats".dot git-tools-2022.12/misc/git-restore-mtime-min000077500000000000000000000024361435372702700206410ustar00rootroot00000000000000#!/usr/bin/env python2 # Original post from https://stackoverflow.com/a/13284229/624066 # # Bare-bones version. Current directory must be top-level of work tree. # Usage: git-restore-mtime-bare [pathspecs...] # By default update all files # Example: to only update only the README and files in ./doc: # git-restore-mtime-bare README doc import subprocess, shlex import sys, os.path filelist = set() for path in (sys.argv[1:] or [os.path.curdir]): if os.path.isfile(path) or os.path.islink(path): filelist.add(os.path.relpath(path)) elif os.path.isdir(path): for root, subdirs, files in os.walk(path): if '.git' in subdirs: subdirs.remove('.git') for file in files: filelist.add(os.path.relpath(os.path.join(root, file))) mtime = 0 gitobj = subprocess.Popen(shlex.split('git whatchanged --pretty=%at'), stdout=subprocess.PIPE) for line in gitobj.stdout: line = line.strip() if not line: continue if line.startswith(':'): file = line.split('\t')[-1] if file in filelist: filelist.remove(file) #print mtime, file os.utime(file, (mtime, mtime)) else: mtime = long(line) # All files done? if not filelist: break git-tools-2022.12/windows/000077500000000000000000000000001435372702700153075ustar00rootroot00000000000000git-tools-2022.12/windows/.gitignore000066400000000000000000000000451435372702700172760ustar00rootroot00000000000000/build /dist /git-restore-mtime.spec git-tools-2022.12/windows/README.md000066400000000000000000000050431435372702700165700ustar00rootroot00000000000000Tools to build a stand-alone Windows executable =============================================== Windows batch files to build a stand-alone Windows executable that can be distributed without the need to install Python. At this time the batch file only builds an executable for git-restore-mtime: git-restore-mtime.exe. Requirements ------------ - **Windows**. Tested with Windows 8.1 - **Git**. Tested in v2.17.1 and prior versions since 2010 - **Python**. Tested in Python 3.8.0. - **pip**. Tested with pip 19.3.1 - **setuptools**. Tested with setuptools 42.0.0 - **pyinstaller**. Tested with pyinstaller 4.0.dev0+1eadfa55f2 Automatic installation of requirements ----------------------------------- You can automatically perform the installation of all requirements by running the following command from an elevated command prompt: ```cmd build_windows_executable.bat /INIT ``` Manual installation of requirements ----------------------------------- The easiest way to install Git and Python on Windows is with Chocolatey (https://chocolatey.org). NOTE: The easiest way to run the installation commands below is with 'Run as administrator'. For pip.exe you could use a '--user' parameter to bypass this, but then you have to add the specific user directory to the PATH to make everything work. Installing Chocolatey (): ```cmd @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass ^ -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" ^ && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin" ``` Installing the latest Git and Python with Chocolatey: ```cmd choco.exe install Git choco.exe install Python ``` Upgrading pip and setuptools to the latest version: ```cmd pip.exe install --upgrade --trusted-host pypi.org --trusted-host files.pythonhosted.org pip setuptools ``` Installing the latest version of pyinstaller: ```cmd pip.exe install --trusted-host pypi.org --trusted-host files.pythonhosted.org ^ https://github.com/pyinstaller/pyinstaller/archive/develop.tar.gz ``` Creating the Windows Executable ------------------------------- If all dependencies are met, all you have to do is doubleclick (or run from a non-elevated command prompt): ``` build_windows_executable.bat ``` This should result in a 'dist\git-restore-mtime.exe' file. All other files that are created are temporary files: Both 'git-restore-mtime.spec' and the 'build/' directory can be discarded. git-tools-2022.12/windows/build_windows_executable.bat000066400000000000000000000034501435372702700230530ustar00rootroot00000000000000@ECHO OFF IF "%1"=="/INIT" GOTO InitializeEnvironment PUSHD "%~dp0" ECHO. ECHO Checking current python.exe location(s) where python.exe ECHO. ECHO Version info for Python/pip/pyinstaller: python.exe --version pip.exe --version pyinstaller.exe --version ECHO. ECHO Testing if current git-restore-mtime Python script works... python.exe ..\git-restore-mtime --help REM pyinstaller uses upx by default to compress the executable REM When running the created executable this results in an error: REM git-restore-mtime.exe - Bad Image: %TEMP%\VCRUNTIME140.dll REM is either not designed to run on Windows or it contains an error (..) REM Therefore run pyinstaller with the --noupx parameter pyinstaller.exe -F --noupx ..\git-restore-mtime ECHO. ECHO Testing if git-restore-mtime.exe works... dist\git-restore-mtime.exe --help PAUSE GOTO :EOF :InitializeEnvironment ECHO. ECHO NOTE: This script needs to run as administrator ECHO Press a key to install Chocolatey, Python and the required Python packages... PAUSE ECHO. ECHO Installing/updating Chocolatey... @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass ^ -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" ^ && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin" ECHO. ECHO Installing/updating Python... choco.exe install -y python ECHO. ECHO Upgrading pip and setuptools to latest version... pip.exe install --upgrade --trusted-host pypi.org --trusted-host files.pythonhosted.org pip setuptools ECHO. ECHO Installing latest version of pyinstaller... pip.exe install --trusted-host pypi.org --trusted-host files.pythonhosted.org ^ https://github.com/pyinstaller/pyinstaller/archive/develop.tar.gz ECHO. ECHO Finished! PAUSE GOTO :EOF git-tools-2022.12/windows/non-ascii-paths.txt000066400000000000000000000055441435372702700210550ustar00rootroot00000000000000For git-restore-mtime to work, path name encoding used by Git and Python must agree, and that might depend on the underlying filesystem encoding. So: - If filesystem encoding is UTF-8 normalization form C, it's all good. All hail Linux! - On Mac, HFS+ uses UTF-8, but not normalization form C, so letters with accents might use 2 Unicode code-points. Does Git properly deals with this? No idea. https://developer.apple.com/library/archive/technotes/tn/tn1150.html#UnicodeSubtleties https://stackoverflow.com/a/9758019/624066 - On Windows, native NTFS encoding *might* be UTF-16 or something else, and Git (on Windows) might or might not transcode that to UTF-8 norm C when storing. Git doc is not conclusive enough, depending on how you interpret this: https://github.com/git/git/blob/master/Documentation/i18n.txt Git is to some extent character encoding agnostic. - Path names are encoded in UTF-8 normalization form C. This applies to tree objects, the index file, ref names, as well as path names in command line arguments, environment variables and config files. + Note that Git at the core level treats path names simply as sequences of non-NUL bytes, there are no path name encoding conversions (except on Mac and Windows). Therefore, using non-ASCII path names will mostly work even on platforms and file systems that use legacy extended ASCII encodings. However, repositories created on such systems will not work properly on UTF-8-based systems (e.g. Linux, Mac, Windows) and vice versa. Additionally, many Git-based tools simply assume path names to be UTF-8 and will fail to display other encodings correctly. - Also worth reading: https://github.com/git-for-windows/git/wiki/FAQ, specially "Some native console programs don't work when run from Git Bash. How to fix it?" and https://github.com/msysgit/msysgit/wiki/Git-for-Windows-Unicode-Support - Terminal might play a role. Git for Windows apparently uses `minitty`, check if (and how) it performs transcoding. Same for PowerShell, if applicable. - Setting `git config core.quotepath off` might fix issues. On Mac, `core.precomposeunicode` may play a role. - Using `-z` in `ls-files` and `whatchanged` is an option to consider. For reading NUL-delimited data, see https://stackoverflow.com/q/9237246/624066 Bottom line, the following encodings must all agree with each other: - Git ls-files / whatchanged ASCII escaping when core.quotepath on (the default) - Git ls-files / whatchanged binary output when core.quotepath off - Python `Popen.stdout` decoding when using `universal_newlines=True`/`text=True`, (or specified `encoding`) if quotepath off - normalize() un-escape algorithm if quotepath on. It currently assumes UTF-8 escaping - paths in args.{pathspec,gitdir,workdir,...} - path parameter for os.utime(), os.path.dirname() (if args.pathspec)