pax_global_header00006660000000000000000000000064147627022030014515gustar00rootroot0000000000000052 comment=7a388ab6f02ff9f48657530a780b374d9930d157 git-delete-merged-branches-7.5.0/000077500000000000000000000000001476270220300165755ustar00rootroot00000000000000git-delete-merged-branches-7.5.0/.github/000077500000000000000000000000001476270220300201355ustar00rootroot00000000000000git-delete-merged-branches-7.5.0/.github/dependabot.yml000066400000000000000000000004751476270220300227730ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later version: 2 updates: - package-ecosystem: "github-actions" commit-message: include: "scope" prefix: "Actions" directory: "/" labels: - "enhancement" schedule: interval: "weekly" git-delete-merged-branches-7.5.0/.github/workflows/000077500000000000000000000000001476270220300221725ustar00rootroot00000000000000git-delete-merged-branches-7.5.0/.github/workflows/enforce-copies-of-help-output-in-sync.yml000066400000000000000000000023451476270220300320660ustar00rootroot00000000000000# Copyright (C) 2022 Sebastian Pipping # Licensed under GPL v3 or later name: Enforce that copies of --help output are in sync on: - pull_request - push jobs: run_pre_commit: name: Check if copies of --help output are in sync runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Set up Python 3.12 uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5.4.0 with: python-version: 3.12 - name: Install build dependencies run: | sudo apt-get install --no-install-recommends -y help2man - name: Install delete-merged-branches entry point script run: |- pip install \ --disable-pip-version-check \ --user \ --no-warn-script-location \ . echo "PATH=${HOME}/.local/bin:${PATH}" >> "${GITHUB_ENV}" - name: Check if the man page is in sync with --help output run: |- rm git-{delete-merged-branches,dmb}.1 # to enforce a diff for the generator to remove ./sync-manpages-with-help-output.sh git diff --exit-code -- git-{delete-merged-branches,dmb}.1 git-delete-merged-branches-7.5.0/.github/workflows/pre-commit-detect-outdated.yml000066400000000000000000000042021476270220300300440ustar00rootroot00000000000000# Copyright (c) 2022 Sebastian Pipping # Licensed under GPL v3 or later name: Detect outdated pre-commit hooks on: schedule: - cron: '0 16 * * 5' # Every Friday 4pm # NOTE: This will drop all permissions from GITHUB_TOKEN except metadata read, # and then (re)add the ones listed below: permissions: contents: write pull-requests: write jobs: pre_commit_detect_outdated: name: Detect outdated pre-commit hooks runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Set up Python 3.12 uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5.4.0 with: python-version: 3.12 - name: Install pre-commit run: |- pip install \ --disable-pip-version-check \ --no-warn-script-location \ --user \ pre-commit echo "PATH=${HOME}/.local/bin:${PATH}" >> "${GITHUB_ENV}" - name: Check for outdated hooks run: |- pre-commit autoupdate git diff -- .pre-commit-config.yaml - name: Create pull request from changes (if any) id: create-pull-request uses: peter-evans/create-pull-request@dd2324fc52d5d43c699a5636bcf19fceaa70c284 # v7.0.7 with: author: 'pre-commit ' base: master body: |- For your consideration. :warning: Please **CLOSE AND RE-OPEN** this pull request so that [further workflow runs get triggered](https://github.com/peter-evans/create-pull-request/blob/main/docs/concepts-guidelines.md#triggering-further-workflow-runs) for this pull request. branch: precommit-autoupdate commit-message: "pre-commit: Autoupdate" delete-branch: true draft: true labels: enhancement title: "pre-commit: Autoupdate" - name: Log pull request URL if: "${{ steps.create-pull-request.outputs.pull-request-url }}" run: | echo "Pull request URL is: ${{ steps.create-pull-request.outputs.pull-request-url }}" git-delete-merged-branches-7.5.0/.github/workflows/pre-commit.yml000066400000000000000000000010031476270220300247630ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later name: Run pre-commit on: - pull_request - push jobs: pre-commit: name: Run pre-commit runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5.4.0 with: python-version: 3.12 - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 git-delete-merged-branches-7.5.0/.github/workflows/run-tests.yml000066400000000000000000000016161476270220300246650ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later name: Run the test suite on: - pull_request - push jobs: run-tests: name: Run the test suite strategy: matrix: python-version: [3.9, 3.13] # no particular need for in-between versions runs-on: [macos-latest, ubuntu-latest] runs-on: ${{ matrix.runs-on }} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5.4.0 with: python-version: ${{ matrix.python-version }} - name: Run the test suite run: | set -x python3 --version pip3 install -U pip setuptools wheel pip3 install ".[tests]" # for test dependencies pip3 install -U pytest # for a test runner exec pytest -v -Wdefault -Werror git-delete-merged-branches-7.5.0/.gitignore000066400000000000000000000001021476270220300205560ustar00rootroot00000000000000/build/ /dist/ /git_delete_merged_branches.egg-info/ __pycache__/ git-delete-merged-branches-7.5.0/.pre-commit-config.yaml000066400000000000000000000007171476270220300230630ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v5.0.0 hooks: - id: check-merge-conflict - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.9.10 hooks: - id: ruff args: - --fix - id: ruff-format git-delete-merged-branches-7.5.0/LICENSE000066400000000000000000001045151476270220300176100ustar00rootroot00000000000000 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-delete-merged-branches-7.5.0/README.md000066400000000000000000000133441476270220300200610ustar00rootroot00000000000000[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit)](https://github.com/pre-commit/pre-commit) [![Run the test suite](https://github.com/hartwork/git-delete-merged-branches/actions/workflows/run-tests.yml/badge.svg)](https://github.com/hartwork/git-delete-merged-branches/actions/workflows/run-tests.yml) [![Packaging status](https://repology.org/badge/tiny-repos/git-delete-merged-branches.svg)](https://repology.org/project/git-delete-merged-branches/versions) # git-delete-merged-branches A convenient command-line tool helping you keep repositories clean. # Installation ```console # pip install git-delete-merged-branches ``` If you are using one of the distributions below, you can install `git-delete-merged-branches` through the respective package manager, e.g.: | Distribution | Command | | ------------ | ------- | | [Arch Linux (AUR)](https://aur.archlinux.org/packages/git-delete-merged-branches/) | `yay -S git-delete-merged-branches` | | [Debian GNU/Linux (>=bookworm)](https://packages.debian.org/bookworm/git-delete-merged-branches) | `apt install git-delete-merged-branches` | | [Gentoo Linux](https://packages.gentoo.org/packages/dev-vcs/git-delete-merged-branches) | `emerge -av dev-vcs/git-delete-merged-branches` | | [Homebrew](https://formulae.brew.sh/formula/git-delete-merged-branches) | `brew install git-delete-merged-branches` | | [MacPorts](https://ports.macports.org/port/py-git-delete-merged-branches/details/) | `port install py-git-delete-merged-branches` | | [NixOS](https://search.nixos.org/packages?query=git-delete-merged-branches) | `nix-shell -p git-delete-merged-branches` | | [Ubuntu (>=lunar/23.04)](https://packages.ubuntu.com/source/lunar/git-delete-merged-branches) | `apt install git-delete-merged-branches` | | [Void Linux](https://github.com/void-linux/void-packages/tree/master/srcpkgs/git-delete-merged-branches) | `xbps-install -S git-delete-merged-branches` | # Example ```console # git-delete-merged-branches Do you want to run "git remote update --prune" for 1 remote(s): - origin Update? [y/N] y Do you want to run "git pull --ff-only" for 1 branch(es): - master Pull? [y/N] y You are about to delete 6 local branch(es): - improve-setup-py - issue-12-enable-ci-for-pull-requests - issue-5-fix-waste-of-one-second-per-service - keep-github-actions-up-to-date - refactoring-one - simple-ci Delete? [y/N] y 6 local branch(es) deleted. You are about to delete 6 remote branch(es): - origin/improve-setup-py - origin/issue-12-enable-ci-for-pull-requests - origin/issue-5-fix-waste-of-one-second-per-service - origin/keep-github-actions-up-to-date - origin/refactoring-one - origin/simple-ci Delete? [y/N] y To github.com:hartwork/wait-for-it.git - [deleted] improve-setup-py - [deleted] issue-12-enable-ci-for-pull-requests - [deleted] issue-5-fix-waste-of-one-second-per-service - [deleted] keep-github-actions-up-to-date - [deleted] refactoring-one - [deleted] simple-ci 6 remote branch(es) deleted. ``` # Features - Supports deletion of both local and remote branches - Detects multiple forms of de-facto merges (rebase merges, squash merges (needs `--effort=3`), single or range cherry-picks… leveraging `git cherry`) - Supports workflows with multiple release branches, e.g. only delete branches that have been merged to *all* of `master`, `dev` and `staging` - Quick interactive configuration - Provider agnostic: Works with GitHub, GitLab, Gitea and any other Git hosting - Takes safety seriously # Safety Deletion is a sharp knife that requires care. While `git reflog` would have your back in most cases, `git-delete-merged-branches` takes safety seriously. Here's what `git-delete-merged-branches` does for your safety: - No branches are deleted without confirmation or passing `--yes`. - Confirmation defaults to "no"; plain `[Enter]`/`[Return]` does not delete. - `git push` is used with `--force-with-lease` so if the server and you have a different understanding of that branch, it is not deleted. - There is no use of `os.system` or shell code to go wrong. - With `--dry-run` you can get a feel for the changes that `git-delete-merged-branches` would be making to your branches. - Show any Git commands run using `--verbose`. # Best Practices When the repository is a fork (with an upstream remote and a fork remote): - Make sure that release branches are tracking the right remote, e.g. `master` should probably track original upstream's `master` rather than `master` of your fork. - Consider keeping your fork's remote `master` up to date (using `git push`). When using GitHub: - You can make GitHub [delete branches of merged pull requests](https://docs.github.com/en/github/administering-a-repository/managing-the-automatic-deletion-of-branches) for you, to save `git-delete-merged-branches` some work on the remote side, if you like. # Name clash on "git-delete-merged-branches" with git-extras Utility collection [git-extras](https://github.com/tj/git-extras) provides a [simple shell script named `git-delete-merged-branches`](https://github.com/tj/git-extras/blob/master/bin/git-delete-merged-branches) that competes for command `git-delete-merged-branches` when both software packages are installed. To address this conflict you can: - a) Invoke `python3 -m git_delete_merged_branches` instead of `git-delete-merged-branches` - b) Invoke command `git-dmb` instead of `git-delete-merged-branches` - c) Control path resolution order through environment variable `$PATH` - d) Invoke `git-delete-merged-branches` with its absolute path. You can run `which -a git-delete-merged-branches` to see where it's located. # Support Please report any bugs that you find. Like this tool? Support it with a star! git-delete-merged-branches-7.5.0/git-delete-merged-branches.1000066400000000000000000000045501476270220300237320ustar00rootroot00000000000000.\" DO NOT MODIFY THIS FILE! It was generated by help2man. .TH GIT-DELETE-MERGED-BRANCHES "1" "March 2025" "git-delete-merged-branches 7.5.0" "User Commands" .SH NAME git-delete-merged-branches \- Command-line tool to delete merged Git branches .SH SYNOPSIS .B git\-delete\-merged\-branches [\fB\-\-configure\fR | \fB\-\-help\fR | \fB\-\-version\fR\] [\fB\-\-branch\fR BRANCH] [\fB\-\-effort\fR LEVEL] [\fB\-\-remote\fR REMOTE] [\fB\-\-exclude\fR BRANCH] [\fB\-\-include\-regex\fR PATTERN] [\fB\-\-debug\fR] [\fB\-\-dry\-run\fR] [\fB\-\-verbose\fR] [\fB\-\-yes\fR] .SH DESCRIPTION .PP Command\-line tool to delete merged Git branches .SS "modes:" .TP \fB\-\-configure\fR configure .B git\-delete\-merged\-branches and exit (without processing any branches) .TP \fB\-\-help\fR, \fB\-h\fR show this help message and exit .TP \fB\-\-version\fR show program's version number and exit .SS "rules:" .TP \fB\-\-branch\fR BRANCH, \fB\-b\fR BRANCH require the given branch as a merge target (instead of what is configured for this repository); can be passed multiple times .TP \fB\-\-effort\fR LEVEL level of effort to put into finding merged branches; level 1 uses nothing but "git branch \-\-merged", level 2 adds use of "git cherry", level 3 adds use of "git cherry" on temporary squashed copies (default level: 2) .SS "scope:" .TP \fB\-\-remote\fR REMOTE, \fB\-r\fR REMOTE process the given remote (instead of the remotes that are configured for this repository); can be passed multiple times .TP \fB\-\-exclude\fR BRANCH, \fB\-x\fR BRANCH exclude the given branch from deletion (in addition to the exclusion list that is configured for this repository); can be passed multiple times .TP \fB\-\-include\-regex\fR PATTERN only consider branches for deletion that match the given regular expression (e.g. "^issue\-"); syntax is that of Python module "re"; can be passed multiple times, then acts in logical conjunction ("and") .SS "flags:" .TP \fB\-\-debug\fR enable debugging output .TP \fB\-\-dry\-run\fR, \fB\-n\fR perform a trial run with no changes made .TP \fB\-\-verbose\fR, \fB\-v\fR enable verbose output .TP \fB\-\-yes\fR, \fB\-y\fR do not ask for confirmation, assume reply "yes" .PP .SH EPILOG Software libre licensed under GPL v3 or later. Brought to you by Sebastian Pipping . .PP Please report bugs at https://github.com/hartwork/git\-delete\-merged\-branches — thank you! git-delete-merged-branches-7.5.0/git-dmb.1000066400000000000000000000044321476270220300202050ustar00rootroot00000000000000.\" DO NOT MODIFY THIS FILE! It was generated by help2man. .TH GIT-DMB "1" "March 2025" "git-dmb 7.5.0" "User Commands" .SH NAME git-dmb \- Command-line tool to delete merged Git branches .SH SYNOPSIS .B git\-dmb [\fB\-\-configure\fR | \fB\-\-help\fR | \fB\-\-version\fR\] [\fB\-\-branch\fR BRANCH] [\fB\-\-effort\fR LEVEL] [\fB\-\-remote\fR REMOTE] [\fB\-\-exclude\fR BRANCH] [\fB\-\-include\-regex\fR PATTERN] [\fB\-\-debug\fR] [\fB\-\-dry\-run\fR] [\fB\-\-verbose\fR] [\fB\-\-yes\fR] .SH DESCRIPTION .PP Command\-line tool to delete merged Git branches .SS "modes:" .TP \fB\-\-configure\fR configure .B git\-delete\-merged\-branches and exit (without processing any branches) .TP \fB\-\-help\fR, \fB\-h\fR show this help message and exit .TP \fB\-\-version\fR show program's version number and exit .SS "rules:" .TP \fB\-\-branch\fR BRANCH, \fB\-b\fR BRANCH require the given branch as a merge target (instead of what is configured for this repository); can be passed multiple times .TP \fB\-\-effort\fR LEVEL level of effort to put into finding merged branches; level 1 uses nothing but "git branch \-\-merged", level 2 adds use of "git cherry", level 3 adds use of "git cherry" on temporary squashed copies (default level: 2) .SS "scope:" .TP \fB\-\-remote\fR REMOTE, \fB\-r\fR REMOTE process the given remote (instead of the remotes that are configured for this repository); can be passed multiple times .TP \fB\-\-exclude\fR BRANCH, \fB\-x\fR BRANCH exclude the given branch from deletion (in addition to the exclusion list that is configured for this repository); can be passed multiple times .TP \fB\-\-include\-regex\fR PATTERN only consider branches for deletion that match the given regular expression (e.g. "^issue\-"); syntax is that of Python module "re"; can be passed multiple times, then acts in logical conjunction ("and") .SS "flags:" .TP \fB\-\-debug\fR enable debugging output .TP \fB\-\-dry\-run\fR, \fB\-n\fR perform a trial run with no changes made .TP \fB\-\-verbose\fR, \fB\-v\fR enable verbose output .TP \fB\-\-yes\fR, \fB\-y\fR do not ask for confirmation, assume reply "yes" .PP .SH EPILOG Software libre licensed under GPL v3 or later. Brought to you by Sebastian Pipping . .PP Please report bugs at https://github.com/hartwork/git\-delete\-merged\-branches — thank you! git-delete-merged-branches-7.5.0/git_delete_merged_branches/000077500000000000000000000000001476270220300240725ustar00rootroot00000000000000git-delete-merged-branches-7.5.0/git_delete_merged_branches/__init__.py000066400000000000000000000000001476270220300261710ustar00rootroot00000000000000git-delete-merged-branches-7.5.0/git_delete_merged_branches/__main__.py000066400000000000000000000002371476270220300261660ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later from ._cli import main if __name__ == "__main__": main() git-delete-merged-branches-7.5.0/git_delete_merged_branches/_argparse_color.py000066400000000000000000000025711476270220300276120ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later import re import colorama _SECTION_COLOR = colorama.Fore.WHITE + colorama.Style.BRIGHT _ARGUMENT_COLOR = colorama.Fore.GREEN + colorama.Style.BRIGHT _PARAMETER_COLOR = colorama.Fore.GREEN _PROG_COLOR = colorama.Fore.CYAN + colorama.Style.BRIGHT _URL_COLOR = colorama.Fore.MAGENTA + colorama.Style.BRIGHT _RESET_COLOR = colorama.Style.RESET_ALL _SUBSTITUTIONS = ( ("^([^ ].+):$", f"{_SECTION_COLOR}\\1{_RESET_COLOR}:"), ( "(? # Licensed under GPL v3 or later import argparse import os import sys import traceback from argparse import RawDescriptionHelpFormatter from functools import partial from signal import SIGINT from subprocess import CalledProcessError from textwrap import dedent import colorama from ._argparse_color import add_color_to_formatter_class from ._confirm import Confirmation from ._engine import DeleteMergedBranches from ._git import Git from ._messenger import Messenger from ._metadata import APP, DESCRIPTION, VERSION from ._multiselect import multiselect def _parse_command_line(colorize: bool, args=None): _EPILOG = dedent(f"""\ Software libre licensed under GPL v3 or later. Brought to you by Sebastian Pipping . Please report bugs at https://github.com/hartwork/{APP} — thank you! """) if args is None: args = sys.argv[1:] formatter_class = RawDescriptionHelpFormatter if colorize: formatter_class = add_color_to_formatter_class(formatter_class) prog = os.path.basename(sys.argv[0]) parser = argparse.ArgumentParser( prog=prog, add_help=False, description=DESCRIPTION, epilog=_EPILOG, formatter_class=formatter_class, ) modes = parser.add_argument_group("modes").add_mutually_exclusive_group() modes.add_argument( "--configure", dest="force_reconfiguration", action="store_true", help=f"configure {APP} and exit (without processing any branches)", ) modes.add_argument("--help", "-h", action="help", help="show this help message and exit") modes.add_argument("--version", action="version", version="%(prog)s " + VERSION) rules = parser.add_argument_group("rules") rules.add_argument( "--branch", "-b", metavar="BRANCH", dest="required_target_branches", default=[], action="append", help="require the given branch as a merge target (instead of what is" " configured for this repository); can be passed multiple times", ) rules.add_argument( "--effort", metavar="LEVEL", dest="effort_level", type=int, default=2, choices=[1, 2, 3], help=( "level of effort to put into finding merged branches" '; level 1 uses nothing but "git branch --merged"' ', level 2 adds use of "git cherry"' ', level 3 adds use of "git cherry" on temporary squashed copies' " (default level: %(default)d)" ), ) scope = parser.add_argument_group("scope") scope.add_argument( "--remote", "-r", metavar="REMOTE", dest="enabled_remotes", default=[], action="append", help=( "process the given remote (instead of the remotes that are" " configured for this repository); can be passed multiple times" ), ) scope.add_argument( "--exclude", "-x", metavar="BRANCH", dest="excluded_branches", default=[], action="append", help=( "exclude the given branch from deletion (in addition to" " the exclusion list that is configured for this repository)" "; can be passed multiple times" ), ) scope.add_argument( "--include-regex", metavar="PATTERN", dest="included_branches_patterns", default=[], action="append", help=( "only consider branches for deletion that match the given" ' regular expression (e.g. "^issue-")' '; syntax is that of Python module "re"' "; can be passed multiple times" ', then acts in logical conjunction ("and")' ), ) switches = parser.add_argument_group("flags") switches.add_argument( "--debug", dest="debug", action="store_true", help="enable debugging output" ) switches.add_argument( "--dry-run", "-n", dest="pretend", action="store_true", help="perform a trial run with no changes made", ) switches.add_argument( "--verbose", "-v", dest="verbose", action="store_true", help="enable verbose output" ) switches.add_argument( "--yes", "-y", dest="ask", default=True, action="store_false", help='do not ask for confirmation, assume reply "yes"', ) return parser.parse_args(args) def _innermost_main(config, messenger, colorize: bool): git = Git(messenger, pretend=config.pretend, verbose=config.verbose) confirmation = Confirmation(messenger, ask=config.ask) selector = partial(multiselect, colorize=colorize) dmb = DeleteMergedBranches(git, messenger, confirmation, selector, config.effort_level) git_config = dmb.ensure_configured(config.force_reconfiguration) if config.force_reconfiguration: return required_target_branches = dmb.determine_required_target_branches( git_config, config.required_target_branches ) excluded_branches = dmb.determine_excluded_branches( git_config, config.excluded_branches, config.included_branches_patterns ) enabled_remotes = dmb.determine_enabled_remotes(git_config, config.enabled_remotes) dmb.refresh_remotes(enabled_remotes) dmb.detect_stale_remotes(enabled_remotes, required_target_branches) dmb.refresh_target_branches(required_target_branches) dmb.delete_merged_branches(required_target_branches, excluded_branches, enabled_remotes) def _inner_main(): colorize = "NO_COLOR" not in os.environ if colorize: colorama.init() messenger = Messenger(colorize=colorize) config = _parse_command_line(colorize=colorize) try: _innermost_main(config, messenger, colorize) except CalledProcessError as e: # Produce more human-friendly output than str(e) message = f"Command '{' '.join(e.cmd)}' returned non-zero exit status {e.returncode}." messenger.tell_error(message) sys.exit(1) except Exception as e: if config.debug: traceback.print_exc() messenger.tell_error(str(e)) sys.exit(1) def main(): try: _inner_main() except KeyboardInterrupt: sys.exit(128 + SIGINT) git-delete-merged-branches-7.5.0/git_delete_merged_branches/_confirm.py000066400000000000000000000013541476270220300262430ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later class Confirmation: _CONFIRM_GOOD = ("y", "Y") _CONFIRM_BAD = ("", "n", "N") _CONFIRM_KNOWN = _CONFIRM_GOOD + _CONFIRM_BAD def __init__(self, messenger, ask): self._messenger = messenger self._ask = ask def confirmed(self, question): if not self._ask: return True question = self._messenger.format_question(question) self._messenger.produce_air() while True: reply = input(f"{question} [y/N] ") if reply in self._CONFIRM_KNOWN: break self._messenger.request_air(question) return reply in self._CONFIRM_GOOD git-delete-merged-branches-7.5.0/git_delete_merged_branches/_engine.py000066400000000000000000000600341476270220300260530ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later import os import re from functools import partial, reduce from operator import and_ from subprocess import CalledProcessError from typing import Optional from ._git import CheckoutFailed, MergeBaseFailed, PullFailed from ._metadata import APP class _DmbException(Exception): pass class _GitRepositoryWithoutBranches(_DmbException): """ Exception for the time between "git init" and the first "git commit" where "git branch" will tell us that there are no branches """ def __init__(self): super().__init__("This Git repository does not have any branches.") class _NoSuchBranchException(_DmbException): def __init__(self, branch_name): super().__init__(f"There is no branch {branch_name!r}.") class _NoSuchRemoteException(_DmbException): def __init__(self, remote_name): super().__init__(f"There is no remote {remote_name!r}.") class _TooFewOptionsAvailable(_DmbException): pass class _ZeroMergeTargetsException(_DmbException): def __init__(self): super().__init__("One or more existing target branch is required.") class _InvalidRegexPattern(_DmbException): def __init__(self, pattern): super().__init__( f'Pattern "{pattern}" is not well-formed regular expression syntax ' '(with regard to Python module "re").' ) class _CannotDryRunConfigurationError(_DmbException): def __init__(self, force_reconfiguration): message = ( "Arguments --configure and --dry-run are not compatible." if force_reconfiguration else f"{APP}' need for configuration and argument --dry-run are not compatible." ) super().__init__(message) class DeleteMergedBranches: _CONFIG_KEY_CONFIGURED = "delete-merged-branches.configured" _CONFIG_VALUE_CONFIGURED = "5.0.0+" # i.e. most ancient version with compatible config _CONFIG_VALUE_TRUE = "true" _PATTERN_REMOTE_ENABLED = "^remote\\.(?P[^ ]+)\\.dmb-enabled$" _PATTERN_BRANCH_EXCLUDED = "^branch\\.(?P[^ ]+)\\.dmb-excluded$" _PATTERN_BRANCH_REQUIRED = "^branch\\.(?P[^ ]+)\\.dmb-required$" _FORMAT_REMOTE_ENABLED = "remote.{name}.dmb-enabled" _FORMAT_BRANCH_EXCLUDED = "branch.{name}.dmb-excluded" _FORMAT_BRANCH_REQUIRED = "branch.{name}.dmb-required" def __init__(self, git, messenger, confirmation, selector, effort_level): self._confirmation = confirmation self._messenger = messenger self._git = git self._selector = selector self._effort_using_git_cherry = effort_level >= 2 self._effort_using_squashed_copies = effort_level >= 3 def _interactively_edit_list( self, description, valid_names, old_names, format, min_selection_count ) -> set[str]: if len(valid_names) < min_selection_count: raise _TooFewOptionsAvailable help = ( "(Press [Space] to toggle selection, [Enter]/[Return] to accept, [Ctrl]+[C] to quit.)" ) old_names = set(old_names) initial_selection = [i for i, name in enumerate(valid_names) if name in old_names] if valid_names: new_names = set( self._selector( self._messenger, valid_names, initial_selection, description, help, min_selection_count, ) ) else: new_names = set() assert len(new_names) >= min_selection_count names_to_remove = old_names - new_names names_to_add = new_names - old_names for names, new_value in ((names_to_remove, None), (names_to_add, self._CONFIG_VALUE_TRUE)): for name in names: key = format.format(name=name) self._git.set_config(key, new_value) return new_names def _configure_required_branches(self, git_config) -> set[str]: try: return self._interactively_edit_list( "[1/3] For a branch to be considered" " fully merged, which other branches" " must it have been merged to?", self._git.find_local_branches(), self.find_required_branches(git_config), self._FORMAT_BRANCH_REQUIRED, min_selection_count=1, ) except _TooFewOptionsAvailable: raise _GitRepositoryWithoutBranches def _configure_excluded_branches(self, git_config, new_required_branches: set[str]): valid_names = sorted(set(self._git.find_all_branch_names()) - new_required_branches) self._interactively_edit_list( "[2/3] Which of these branches (if any) should be kept around at all times?", valid_names, self.find_excluded_branches(git_config), self._FORMAT_BRANCH_EXCLUDED, min_selection_count=0, ) def _configure_enabled_remotes(self, git_config): self._interactively_edit_list( "[3/3] Which remotes (if any) do you want to enable deletion of merged branches for?", self._git.find_remotes(), self.find_enabled_remotes(git_config), self._FORMAT_REMOTE_ENABLED, min_selection_count=0, ) def _configure(self, git_config): repo_basename = os.path.basename(os.getcwd()) self._messenger.tell_info(f"Configure {APP} for repository {repo_basename!r}:") new_required_branches = self._configure_required_branches(git_config) self._configure_excluded_branches(git_config, new_required_branches) self._configure_enabled_remotes(git_config) self._git.set_config(self._CONFIG_KEY_CONFIGURED, self._CONFIG_VALUE_CONFIGURED) @classmethod def _is_configured(cls, git_config): return git_config.get(cls._CONFIG_KEY_CONFIGURED) == cls._CONFIG_VALUE_CONFIGURED def ensure_configured(self, force_reconfiguration): git_config = self._git.extract_git_config() if force_reconfiguration or not self._is_configured(git_config): if self._git.pretend: raise _CannotDryRunConfigurationError(force_reconfiguration) self._configure(git_config) git_config = self._git.extract_git_config() assert self._is_configured(git_config) return git_config @classmethod def _filter_git_config(cls, git_config, pattern): matcher = re.compile(pattern) matched_names = [] for key, value in git_config.items(): match = matcher.match(key) if match and value == cls._CONFIG_VALUE_TRUE: matched_names.append(match.group("name")) return matched_names @classmethod def find_excluded_branches(cls, git_config): return cls._filter_git_config(git_config, cls._PATTERN_BRANCH_EXCLUDED) @classmethod def find_required_branches(cls, git_config): return cls._filter_git_config(git_config, cls._PATTERN_BRANCH_REQUIRED) @classmethod def find_enabled_remotes(cls, git_config): return cls._filter_git_config(git_config, cls._PATTERN_REMOTE_ENABLED) def _find_branches_merged_using_git_branch_merged( self, required_target_branches, remote_name: Optional[str] ) -> set[str]: if remote_name is None: find_branches_that_were_merged_into = self._git.find_merged_local_branches_for else: find_branches_that_were_merged_into = partial( self._git.find_merged_remote_branches_for, remote_name ) if len(required_target_branches) == 1: target_branch = next(iter(required_target_branches)) branches_merged_to_all_required_targets = set( find_branches_that_were_merged_into(target_branch) ) else: branches_merged_to_all_required_targets = reduce( and_, ( set(find_branches_that_were_merged_into(target_branch)) for target_branch in required_target_branches ), ) return branches_merged_to_all_required_targets def _has_been_squash_merged_into(self, target_branch, topic_branch) -> bool: """ Tries to detect a squashed merge, i.e. where a single commit on the target branch pulls in the sum of all commits between the common merge base commit and the tip of the topic branch. The implementation creates a temporary squashed copy of those commits and then asks ``git cherry`` if that squashed commit has an equivalent on the target branch. """ try: merge_base_commit_sha1 = self._git.merge_base(target_branch, topic_branch) except MergeBaseFailed: return False squash_merge_commit_sha1 = self._git.commit_tree( message=f"Squash-merge {topic_branch!r}", parent_committish=merge_base_commit_sha1, tree=topic_branch + "^{tree}", ) cherry_lines = self._git.cherry(target_branch, squash_merge_commit_sha1) defacto_merged_into_target = all(line.startswith("-") for line in cherry_lines) return defacto_merged_into_target def _find_branches_merged_using_git_cherry( self, required_target_branches, candidate_branches ) -> set[str]: assert required_target_branches if not candidate_branches: return set() branches_merged_to_all_required_targets = set() candidates_for_squashed_merges = [] for topic_branch in sorted(candidate_branches): assert topic_branch not in required_target_branches for target_branch in sorted(required_target_branches): cherry_lines = self._git.cherry(target_branch, topic_branch) defacto_merged_into_target = all(line.startswith("-") for line in cherry_lines) if not defacto_merged_into_target: if len(cherry_lines) > 1: candidates_for_squashed_merges.append(topic_branch) break else: # i.e. no break happened above branches_merged_to_all_required_targets.add(topic_branch) if self._effort_using_squashed_copies: check_for_squash_merges = True if candidates_for_squashed_merges: if self._git.has_detached_heads(): self._messenger.tell_info( "Skipped further inspection of branches because of detached HEAD." ) check_for_squash_merges = False if check_for_squash_merges: if self._git.has_uncommitted_changes(): self._messenger.tell_info( "Skipped further inspection of branches due to uncommitted changes." ) check_for_squash_merges = False if check_for_squash_merges: for topic_branch in candidates_for_squashed_merges: for target_branch in sorted(required_target_branches): defacto_merged_into_target = self._has_been_squash_merged_into( target_branch=target_branch, topic_branch=topic_branch ) if not defacto_merged_into_target: break else: # i.e. no break happened above branches_merged_to_all_required_targets.add(topic_branch) return branches_merged_to_all_required_targets def _find_branches_merged_to_all_targets_for_single_remote( self, required_target_branches, excluded_branches: set[str], remote_name: Optional[str] ) -> tuple[set[str], set[str]]: if remote_name is not None: excluded_branches = { f"{remote_name}/{branch_name}" for branch_name in excluded_branches } truly_merged_branches = ( self._find_branches_merged_using_git_branch_merged( required_target_branches, remote_name=remote_name ) ) - excluded_branches if self._effort_using_git_cherry: if remote_name is None: all_branches_at_remote = set(self._git.find_local_branches()) else: all_branches_at_remote = set(self._git.find_remote_branches_at(remote_name)) if remote_name is not None: required_target_branches = { f"{remote_name}/{branch_name}" for branch_name in required_target_branches } branches_to_inspect_using_git_cherry = ( all_branches_at_remote - required_target_branches - excluded_branches - truly_merged_branches ) defacto_merged_branches = self._find_branches_merged_using_git_cherry( required_target_branches, branches_to_inspect_using_git_cherry ) else: defacto_merged_branches = set() return (truly_merged_branches, defacto_merged_branches) def _report_branches_as_deleted(self, branch_names: set[str], remote_name: str = None): branch_type = "local" if (remote_name is None) else "remote" info_text = f"{len(branch_names)} {branch_type} branch(es) deleted." self._messenger.tell_info(info_text) def _delete_local_merged_branches_for(self, required_target_branches, excluded_branches): for working_tree_branch in self._git.find_working_tree_branches(): branch_would_be_analyzed = ( working_tree_branch is not None and working_tree_branch not in required_target_branches and working_tree_branch not in excluded_branches ) if branch_would_be_analyzed: excluded_branches = excluded_branches | {working_tree_branch} self._messenger.tell_info( f"Skipped branch {working_tree_branch!r} because it is currently checked out." ) truly_merged, defacto_merged = self._find_branches_merged_to_all_targets_for_single_remote( required_target_branches, excluded_branches, remote_name=None ) local_branches_to_delete = truly_merged | defacto_merged if not local_branches_to_delete: self._messenger.tell_info("No local branches deleted.") return description = ( f"You are about to delete {len(local_branches_to_delete)}" " local branch(es):\n" + "\n".join(f" - {name}" for name in sorted(local_branches_to_delete)) + "\n\nDelete?" ) if not self._confirmation.confirmed(description): return # NOTE: With regard to reporting, the idea is to # - report all deleted local branches at once when deletion was successful, and to # - not silence partial success # when the first delete call was successful and the second call was not. self._git.delete_local_branches(truly_merged) try: self._git.delete_local_branches(defacto_merged, force=True) except CalledProcessError: self._report_branches_as_deleted(truly_merged) raise else: self._report_branches_as_deleted(truly_merged | defacto_merged) def _delete_remote_merged_branches_for( self, required_target_branches, excluded_branches, remote_name, all_branch_refs: set[str] ): if not all( (f"{remote_name}/{branch_name}" in all_branch_refs) for branch_name in required_target_branches ): self._messenger.tell_info( f"Skipped remote {remote_name!r} as it does not have all required branches." ) return truly_merged, defacto_merged = self._find_branches_merged_to_all_targets_for_single_remote( required_target_branches, excluded_branches, remote_name=remote_name ) remote_branches_to_delete = [ b for b in (truly_merged | defacto_merged) if b.startswith(f"{remote_name}/") ] if not remote_branches_to_delete: self._messenger.tell_info("No remote branches deleted.") return description = ( f"You are about to delete {len(remote_branches_to_delete)} " "remote branch(es):\n" + "\n".join(f" - {name}" for name in sorted(remote_branches_to_delete)) + "\n\nDelete?" ) if not self._confirmation.confirmed(description): return self._git.delete_remote_branches(remote_branches_to_delete, remote_name) self._report_branches_as_deleted(remote_branches_to_delete, remote_name) def refresh_remotes(self, enabled_remotes): sorted_remotes = sorted(set(enabled_remotes)) if not sorted_remotes: return description = ( f'Do you want to run "git remote update --prune"' f" for {len(sorted_remotes)} remote(s):\n" + "\n".join(f" - {name}" for name in sorted_remotes) + "\n\nUpdate?" ) if not self._confirmation.confirmed(description): return for remote_name in sorted_remotes: self._git.update_and_prune_remote(remote_name) def detect_stale_remotes(self, enabled_remotes, required_target_branches): sorted_remotes = sorted(set(enabled_remotes)) if not sorted_remotes: return sorted_required_target_branches = sorted(set(required_target_branches)) assert sorted_required_target_branches for remote_name in enabled_remotes: remote_branches = set(self._git.find_remote_branches_at(remote_name)) not_fully_pushed_branches = [ branch for branch in sorted_required_target_branches if f"{remote_name}/{branch}" in remote_branches and self._git.has_unpushed_commits_on( branch, with_regard_to=f"{remote_name}/{branch}" ) ] if not_fully_pushed_branches: self._messenger.tell_info( ( f"Remote {remote_name!r} is not up to date with" f" {len(not_fully_pushed_branches)} local" " branch(es):\n" ) + "\n".join(f" - {branch}" for branch in not_fully_pushed_branches) + ( "\n\nThis will likely impair detection" f" of merged branches for remote {remote_name!r}." "\nPlease consider getting it back in sync" " by running\n" ) + "\n".join( f" $ git push {remote_name} {branch}" for branch in not_fully_pushed_branches ) + f"\n\nand then invoking {APP}, again." ) def refresh_target_branches(self, required_target_branches): sorted_branches = sorted(set(required_target_branches)) if not sorted_branches: return initial_branch = self._git.find_current_branch() if initial_branch is None or self._git.has_detached_heads(): self._messenger.tell_info("Skipped refreshing branches because of detached HEAD.") return if self._git.has_uncommitted_changes(): self._messenger.tell_info("Skipped refreshing branches due to uncommitted changes.") return description = ( f'Do you want to run "git pull --ff-only"' f" for {len(sorted_branches)} branch(es):\n" + "\n".join(f" - {name}" for name in sorted_branches) + "\n\nPull?" ) if not self._confirmation.confirmed(description): return needs_a_switch_back = False try: for branch_name in sorted_branches: if branch_name != initial_branch: try: self._git.checkout(branch_name) except CheckoutFailed: self._messenger.tell_error( f"Refreshing local branch {branch_name!r}" " failed" " because the branch cannot be checkout out." ) continue needs_a_switch_back = True try: self._git.pull_ff_only() except PullFailed: self._messenger.tell_error( f"Refreshing local branch {branch_name!r} failed" " because the branch cannot be pulled" " with fast forward." ) finally: if needs_a_switch_back: self._git.checkout(initial_branch) def delete_merged_branches(self, required_target_branches, excluded_branches, enabled_remotes): self._delete_local_merged_branches_for(required_target_branches, excluded_branches) all_branch_refs = set(self._git.find_all_branch_refs()) for remote_name in enabled_remotes: self._delete_remote_merged_branches_for( required_target_branches, excluded_branches, remote_name, all_branch_refs ) def determine_excluded_branches( self, git_config: dict, excluded_branches: list[str], included_branches_patterns: list[str] ) -> set[str]: existing_branches = set(self._git.find_all_branch_names()) if excluded_branches: excluded_branches_set = set(excluded_branches) invalid_branches = excluded_branches_set - existing_branches if invalid_branches: raise _NoSuchBranchException(sorted(invalid_branches)[0]) else: excluded_branches_set = set() excluded_branches_set |= set(self.find_excluded_branches(git_config)) & existing_branches # The inclusion patterns are meant to work in logical conjunction ("and") but an empty # list should not exclude any branches. So we'll add any existing branch to the exclusion # set that fails to match any of the inclusion patterns: for included_branches_pattern in included_branches_patterns: try: matcher = re.compile(included_branches_pattern) except re.error: raise _InvalidRegexPattern(included_branches_pattern) for branch_name in existing_branches: if matcher.search(branch_name): continue excluded_branches_set.add(branch_name) return excluded_branches_set def determine_required_target_branches( self, git_config: dict, required_target_branches: list[str] ): existing_branches = set(self._git.find_local_branches()) if required_target_branches: required_target_branches_set = set(required_target_branches) invalid_branches = required_target_branches_set - existing_branches if invalid_branches: raise _NoSuchBranchException(required_target_branches[0]) else: required_target_branches_set = ( set(self.find_required_branches(git_config)) & existing_branches ) if not required_target_branches_set: raise _ZeroMergeTargetsException return required_target_branches_set def determine_enabled_remotes(self, git_config: dict, enabled_remotes: list[str]): existing_remotes = set(self._git.find_remotes()) if enabled_remotes: enabled_remotes_set = set(enabled_remotes) invalid_remotes = enabled_remotes_set - existing_remotes if invalid_remotes: raise _NoSuchRemoteException(enabled_remotes[0]) return enabled_remotes_set else: return set(self.find_enabled_remotes(git_config)) & existing_remotes git-delete-merged-branches-7.5.0/git_delete_merged_branches/_git.py000066400000000000000000000270431476270220300253740ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later import os import subprocess from collections import OrderedDict from typing import Optional from ._metadata import APP class GitException(Exception): pass class CheckoutFailed(GitException): pass class PullFailed(GitException): pass class MergeBaseFailed(GitException): pass class Git: _GIT = "git" _GIT_ENCODING = "utf-8" _APP_EMAIL = f"{APP}@localhost" _ARBITRARY_FIXED_DATETIME = "2005-12-21T00:00:00+00:00" # release date of Git 1.0.0 _COMMIT_ENVIRON = { "GIT_AUTHOR_DATE": _ARBITRARY_FIXED_DATETIME, "GIT_AUTHOR_EMAIL": _APP_EMAIL, "GIT_AUTHOR_NAME": APP, "GIT_COMMITTER_DATE": _ARBITRARY_FIXED_DATETIME, "GIT_COMMITTER_EMAIL": _APP_EMAIL, "GIT_COMMITTER_NAME": APP, } def __init__(self, messenger, pretend, verbose, work_dir=None): self._messenger = messenger self._verbose = verbose self._pretend = pretend self._working_directory = work_dir @property def pretend(self): return self._pretend def _wrap_subprocess(self, subprocess_function, argv, is_write, pretend_result, env): pretend = is_write and self._pretend if self._verbose: comment = "skipped due to --dry-run" if pretend else "" display_argv = [a for a in argv if not a.startswith("--format=")] self._messenger.tell_command(display_argv, comment) if pretend: return pretend_result return subprocess_function(argv, cwd=self._working_directory, env=env) def _subprocess_check_output(self, argv, is_write, env=None): return self._wrap_subprocess( subprocess.check_output, argv=argv, is_write=is_write, pretend_result=b"", env=env ) def _subprocess_check_call(self, argv, is_write, env=None): return self._wrap_subprocess( subprocess.check_call, argv=argv, is_write=is_write, pretend_result=0, env=env ) @classmethod def _output_bytes_to_lines(cls, output_bytes) -> list[str]: text = output_bytes.decode(cls._GIT_ENCODING).rstrip() if not text: # protect against this: ''.split('\n') -> [''] return [] return text.split("\n") def extract_git_config(self): argv = [self._GIT, "config", "--list", "--null"] output_bytes = self._subprocess_check_output(argv, is_write=False) key_newline_value_list = [ chunk.decode(self._GIT_ENCODING) for chunk in output_bytes.split(b"\0") ] git_config = OrderedDict() for key_newline_value in key_newline_value_list: if not key_newline_value: continue try: key, value = key_newline_value.split("\n", 1) except ValueError: self._messenger.tell_info( f"Git config option {key_newline_value!r} lacks assignment of a value." ) continue git_config[key] = value return git_config def find_remotes(self): argv = [self._GIT, "remote"] output_bytes = self._subprocess_check_output(argv, is_write=False) return self._output_bytes_to_lines(output_bytes) def _find_branches(self, extra_argv=None, strip_left: int = 2) -> list[str]: # strip_left==1 strips leading "refs/" # strip_left==2 strips leading "refs/heads/" and "refs/remotes/" argv = [ self._GIT, "-c", "column.branch=plain", "branch", f"--format=%(refname:lstrip={strip_left})", ] if extra_argv is not None: argv += extra_argv output_bytes = self._subprocess_check_output(argv, is_write=False) lines = self._output_bytes_to_lines(output_bytes) return [ line for line in lines if not line.endswith("/HEAD") and "HEAD detached at" not in line ] def find_local_branches(self) -> list[str]: return self._find_branches() def find_all_branch_refs(self) -> list[str]: return self._find_branches(["--all"]) def find_all_branch_names(self) -> set[str]: branch_names = set() for line in self._find_branches(["--all"], strip_left=1): heads_or_remotes, *remainder = line.split("/") if heads_or_remotes == "heads": branch_name = "/".join(remainder) elif heads_or_remotes == "remotes": branch_name = "/".join(remainder[1:]) else: raise ValueError(f"Reference {line!r} not understood") branch_names.add(branch_name) return branch_names def find_remote_branches_at(self, remote_name) -> list[str]: assert remote_name extra_argv = ["--remote", "--list", f"{remote_name}/*"] return self._find_branches(extra_argv) def find_current_branch(self) -> Optional[str]: # Note: Avoiding "git branch --show-current" of Git >=2.22.0 # to keep Git 2.17.1 of Ubuntu 18.04 in the boat, for now. argv = [self._GIT, "rev-parse", "--symbolic-full-name", "HEAD"] output_bytes = self._subprocess_check_output(argv, is_write=False) lines = self._output_bytes_to_lines(output_bytes) assert len(lines) == 1 expected_prefix = "refs/heads/" reference = lines[0] # 'HEAD' when detached, else 'refs/heads/' if not reference.startswith(expected_prefix): return None # detached head return reference[len(expected_prefix) :] def find_working_tree_branches(self) -> list[Optional[str]]: argv = [self._GIT, "worktree", "list", "--porcelain"] # requires Git >=2.7.0 output_bytes = self._subprocess_check_output(argv, is_write=False) lines = self._output_bytes_to_lines(output_bytes) detached_line_prefix = "detached" branch_line_prefix = "branch " branch_prefix = "refs/heads/" branch_names: list[Optional[str]] = [] for line in lines: if line.startswith(detached_line_prefix): branch_names.append(None) elif line.startswith(branch_line_prefix): branch_name = line[len(branch_line_prefix) :] if branch_name.startswith(branch_prefix): branch_name = branch_name[len(branch_prefix) :] branch_names.append(branch_name) return branch_names def has_detached_heads(self) -> bool: return None in self.find_working_tree_branches() def _get_merged_branches_for(self, target_branch: str, remote: bool): extra_argv = [] if remote: extra_argv.append("--remote") extra_argv += [ "--merged", target_branch, ] merged_branches = self._find_branches(extra_argv) return (branch for branch in merged_branches if branch != target_branch) def find_merged_local_branches_for(self, branch_name): return self._get_merged_branches_for(branch_name, remote=False) def find_merged_remote_branches_for(self, remote_name, branch_name): return self._get_merged_branches_for(f"{remote_name}/{branch_name}", remote=True) def delete_local_branches(self, branch_names, force=False): if not branch_names: return argv = [self._GIT, "branch", "--delete"] if force: argv.append("--force") argv += sorted(branch_names) self._subprocess_check_call(argv, is_write=True) def delete_remote_branches(self, branch_names, remote_name): if not branch_names: return remote_prefix = f"{remote_name}/" remote_branches_to_delete = [ "refs/heads/" + remote_slash_branch[len(remote_prefix) :] for remote_slash_branch in branch_names if remote_slash_branch.startswith(remote_prefix) ] if not remote_branches_to_delete: return argv = [ self._GIT, "push", "--delete", "--force-with-lease", remote_name, ] + remote_branches_to_delete self._subprocess_check_output(argv, is_write=True) def set_config(self, key, value): argv = [self._GIT, "config"] if value is None: argv += ["--unset", key] else: argv += [key, value] self._subprocess_check_output(argv, is_write=True) def update_and_prune_remote(self, remote_name: str) -> None: argv = [self._GIT, "remote", "update", "--prune", remote_name] self._subprocess_check_output(argv, is_write=True) def checkout(self, committish: str) -> None: argv = [self._GIT, "checkout", "-q"] argv.append(committish) try: self._subprocess_check_output(argv, is_write=True) except subprocess.CalledProcessError as e: if e.returncode == 1: raise CheckoutFailed raise def pull_ff_only(self) -> None: argv = [self._GIT, "pull", "--ff-only"] try: self._subprocess_check_output(argv, is_write=True) except subprocess.CalledProcessError as e: if e.returncode == 1: raise PullFailed raise def _has_changes(self, extra_argv: Optional[list[str]] = None) -> bool: argv = [self._GIT, "diff", "--exit-code", "--quiet"] if extra_argv: argv += extra_argv try: self._subprocess_check_output(argv, is_write=False) return False except subprocess.CalledProcessError as e: if e.returncode == 1: return True raise def has_staged_changes(self) -> bool: return self._has_changes(["--cached"]) def has_uncommitted_changes(self) -> bool: if self._has_changes(): return True return self.has_staged_changes() def cherry(self, target_branch, topic_branch) -> list[str]: argv = [self._GIT, "cherry", target_branch, topic_branch] output_bytes = self._subprocess_check_output(argv, is_write=False) return self._output_bytes_to_lines(output_bytes) def has_unpushed_commits_on(self, branch, with_regard_to): cherry_lines = self.cherry(with_regard_to, branch) return any(line.startswith("+") for line in cherry_lines) def commit_tree(self, message: str, parent_committish: str, tree: str) -> str: argv = [self._GIT, "commit-tree", "-m", message, "-p", parent_committish, tree] env = os.environ.copy() env.update(self._COMMIT_ENVIRON) # Note: Command "git commit-tree" does write to the repository but it does # not switch branches, move HEAD or delete things; that's why it # it is considered "not writing" (``is_write=False``) here and # will be performed even when ``--dry-run``/``self._pretend`` is active. output_bytes = self._subprocess_check_output(argv, env=env, is_write=False) lines = self._output_bytes_to_lines(output_bytes) assert len(lines) == 1 return lines[0] def merge_base(self, target_branch, topic_branch) -> str: argv = [self._GIT, "merge-base", target_branch, topic_branch] try: output_bytes = self._subprocess_check_output(argv, is_write=False) except subprocess.CalledProcessError as e: if e.returncode == 1: raise MergeBaseFailed raise lines = self._output_bytes_to_lines(output_bytes) assert len(lines) == 1 return lines[0] git-delete-merged-branches-7.5.0/git_delete_merged_branches/_messenger.py000066400000000000000000000040341476270220300265740ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later import sys import colorama from ._shell import escape_for_shell_display _INFO_COLOR = colorama.Fore.WHITE + colorama.Style.BRIGHT _ERROR_COLOR = colorama.Fore.RED + colorama.Style.BRIGHT _COMMAND_COLOR = colorama.Fore.CYAN _QUESTION_COLOR = colorama.Fore.GREEN + colorama.Style.BRIGHT _RESET_COLOR = colorama.Style.RESET_ALL class Messenger: def __init__(self, colorize): self._colorize = colorize # Multi-line block of text should by separated from consecutive output (if any) # by a blank line to give it some "air". This flag is a tiny state machine. self._air_needed = False def produce_air(self): if self._air_needed: print() self._air_needed = False def request_air(self, future_message): if "\n" in future_message: self._air_needed = True def _produce_and_request_air(self, future_message): self.produce_air() self.request_air(future_message) def tell_info(self, message): self._produce_and_request_air(message) if self._colorize: message = f"{_INFO_COLOR}{message}{_RESET_COLOR}" print(message) def tell_command(self, argv, comment): self._produce_and_request_air("") epilog = f" # {comment}" if comment else "" argv = [escape_for_shell_display(arg) for arg in argv] message = f"# {' '.join(argv)}" if self._colorize: message = f"{_COMMAND_COLOR}{message}{_RESET_COLOR}" message += epilog print(message, file=sys.stderr) def tell_error(self, message): self._produce_and_request_air(message) message = f"Error: {message}" if self._colorize: message = f"{_ERROR_COLOR}{message}{_RESET_COLOR}" print(message, file=sys.stderr) def format_question(self, message): if self._colorize: message = f"{_QUESTION_COLOR}{message}{_RESET_COLOR}" return message git-delete-merged-branches-7.5.0/git_delete_merged_branches/_metadata.py000066400000000000000000000003331476270220300263620ustar00rootroot00000000000000# Copyright (C) 2020-2022 Sebastian Pipping # Licensed under GPL v3 or later APP = "git-delete-merged-branches" DESCRIPTION = "Command-line tool to delete merged Git branches" VERSION = "7.5.0" git-delete-merged-branches-7.5.0/git_delete_merged_branches/_multiselect.py000066400000000000000000000344761476270220300271530ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later from abc import ABC from dataclasses import dataclass from typing import Any, Optional from prompt_toolkit.application import Application from prompt_toolkit.buffer import Buffer from prompt_toolkit.document import Document from prompt_toolkit.filters import is_searching from prompt_toolkit.formatted_text.base import StyleAndTextTuples from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout import HSplit, Layout, Window from prompt_toolkit.layout.containers import Container, VerticalAlign from prompt_toolkit.layout.controls import BufferControl from prompt_toolkit.layout.dimension import Dimension from prompt_toolkit.layout.mouse_handlers import MouseHandlers from prompt_toolkit.layout.processors import Processor, Transformation, TransformationInput from prompt_toolkit.layout.screen import Screen, WritePosition from prompt_toolkit.layout.scrollable_pane import ScrollablePane, ScrollOffsets from prompt_toolkit.search import SearchState from prompt_toolkit.widgets import SearchToolbar from ._messenger import Messenger class _ItemRenderProcessor(Processor): """ A Prompt Toolkit input processor for Buffer that formats lines for display to the user. """ def __init__(self, prompt: "_MultiSelectPrompt"): self._prompt = prompt def apply_transformation(self, transformation_input: TransformationInput) -> Transformation: line_info = self._prompt.item_lines[transformation_input.lineno] new_fragments: StyleAndTextTuples = [] highlighted = transformation_input.lineno == self._prompt.get_cursor_line() cursor = "▶" if highlighted else " " checkmark = "x" if line_info.selected else " " fallback_style = ( self._prompt.highlighted_style if highlighted else self._prompt.neutral_style ) new_fragments.append((fallback_style, f"{cursor} [{checkmark}] ")) # Apply new style where adequate for fragment in transformation_input.fragments: old_style, text = fragment # NOTE: The idea is to respect search result markers (that have been inserted # by HighlightSearchProcessor or HighlightIncrementalSearchProcessor) # in item text, and only there. new_style = old_style or fallback_style new_fragments.append((new_style, text)) # Add right padding padding_width = 2 + (self._prompt.peak_item_label_length - len(line_info.text)) new_fragments.append((fallback_style, " " * padding_width)) return Transformation(fragments=new_fragments) class _NonItemRenderProcessor(Processor): """ A Prompt Toolkit input processor for Buffer that formats lines for display to the user. """ def __init__(self, prompt: "_MultiSelectPrompt", lines: list): self._prompt = prompt self._lines = lines def apply_transformation(self, transformation_input: TransformationInput) -> Transformation: line_info = self._lines[transformation_input.lineno] if isinstance(line_info, self._prompt.HeaderLine): new_style = self._prompt.header_style else: new_style = self._prompt.neutral_style new_fragments: StyleAndTextTuples = [ (new_style, text) for _old_style, text in transformation_input.fragments ] return Transformation(fragments=new_fragments) class _LineJumpingBuffer(Buffer): """ A Prompt Toolkit Buffer that will skip all but the first search match per line when iterating search matches using keys "n" and "N". """ def apply_search( self, search_state: SearchState, include_current_position: bool = True, count: int = 1, ) -> None: previous_cursor_position = self.cursor_position previous_line_index, _ = self.document.translate_index_to_position(self.cursor_position) while True: super().apply_search( search_state=search_state, include_current_position=include_current_position, count=count, ) if self.cursor_position == previous_cursor_position: # The call to search has not moved the cursor, search has ended return current_line_index, _ = self.document.translate_index_to_position(self.cursor_position) if current_line_index != previous_line_index: # We changed lines already, that's all we wanted return previous_cursor_position = self.cursor_position previous_line_index = current_line_index class _HeightTrackingScrollablePane(ScrollablePane): """ A copy of ``ScrollablePane`` that remembers the latest rendering height. """ def __init__(self, content: Container, **kwargs): super().__init__(content=content, **kwargs) self.current_height = None def write_to_screen( self, screen: Screen, mouse_handlers: MouseHandlers, write_position: WritePosition, parent_style: str, erase_bg: bool, z_index: Optional[int], ) -> None: self.current_height = write_position.height super().write_to_screen( screen=screen, mouse_handlers=mouse_handlers, write_position=write_position, parent_style=parent_style, erase_bg=erase_bg, z_index=z_index, ) class _MultiSelectPrompt: """ An interactive multi-select using the terminal, based on Prompt Toolkit. """ @dataclass class _LineBase(ABC): text: str @dataclass class PlainLine(_LineBase): pass @dataclass class HeaderLine(_LineBase): pass @dataclass class ItemLine(_LineBase): value: Any selected: bool def __init__( self, highlighted_style: str = "", header_style: str = "", initial_cursor_index=0, min_selection_count=0, ): self.neutral_style: str = "" self.highlighted_style: str = highlighted_style self.header_style: str = header_style self._initial_cursor_item_index: int = initial_cursor_index self._min_selection_count: int = min_selection_count self.peak_item_label_length: int = 0 self.item_lines: [_MultiSelectPrompt.ItemLine] = [] self._header_lines: [_MultiSelectPrompt.HeaderLine] = [] self._footer_lines: [_MultiSelectPrompt.PlainLine] = [] self._item_selection_pane: Optional[_HeightTrackingScrollablePane] = None self._buffer: Optional[Buffer] = None self._document: Optional[Document] = None self._accepted_selection: list[Any] = None def _move_cursor_one_page_vertically(self, upwards: bool): render_cursor_line = ( self._item_selection_pane.content.render_info.cursor_position.y - self._item_selection_pane.vertical_scroll ) page_height_in_lines = self._item_selection_pane.current_height if upwards and render_cursor_line > 0: new_line_index = self.get_cursor_line() - render_cursor_line elif not upwards and render_cursor_line < page_height_in_lines - 1: new_line_index = self.get_cursor_line() + ( page_height_in_lines - render_cursor_line - 1 ) else: current_line_index = self.get_cursor_line() if upwards: new_line_index = max(0, current_line_index - page_height_in_lines) else: new_line_index = min( len(self.item_lines) - 1, current_line_index + page_height_in_lines ) self._move_cursor_to_line(new_line_index) def _move_cursor_to_line(self, line_index: int): self._buffer.cursor_position = self._document.translate_row_col_to_index( row=line_index, col=0 ) def get_cursor_line(self): row, col = self._document.translate_index_to_position(self._buffer.cursor_position) return row def _move_cursor_one_step_vertically(self, upwards: bool): if len(self.item_lines) < 2: return current_line_index = self.get_cursor_line() # Can we even move any further in that direction? if (upwards and current_line_index == 0) or ( not upwards and current_line_index == len(self.item_lines) - 1 ): return self._move_cursor_to_line(current_line_index + (-1 if upwards else 1)) def _on_move_line_down(self, _event): self._move_cursor_one_step_vertically(upwards=False) def _on_move_line_up(self, _event): self._move_cursor_one_step_vertically(upwards=True) def _on_move_page_up(self, _event): self._move_cursor_one_page_vertically(upwards=True) def _on_move_page_down(self, _event): self._move_cursor_one_page_vertically(upwards=False) def _on_move_to_first(self, _event): self._move_cursor_to_line(0) def _on_move_to_last(self, _event): self._move_cursor_to_line(len(self.item_lines) - 1) def _on_toggle(self, _event): line_index = self.get_cursor_line() line_info = self.item_lines[line_index] line_info.selected = not line_info.selected def _on_accept(self, event): selected_values = self._collect_selected_values() if len(selected_values) < self._min_selection_count: return self._accepted_selection = selected_values event.app.exit() def _on_abort(self, event): event.app.exit() def add_header(self, text): self._header_lines.append(self.HeaderLine(text)) def add_item(self, value: Any, label: str = None, selected: bool = False): if label is None: label = str(value) self.peak_item_label_length = max(self.peak_item_label_length, len(label)) item_line = self.ItemLine(selected=selected, text=label, value=value) self.item_lines.append(item_line) def add_footer(self, text): self._footer_lines.append(self.PlainLine(text)) def _create_key_bindings(self): key_bindings = KeyBindings() key_bindings.add("c-c")(self._on_abort) key_bindings.add("q", filter=~is_searching)(self._on_abort) key_bindings.add("space", filter=~is_searching)(self._on_toggle) for key in ("enter", "right"): key_bindings.add(key, filter=~is_searching)(self._on_accept) for key in ("up", "k"): key_bindings.add(key, filter=~is_searching)(self._on_move_line_up) for key in ("down", "j"): key_bindings.add(key, filter=~is_searching)(self._on_move_line_down) key_bindings.add("pageup", filter=~is_searching)(self._on_move_page_up) key_bindings.add("pagedown", filter=~is_searching)(self._on_move_page_down) key_bindings.add("home", filter=~is_searching)(self._on_move_to_first) key_bindings.add("end", filter=~is_searching)(self._on_move_to_last) return key_bindings def _create_text_display_window_for(self, lines: list[_LineBase]) -> Window: document = Document(text="\n".join(line.text for line in lines)) buffer = Buffer(read_only=True, document=document) buffer_control = BufferControl( buffer=buffer, input_processors=[_NonItemRenderProcessor(prompt=self, lines=lines)] ) return Window(buffer_control, wrap_lines=True, height=Dimension(min=len(lines))) def _create_layout(self) -> tuple[Layout, _HeightTrackingScrollablePane]: header = self._create_text_display_window_for(self._header_lines) footer = self._create_text_display_window_for(self._footer_lines) search = SearchToolbar(ignore_case=True) buffer_control = BufferControl( buffer=self._buffer, input_processors=[_ItemRenderProcessor(prompt=self)], preview_search=True, search_buffer_control=search.control, ) item_selection_window = Window(buffer_control, always_hide_cursor=True, wrap_lines=True) pane_scroll_offsets = ScrollOffsets(top=0, bottom=0) pane_height = Dimension( min=1, max=self._document.line_count, preferred=self._document.line_count ) item_selection_pane = _HeightTrackingScrollablePane( item_selection_window, height=pane_height, scroll_offsets=pane_scroll_offsets ) item_selection_pane.show_scrollbar = ( lambda: (item_selection_pane.current_height or 0) < self._document.line_count ) item_selection_pane_plus_search = HSplit([item_selection_pane, search]) hsplit = HSplit( [header, item_selection_pane_plus_search, footer], padding=1, align=VerticalAlign.TOP ) return Layout(hsplit, focused_element=item_selection_pane), item_selection_pane def _collect_selected_values(self): return [item.value for item in self.item_lines if item.selected] def get_selected_values(self) -> list[Any]: self._document = Document(text="\n".join(line.text for line in self.item_lines)) self._buffer = _LineJumpingBuffer(read_only=True, document=self._document) layout, self._item_selection_pane = self._create_layout() app = Application(key_bindings=self._create_key_bindings(), layout=layout) self._move_cursor_to_line(self._initial_cursor_item_index) app.run() return self._accepted_selection def multiselect( messenger: Messenger, options: list[str], initial_selection: list[int], title: str, help: str, min_selection_count: int, colorize: bool, ) -> list[str]: assert len(options) >= min_selection_count menu = _MultiSelectPrompt( highlighted_style="bold fg:black bg:white" if colorize else "", header_style="bold fg:ansibrightgreen" if colorize else "", initial_cursor_index=initial_selection[0] if initial_selection else 0, min_selection_count=min_selection_count, ) menu.add_header(title) for i, option in enumerate(options): menu.add_item(option, selected=i in initial_selection) menu.add_footer(help) messenger.produce_air() selected_options = menu.get_selected_values() if selected_options is None: raise KeyboardInterrupt messenger.request_air("\n") return selected_options git-delete-merged-branches-7.5.0/git_delete_merged_branches/_shell.py000066400000000000000000000031111476270220300257060ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later _NEED_ESCAPING_INSIDE_DOUBLE_QUOTES = set('!`"$\\') _NEED_ESCAPING_WITHOUT_QUOTES = _NEED_ESCAPING_INSIDE_DOUBLE_QUOTES | set("' {}()?*&<>;#") def _escape_for_double_quotes(text: str) -> str: escape = {c: f"\\{c}" for c in _NEED_ESCAPING_INSIDE_DOUBLE_QUOTES} escaped = "".join(escape.get(c, c) for c in text) return escaped def escape_for_shell_display(text: str) -> str: """ Format text for display as part of a shell command close to what a human would write and expect to read. In detail, the requirements are: 1. Do not escape spaces but rather surround by quotes, single or double. 2. Do not surround by any quotes if the string does not contain spaces and is not the empty string. 3. Prefer single quotes over double quotes, i.e. use double quotes only when single quotes are already present. """ if not text: return "''" if " " in text: # Is surrounding by single quotes an option? if "'" in text: # Surrounding by single quotes is not an option; # so escape for use inside double quotes return f'"{_escape_for_double_quotes(text)}"' else: return f"'{text}'" needs_escaping = any((c in _NEED_ESCAPING_WITHOUT_QUOTES) for c in text) if not needs_escaping: return text # Is surrounding by single quotes an option? if "'" in text: return f'"{_escape_for_double_quotes(text)}"' else: return f"'{text}'" git-delete-merged-branches-7.5.0/git_delete_merged_branches/tests/000077500000000000000000000000001476270220300252345ustar00rootroot00000000000000git-delete-merged-branches-7.5.0/git_delete_merged_branches/tests/__init__.py000066400000000000000000000000001476270220300273330ustar00rootroot00000000000000git-delete-merged-branches-7.5.0/git_delete_merged_branches/tests/helpers.py000066400000000000000000000026171476270220300272560ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later import subprocess from tempfile import NamedTemporaryFile from textwrap import dedent from unittest.mock import Mock from .._confirm import Confirmation from .._engine import DeleteMergedBranches from .._git import Git from .._messenger import Messenger def run_script(content, cwd): header = dedent("""\ set -e set -x export HOME= # make global git config have no effect export GIT_AUTHOR_EMAIL=author1@localhost export GIT_AUTHOR_NAME='Author One' export GIT_COMMITTER_EMAIL=committer2@localhost export GIT_COMMITTER_NAME='Committer Two' """) with NamedTemporaryFile() as f: for text in (header, content): f.write(text.encode("utf-8")) f.flush() subprocess.check_call(["bash", f.name], cwd=cwd) def create_git(work_dir: str) -> Git: messenger = Messenger(colorize=False) return Git(messenger=messenger, pretend=False, verbose=True, work_dir=work_dir) def create_dmb(git: Git, effort_level: int) -> DeleteMergedBranches: messenger = Messenger(colorize=False) confirmation = Confirmation(messenger=messenger, ask=False) return DeleteMergedBranches( git, messenger=messenger, confirmation=confirmation, selector=Mock(), effort_level=effort_level, ) git-delete-merged-branches-7.5.0/git_delete_merged_branches/tests/test_cli.py000066400000000000000000000010001476270220300274030ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later import sys from io import StringIO from unittest import TestCase from unittest.mock import patch from .._cli import _parse_command_line class HelpOutputTest(TestCase): def test_help(self): with patch.object(sys, "stdout", StringIO()) as mock_stdout, self.assertRaises(SystemExit): _parse_command_line(colorize=True, args=["--help"]) self.assertIn("usage", mock_stdout.getvalue()) git-delete-merged-branches-7.5.0/git_delete_merged_branches/tests/test_engine.py000066400000000000000000000266221476270220300301220ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later import os from tempfile import TemporaryDirectory from textwrap import dedent from unittest import TestCase from unittest.mock import Mock from parameterized import parameterized from .._engine import DeleteMergedBranches from .helpers import create_dmb, create_git, run_script class MergeDetectionTest(TestCase): def test_effort_1_truly_merged(self): setup_script = dedent(""" git init # Create a commit to base future branches upon echo line1 > file.txt git add file.txt git commit -m 'Add file.txt with one line' # Create a merged branch: With HEAD sitting in master's past git branch merged1 # Create a merged branch: Topic branch with original commit git checkout -b merged2 echo line2 >> file.txt git commit -a -m 'Add line 2' git checkout master git merge --no-ff --no-edit merged2 # Create a not-merged branch git checkout -b not-merged1 echo line3 >> file.txt git commit -a -m 'Add line 3' """) with TemporaryDirectory() as d: run_script(setup_script, cwd=d) git = create_git(d) dmb = create_dmb(git, effort_level=1) self.assertEqual( git.find_local_branches(), ["master", "merged1", "merged2", "not-merged1"] ) truly_merged, defacto_merged = ( dmb._find_branches_merged_to_all_targets_for_single_remote( {"master"}, set(), remote_name=None ) ) self.assertEqual(truly_merged, {"merged1", "merged2"}) self.assertEqual(defacto_merged, set()) def test_effort_2_unsquashed_cherries(self): setup_script = dedent(""" git init # Create a commit to base future branches upon echo line1 > file1.txt git add file1.txt git commit -m 'Add file1.txt' # Create a de-facto merged branch: forward order git checkout -b defacto-merged1 cp file1.txt file2.txt git add file2.txt git commit -m 'Add file2.txt' cp file1.txt file3.txt git add file3.txt git commit -m 'Add file3.txt' # Create a de-facto merged branch: backward order git checkout -b defacto-merged2 master cp file1.txt file3.txt git add file3.txt git commit -m 'Add file3.txt' cp file1.txt file2.txt git add file2.txt git commit -m 'Add file2.txt' # Add an extra commit on master so that we don't get # identical SHA1s when cherry-picking, after git checkout master cp file1.txt file4.txt git add file4.txt git commit -m 'Add file4.txt' # Get the commits on master that will make # branches defacto-merged{1,2} be detected as de-facto merged git cherry-pick defacto-merged1{^,} # Create a not-defacto-merged branch git checkout -b not-defacto-merged1 defacto-merged1 cp file1.txt file5.txt git add file5.txt git commit -m 'Add file5.txt' """) with TemporaryDirectory() as d: run_script(setup_script, cwd=d) git = create_git(d) dmb = create_dmb(git, effort_level=2) self.assertEqual( git.find_local_branches(), ["defacto-merged1", "defacto-merged2", "master", "not-defacto-merged1"], ) truly_merged, defacto_merged = ( dmb._find_branches_merged_to_all_targets_for_single_remote( {"master"}, set(), remote_name=None ) ) self.assertEqual(truly_merged, set()) self.assertEqual(defacto_merged, {"defacto-merged1", "defacto-merged2"}) def test_effort_3_squashed_cherries(self): setup_script = dedent(""" git init # Create a commit to base future branches upon echo line1 > file1.txt git add file1.txt git commit -m 'Add file1.txt' # Create a de-facto squash-merged branch: Adding up to full diff git checkout -b defacto-squash-merged1 cp file1.txt file2.txt git add file2.txt git commit -m 'Add file2.txt' cp file1.txt file3.txt git add file3.txt git commit -m 'Add file3.txt' # Create de-facto squash-merged branch: With reverts, adding up git checkout -b defacto-squash-merged2 git revert --no-edit HEAD git revert --no-edit HEAD # i.e. revert the revert # Get the a squashed commit on master that will make # branches defacto-squash-merged{1,2} be detected as de-facto merged git checkout master git merge --squash defacto-squash-merged1 git commit -m "Add squashed copy of 'defacto-squash-merged1'" # Create not-defacto-squash-merged branch: Squashed copy commit # .. will not have a counterpart git checkout -b not-defacto-squash-merged1 git revert --no-edit HEAD """) with TemporaryDirectory() as d: run_script(setup_script, cwd=d) git = create_git(d) dmb = create_dmb(git, effort_level=3) self.assertEqual( git.find_local_branches(), [ "defacto-squash-merged1", "defacto-squash-merged2", "master", "not-defacto-squash-merged1", ], ) truly_merged, defacto_merged = ( dmb._find_branches_merged_to_all_targets_for_single_remote( {"master"}, set(), remote_name=None ) ) self.assertEqual(truly_merged, set()) self.assertEqual(defacto_merged, {"defacto-squash-merged1", "defacto-squash-merged2"}) class RefreshTargetBranchesTest(TestCase): def test_refresh_gets_branches_back_in_sync(self): setup_script = dedent(""" mkdir upstream cd upstream git init git commit --allow-empty -m 'Dummy commit #1' git branch pull-works git branch pull-trouble git checkout -b checkout-trouble echo line1 > collision.txt git add collision.txt git commit -m 'Add collision.txt' git checkout master cd .. git clone -o upstream upstream downstream cd downstream git branch --track checkout-trouble upstream/checkout-trouble git branch --track pull-trouble upstream/pull-trouble git branch --track pull-works upstream/pull-works cd .. cd upstream git checkout pull-trouble git merge --ff checkout-trouble git checkout pull-works git commit --allow-empty -m 'Dummy commit #2' cd .. cd downstream git checkout -b topic1 echo line1 > collision.txt # uncommitted, just present """) with TemporaryDirectory() as d: run_script(setup_script, cwd=d) downstream_git = create_git(os.path.join(d, "downstream")) downstream_dmb = create_dmb(downstream_git, effort_level=3) self.assertEqual(downstream_git.find_current_branch(), "topic1") self.assertEqual( downstream_git.find_local_branches(), ["checkout-trouble", "master", "pull-trouble", "pull-works", "topic1"], ) downstream_dmb.refresh_remotes(["upstream"]) self.assertEqual(len(downstream_git.cherry("pull-works", "upstream/pull-works")), 1) downstream_dmb.refresh_target_branches( ["checkout-trouble", "pull-trouble", "pull-works"] ) self.assertEqual(len(downstream_git.cherry("pull-works", "upstream/pull-works")), 0) self.assertEqual(downstream_git.find_current_branch(), "topic1") class GitConfigKeysContainDotsTest(TestCase): @parameterized.expand( [ ( DeleteMergedBranches.find_required_branches, "branch.release-1.0.x.dmb-required", "release-1.0.x", ), ( DeleteMergedBranches.find_excluded_branches, "branch.release-1.0.x.dmb-excluded", "release-1.0.x", ), ( DeleteMergedBranches.find_enabled_remotes, "remote.linux-6.x.dmb-enabled", "linux-6.x", ), ] ) def test_supports_branch_names_containing_dots( self, extractor_function, git_config_dict_key, expected_value ): assert "." in expected_value git_config_dict = { git_config_dict_key: "true", } self.assertEqual(extractor_function(git_config_dict), [expected_value]) class DetermineExcludedBranchesTest(TestCase): @parameterized.expand( [ ("git config exclude", ["b1", "b2", "b3"], ["b1", "b3"], [], [], {"b1", "b3"}), ("--exclude", ["b1", "b2", "b3"], [], ["b1", "b3"], [], {"b1", "b3"}), ("--exclude + config exclude", ["b1", "b2", "b3"], ["b1"], ["b3"], [], {"b1", "b3"}), ( "--include-regex match full", ["b1", "b2", "b3"], [], [], ["^..$", "^b2$"], {"b1", "b3"}, ), ("--include-regex match partial", ["b1", "b2", "b3"], [], [], [r"\d", "b"], set()), ( "--include-regex mismatch", ["b1", "b2", "b3"], [], [], ["^b1$", "^b2$"], {"b1", "b2", "b3"}, ), ( "--include-regex + --exclude + config exclude", ["b1", "b2", "b3"], ["b1"], ["b3"], [r"^b\d$"], {"b1", "b3"}, ), ] ) def test( self, _label, existing_branches, excluded_branches_from_config, excluded_branches_extra, included_branches_patterns, expected_exclusion_set, ): git_mock = Mock(find_all_branch_names=Mock(return_value=existing_branches)) dmb = DeleteMergedBranches( git=git_mock, messenger=Mock(), confirmation=Mock(), selector=Mock(), effort_level=999 ) git_config_key_format = DeleteMergedBranches._FORMAT_BRANCH_EXCLUDED git_config = { git_config_key_format.format(name=branch_name): DeleteMergedBranches._CONFIG_VALUE_TRUE for branch_name in excluded_branches_from_config } actual_exclusion_set = dmb.determine_excluded_branches( git_config, excluded_branches_extra, included_branches_patterns ) self.assertEqual(actual_exclusion_set, expected_exclusion_set) git-delete-merged-branches-7.5.0/git_delete_merged_branches/tests/test_git.py000066400000000000000000000151411476270220300274320ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later import os import shlex import subprocess from tempfile import TemporaryDirectory from textwrap import dedent from unittest import TestCase from unittest.mock import Mock, call, patch from parameterized import parameterized from .._git import Git from .._messenger import Messenger from .helpers import create_git, run_script class FindBranchesTest(TestCase): def test_find_branches_drops_head(self): existing_branches = ["remote1/HEAD", "remote2/master"] expected_branches = ["remote2/master"] git = Git(Messenger(colorize=False), pretend=True, verbose=False) command_output_to_inject = ("\n".join(existing_branches) + "\n").encode("utf-8") assert isinstance(command_output_to_inject, bytes) with patch.object(subprocess, "check_output", return_value=command_output_to_inject): actual_branches = git._find_branches() self.assertEqual(actual_branches, expected_branches) @parameterized.expand( [ # NOTE: No point in testing values "never" or "auto" ("column.ui", "always"), # NOTE: No point in testing value "plain" ("column.branch", "column"), ("column.branch", "row"), ] ) def test_find_branches_robust_towards_column_mode(self, git_config_key, git_config_value): expected_branches = ["main_1", "main_2"] with TemporaryDirectory() as tempdir: run_script( dedent( f""" git -c init.defaultBranch=main_1 init git commit --allow-empty -m 'First commit' git config {shlex.quote(git_config_key)} {shlex.quote(git_config_value)} git branch main_2 main_1 """ ), tempdir, ) git = Git(Messenger(colorize=False), pretend=True, verbose=False, work_dir=tempdir) actual_branches = git._find_branches() self.assertEqual(actual_branches, expected_branches) class FindBranchNamesTest(TestCase): def test(self): find_branches_lines = [ "heads/b1", "heads/b2", "remotes/remote1/b3", "remotes/remote2/b1", ] expected = {"b1", "b2", "b3"} git = Git(messenger=Mock(), pretend=True, verbose=False) with patch.object( git, "_find_branches", return_value=find_branches_lines ) as find_branches_mock: actual = git.find_all_branch_names() self.assertEqual(actual, expected) self.assertEqual(find_branches_mock.call_args_list, [call(["--all"], strip_left=1)]) class FindWorkingTreeBranchesTest(TestCase): def test_find_branches_drops_head(self): expected_branches = [None, "branch-arrow-shift", "refactor-layout-window"] git = Git(Messenger(colorize=False), pretend=True, verbose=False) command_output_to_inject = dedent(""" worktree /tmp/tmp.mgTEbE434g/pymux HEAD 493723318912cb44b1a3e47ba3fbc0e50b2a8f5c detached worktree /tmp/tmp.mgTEbE434g/branch-arrow-shift HEAD 3f66e62b9de4b2251c7f9afad6c516dc5a30ec67 branch refs/heads/branch-arrow-shift worktree /tmp/tmp.mgTEbE434g/refactor-layout-window HEAD 3f66e62b9de4b2251c7f9afad6c516dc5a30ec67 branch refs/heads/refactor-layout-window """).encode("utf-8") # with two trialing newlines like Git would do assert isinstance(command_output_to_inject, bytes) with patch.object(subprocess, "check_output", return_value=command_output_to_inject): actual_branches = git.find_working_tree_branches() self.assertEqual(actual_branches, expected_branches) class OutputBytesToLinesTest(TestCase): @parameterized.expand( [ (b"one\ntwo", ["one", "two"]), (b"one\ntwo\n", ["one", "two"]), (b"one\ntwo\n\n", ["one", "two"]), (b"", []), (b"\n", []), (b"\n\n", []), ] ) def test_trailing_newlines(self, output_bytes, extected_interpretation): self.assertEqual(Git._output_bytes_to_lines(output_bytes), extected_interpretation) class ExtractGitConfigTest(TestCase): def test_escapes(self): expected_config = { "z.singlequote": "'", "z.doublequote": '"', "z.doublequote-doublequote": '""', "z.doublequote-doublequote-doublequote": '"""', "z.backlslash": "\\", "z.backlslash-n": "\\n", "z.backlslash-t": "\\t", "z.backlslash-b": "\\b", "z.backlslash-doublequote": '\\"', "z.backlslash-backlslash": "\\\\", "z.linefeed": "\n", "z.tab": "\t", "z.backspace": chr(8), "z.empty": "", } mock_messenger = Mock() with TemporaryDirectory() as d: subprocess.call(["git", "init"], cwd=d) git = Git(messenger=mock_messenger, pretend=False, verbose=True, work_dir=d) for k, v in expected_config.items(): git.set_config(k, v) with open(os.path.join(d, ".git/config"), "a") as f: f.write("\tname-without-assignment") # GitHub issue #96 actual_config = { k: v for k, v in git.extract_git_config().items() if k in expected_config } self.assertEqual(actual_config, expected_config) self.assertEqual( mock_messenger.tell_info.call_args_list, [ call("Git config option 'z.name-without-assignment' lacks assignment of a value."), ], ) class RemoteBranchCollidesWithATagTest(TestCase): def test_remote_branch_deletable_despite_existing_tag_with_the_same_name(self): setup_script = dedent("""\ mkdir upstream pushd upstream git init git commit --allow-empty -m 'First commit' git tag -m '' 1.0.0 git branch 1.0.0 popd git clone upstream downstream """) with TemporaryDirectory() as d: run_script(setup_script, cwd=d) downstream_git = create_git(work_dir=os.path.join(d, "downstream")) self.assertIn("origin/1.0.0", downstream_git.find_remote_branches_at("origin")) downstream_git.delete_remote_branches(["origin/1.0.0"], "origin") self.assertNotIn("origin/1.0.0", downstream_git.find_remote_branches_at("origin")) git-delete-merged-branches-7.5.0/git_delete_merged_branches/tests/test_shell.py000066400000000000000000000010761476270220300277600ustar00rootroot00000000000000# Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later from unittest import TestCase from parameterized import parameterized from .._shell import escape_for_shell_display class ShellEscapingTest(TestCase): @parameterized.expand( [ ("", "''"), ("one", "one"), ("one two", "'one two'"), ("tick'tick'$", "\"tick'tick'\\$\""), ] ) def test(self, text, expected_escaped_text): self.assertEqual(escape_for_shell_display(text), expected_escaped_text) git-delete-merged-branches-7.5.0/ruff.toml000066400000000000000000000003061476270220300204330ustar00rootroot00000000000000indent-width = 4 line-length = 100 target-version = "py39" [lint] select = [ "E", # pycodestyle "F", # Pyflakes + flake8 "I", # isort "UP", # pyupgrade "W", # pycodestyle ] git-delete-merged-branches-7.5.0/setup.py000077500000000000000000000040101476270220300203050ustar00rootroot00000000000000#! /usr/bin/env python3 # Copyright (C) 2020 Sebastian Pipping # Licensed under GPL v3 or later from setuptools import find_packages, setup from git_delete_merged_branches._metadata import APP, DESCRIPTION, VERSION _tests_require = [ "parameterized", ] _extras_require = { "tests": _tests_require, } setup( name=APP, version=VERSION, license="GPLv3+", description=DESCRIPTION, long_description=open("README.md", encoding="utf-8").read(), long_description_content_type="text/markdown", author="Sebastian Pipping", author_email="sebastian@pipping.org", url=f"https://github.com/hartwork/{APP}", python_requires=">=3.9", setup_requires=[ "setuptools>=38.6.0", # for long_description_content_type ], install_requires=[ "colorama>=0.4.3", "prompt-toolkit>=3.0.18", ], extras_require=_extras_require, tests_require=_tests_require, packages=find_packages(), entry_points={ "console_scripts": [ f"{APP} = git_delete_merged_branches.__main__:main", "git-dmb = git_delete_merged_branches.__main__:main", ], }, classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Topic :: Software Development :: Version Control", "Topic :: Software Development :: Version Control :: Git", ], data_files=[ ( "share/man/man1", [ f"{APP}.1", "git-dmb.1", ], ) ], ) git-delete-merged-branches-7.5.0/sync-manpages-with-help-output.sh000077500000000000000000000027271476270220300251460ustar00rootroot00000000000000#! /usr/bin/env bash # Copyright (C) 2022 Sebastian Pipping # Licensed under GPL v3 or later set -e set -o pipefail _BUILD_MONTH=2025-03 # for reproducible builds; bump when doing releases sed_args=( # Produce familiar section "synopsis" -e 's,^\.SH DESCRIPTION,.SH SYNOPSIS,' -e 's,^usage: ,,' -e 's,.*\[\\-\\-yes\]$,\0\n.SH DESCRIPTION,' # Repair usage line bugs -e 's,\]\\fR,\\fR\\],' # un-colorize closing square bracket -e 's,\[\(\\-\\-[a-z\\-]\+\),[\\fB\1\\fR,g' # colorize --argument in brackets # Be robust towards version difference between local help2man and CI help2man -e 's,It was generated by help2man .*,It was generated by help2man.,' # Put epilog in its own section -e 's,^Software libre.*,.SH EPILOG\n\0,' # Format "git-delete-merged-branches" in bold everywhere after section "NAME" -e 's,\(^\| \)\(git\\-\(delete\\-merged\\-branches\|dmb\)\) ,\n.B \2\n,g' # Un-colorize --merged in "git branch --merged" -e 's,git branch \\fB\\-\\-merged\\fR,git branch \\-\\-merged,' ) for i in git-delete-merged-branches git-dmb ; do SOURCE_DATE_EPOCH="$(date --date="${_BUILD_MONTH}-15" +%s)" \ NO_COLOR=please \ COLUMNS=400 \ help2man \ --locale='en_US.UTF-8' \ --no-info \ --name 'Command-line tool to delete merged Git branches' \ ${i} \ | sed "${sed_args[@]}" \ > ${i}.1 done