Repository: rtyley/bfg-repo-cleaner Branch: main Commit: 1bd9715198dd Files: 100 Total size: 203.9 KB Directory structure: gitextract_c1a_g3a9/ ├── .github/ │ ├── PULL_REQUEST_TEMPLATE.md │ └── workflows/ │ ├── ci.yml │ └── release.yml ├── .gitignore ├── .tool-versions ├── BUILD.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── backers.md ├── bfg/ │ ├── build.sbt │ └── src/ │ ├── main/ │ │ └── scala/ │ │ └── com/ │ │ └── madgag/ │ │ └── git/ │ │ └── bfg/ │ │ └── cli/ │ │ ├── CLIConfig.scala │ │ └── Main.scala │ └── test/ │ └── scala/ │ └── com/ │ └── madgag/ │ └── git/ │ └── bfg/ │ └── cli/ │ ├── CLIConfigSpecs.scala │ ├── MainSpec.scala │ ├── MassiveNonFileObjectsRequiresOwnJvmSpec.scala │ └── test/ │ └── unpackedRepo.scala ├── bfg-benchmark/ │ ├── build.sbt │ ├── resources/ │ │ ├── jars/ │ │ │ └── grabJars.sh │ │ └── repos/ │ │ ├── chromium-src/ │ │ │ └── commands/ │ │ │ └── issue-23/ │ │ │ └── bfg.txt │ │ ├── gcc/ │ │ │ └── commands/ │ │ │ └── delete-file/ │ │ │ ├── bfg.txt │ │ │ └── gfb.txt │ │ ├── git/ │ │ │ └── commands/ │ │ │ └── delete-file/ │ │ │ ├── bfg.txt │ │ │ └── gfb.txt │ │ ├── github-gem/ │ │ │ └── commands/ │ │ │ └── delete-file/ │ │ │ ├── bfg.txt │ │ │ └── gfb.txt │ │ ├── intellij/ │ │ │ └── commands/ │ │ │ ├── delete-binary-resources/ │ │ │ │ └── bfg.txt │ │ │ ├── delete-file/ │ │ │ │ ├── bfg.txt │ │ │ │ └── gfb.txt │ │ │ └── git-lfs-binary-resources/ │ │ │ └── bfg.txt │ │ ├── jgit/ │ │ │ └── commands/ │ │ │ ├── delete-file/ │ │ │ │ ├── bfg.txt │ │ │ │ └── gfb.txt │ │ │ ├── replace-1-existing-string/ │ │ │ │ ├── bfg.txt │ │ │ │ └── passwords.1-existing-string.txt │ │ │ ├── replace-20-existing-strings/ │ │ │ │ ├── bfg.txt │ │ │ │ └── passwords.20-existing-strings.txt │ │ │ └── replace-500-existing-strings/ │ │ │ ├── bfg.txt │ │ │ └── passwords.500-existing-strings.txt │ │ ├── linux/ │ │ │ └── commands/ │ │ │ └── delete-file/ │ │ │ ├── bfg.txt │ │ │ └── gfb.txt │ │ ├── rails/ │ │ │ └── commands/ │ │ │ └── delete-file/ │ │ │ ├── bfg.txt │ │ │ └── gfb.txt │ │ └── wine/ │ │ └── commands/ │ │ └── delete-file/ │ │ ├── bfg.txt │ │ └── gfb.txt │ └── src/ │ ├── main/ │ │ └── scala/ │ │ ├── Benchmark.scala │ │ ├── BenchmarkConfig.scala │ │ ├── JavaVersion.scala │ │ ├── lib/ │ │ │ ├── Repo.scala │ │ │ └── Timing.scala │ │ └── model/ │ │ ├── BFGJar.scala │ │ ├── InvocableEngine.scala │ │ ├── InvocableEngineSet.scala │ │ └── Java.scala │ └── test/ │ └── scala/ │ └── JavaVersionSpec.scala ├── bfg-library/ │ ├── build.sbt │ └── src/ │ ├── main/ │ │ └── scala/ │ │ └── com/ │ │ └── madgag/ │ │ ├── collection/ │ │ │ └── concurrent/ │ │ │ ├── ConcurrentMultiMap.scala │ │ │ └── ConcurrentSet.scala │ │ ├── git/ │ │ │ ├── LFS.scala │ │ │ └── bfg/ │ │ │ ├── GitUtil.scala │ │ │ ├── cleaner/ │ │ │ │ ├── BlobCharsetDetector.scala │ │ │ │ ├── BlobTextModifier.scala │ │ │ │ ├── LfsBlobConverter.scala │ │ │ │ ├── ObjectIdCleaner.scala │ │ │ │ ├── ObjectIdSubstitutor.scala │ │ │ │ ├── RepoRewriter.scala │ │ │ │ ├── Reporter.scala │ │ │ │ ├── TreeBlobModifier.scala │ │ │ │ ├── commits.scala │ │ │ │ ├── kit/ │ │ │ │ │ └── BlobInserter.scala │ │ │ │ ├── package.scala │ │ │ │ ├── protection/ │ │ │ │ │ ├── ProtectedObjectCensus.scala │ │ │ │ │ └── ProtectedObjectDirtReport.scala │ │ │ │ └── treeblobs.scala │ │ │ ├── memo.scala │ │ │ ├── model/ │ │ │ │ ├── Commit.scala │ │ │ │ ├── Footer.scala │ │ │ │ └── package.scala │ │ │ └── timing.scala │ │ ├── inclusion/ │ │ │ └── inclusion.scala │ │ └── text/ │ │ ├── ByteSize.scala │ │ ├── Tables.scala │ │ └── text.scala │ └── test/ │ └── scala/ │ └── com/ │ └── madgag/ │ ├── git/ │ │ ├── LFSSpec.scala │ │ └── bfg/ │ │ ├── GitUtilSpec.scala │ │ ├── MessageFooterSpec.scala │ │ ├── TreeEntrySpec.scala │ │ ├── cleaner/ │ │ │ ├── LfsBlobConverterSpec.scala │ │ │ ├── ObjectIdCleanerSpec.scala │ │ │ ├── ObjectIdSubstitutorSpec.scala │ │ │ ├── RepoRewriteSpec.scala │ │ │ └── TreeBlobModifierSpec.scala │ │ └── model/ │ │ └── CommitSpec.scala │ └── text/ │ └── ByteSizeSpecs.scala ├── bfg-test/ │ ├── build.sbt │ └── src/ │ └── main/ │ └── scala/ │ └── com/ │ └── madgag/ │ └── git/ │ └── bfg/ │ └── test/ │ └── unpackedRepo.scala ├── build.sbt ├── project/ │ ├── build.properties │ ├── dependencies.scala │ └── plugins.sbt └── version.sbt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ I assert that this patch is my own work, and to [simplify the licensing of the BFG Repo-Cleaner](https://github.com/rtyley/bfg-repo-cleaner/blob/master/CONTRIBUTING.md#pull-requests): _(choose 1 of these 2 options)_ - [ ] I assign the copyright on this contribution to Roberto Tyley - [ ] I disclaim copyright and thus place this contribution in the public domain ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: workflow_dispatch: pull_request: # triggering CI default branch improves caching # see https://docs.github.com/en/free-pro-team@latest/actions/guides/caching-dependencies-to-speed-up-workflows#restrictions-for-accessing-a-cache push: branches: - main jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: guardian/setup-scala@v1 - name: Build and Test run: sbt -v test - name: Test Summary uses: test-summary/action@v2 with: paths: "test-results/**/TEST-*.xml" if: always() ================================================ FILE: .github/workflows/release.yml ================================================ name: Release on: workflow_dispatch: jobs: release: uses: guardian/gha-scala-library-release-workflow/.github/workflows/reusable-release.yml@v1 permissions: { contents: write, pull-requests: write } with: GITHUB_APP_ID: 930725 SONATYPE_PROFILE_NAME: 'com.madgag' SONATYPE_CREDENTIAL_HOST: 's01.oss.sonatype.org' secrets: SONATYPE_TOKEN: ${{ secrets.AUTOMATED_MAVEN_RELEASE_SONATYPE_TOKEN }} PGP_PRIVATE_KEY: ${{ secrets.AUTOMATED_MAVEN_RELEASE_PGP_SECRET }} GITHUB_APP_PRIVATE_KEY: ${{ secrets.AUTOMATED_MAVEN_RELEASE_GITHUB_APP_PRIVATE_KEY }} ================================================ FILE: .gitignore ================================================ target *~ .idea .idea_modules *.iml *.jar repo.git.zip **/.project **/.classpath **/.settings .bsp .DS_Store test-results/ ================================================ FILE: .tool-versions ================================================ java corretto-11.0.25.9.1 ================================================ FILE: BUILD.md ================================================ The BFG is written in Scala, a modern functional language that runs on the JVM - so it can run anywhere Java can. Here's a rough set of instructions for building the BFG, if you don't want to use the pre-built [downloads](http://rtyley.github.io/bfg-repo-cleaner/#download): * Install Java JDK 11 or above * Install [sbt](https://www.scala-sbt.org/1.x/docs/Setup.html) * `git clone git@github.com:rtyley/bfg-repo-cleaner.git` * `cd bfg-repo-cleaner` * `sbt`<- start the sbt console * `bfg/assembly` <- download dependencies, run the tests, build the jar To find the jar once it's built, just look at the last few lines of output from the `assembly` task - it'll say something like this: ``` [info] Packaging /Users/roberto/development/bfg-repo-cleaner/bfg/target/bfg-1.11.9-SNAPSHOT-master-21d2115.jar ... [info] Done packaging. [success] Total time: 19 s, completed 26-Sep-2014 16:05:11 ``` If you're going to make changes to the Scala code, you may want to use IntelliJ and it's Scala plugin to help with the Scala syntax...! If you use [Eclipse IDE](http://www.eclipse.org/), you can set-up your development environment by following these instructions: * Install `sbt` and build as-above * Install [Scala IDE for Eclipse](http://scala-ide.org/) into your Eclipse installation if not already installed * Add the `sbteclipse-plugin` to your set of local sbt plugins: ``` mkdir -p ~/.sbt/1.0/plugins && tee ~/.sbt/1.0/plugins/plugins.sbt < Import -> Existing Projects into Workspace`, browse to your `bfg` working-copy, and ensure that you select `Search for nested projects` * You should now have the 4 `sbt` projects imported into your Eclipse workspace. I personally found Coursera's [online Scala course](https://www.coursera.org/course/progfun) very helpful in learning Scala, YMMV. ================================================ FILE: CONTRIBUTING.md ================================================ Issues and Questions -------------------- If you've found what looks like a bug, or have a feature request for the BFG, please check [issues on GitHub](https://github.com/rtyley/bfg-repo-cleaner/issues), and create a new issue if necessary. If you just have a general question, or there's something you don't understand, ask on [stackoverflow.com](http://stackoverflow.com/questions/ask) (tag it with [`git-rewrite-history`](http://stackoverflow.com/questions/tagged/git-rewrite-history) and [`bfg-repo-cleaner`](http://stackoverflow.com/questions/tagged/bfg-repo-cleaner) so I see it) - there are many more people who can answer that sort of question on Stackoverflow, you stand a good chance of getting your question answered quicker! Pull Requests ------------- BFG Repo-Cleaner is licensed under the [GPL v3](http://www.gnu.org/licenses/gpl.html), and to be in the best position to enforce the GPL the copyright status of BFG Repo Cleaner needs to be as simple as possible. To achieve this, contributors should only provide contributions which are **their own work**, and either: a) Assign the copyright on the contribution to myself, Roberto Tyley **or** b) Disclaim copyright on it and thus put it in the public domain **Please specify which option you want to use when creating your pull request.** See the [GNU FAQ](http://www.gnu.org/licenses/gpl-faq.html#AssignCopyright) for a fuller explanation of the need for this. If you still want to retain copyright on your contribution, let me know and I'll see if we can work something out. ================================================ FILE: LICENSE ================================================ 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 . ================================================ FILE: README.md ================================================ BFG Repo-Cleaner ================ [![CI](https://github.com/rtyley/bfg-repo-cleaner/actions/workflows/ci.yml/badge.svg)](https://github.com/rtyley/bfg-repo-cleaner/actions/workflows/ci.yml) [![Release](https://github.com/rtyley/bfg-repo-cleaner/actions/workflows/release.yml/badge.svg)](https://github.com/rtyley/bfg-repo-cleaner/actions/workflows/release.yml) _Removes large or troublesome blobs like git-filter-branch does, but faster - and written in Scala_ - [Fund the BFG](https://j.mp/fund-bfg) ``` $ bfg --strip-blobs-bigger-than 1M --replace-text banned.txt repo.git ``` The BFG is a simpler, faster ([10 - 720x](https://docs.google.com/spreadsheet/ccc?key=0AsR1d5Zpes8HdER3VGU1a3dOcmVHMmtzT2dsS2xNenc) faster) alternative to `git-filter-branch` for cleansing bad data out of your Git repository: * Removing **Crazy Big Files** * Removing **Passwords, Credentials** & other **Private data** Main documentation for The BFG is here : **https://rtyley.github.io/bfg-repo-cleaner/** ================================================ FILE: backers.md ================================================ Many thanks to supporters of the BFG! ----- Contribute towards the open-source development of the BFG on [**BountySource**](https://www.bountysource.com/teams/bfg-repo-cleaner) * [Thomas Ferris Nicolaisen](http://www.tfnico.com/) - host of the excellent [GitMinutes](http://www.gitminutes.com) podcast * [Alec Clews](https://alecthegeek.github.io/) * [ramtej](https://github.com/ramtej) ================================================ FILE: bfg/build.sbt ================================================ import java.io.{File, FileOutputStream} import Dependencies.* import sbt.taskKey import scala.sys.process.Process import scala.util.Try val gitDescription = taskKey[String]("Git description of working dir") gitDescription := Try[String](Process("git describe --all --always --dirty --long").lineStream.head.replace("heads/","").replace("-0-g","-")).getOrElse("unknown") libraryDependencies += useNewerJava mainClass := Some("use.newer.java.Version8") Compile / packageBin / packageOptions += Package.ManifestAttributes( "Main-Class-After-UseNewerJava-Check" -> "com.madgag.git.bfg.cli.Main" ) // note you don't want the jar name to collide with the non-assembly jar, otherwise confusion abounds. assembly / assemblyJarName := s"${name.value}-${version.value}-${gitDescription.value}${jgitVersionOverride.map("-jgit-" + _).mkString}.jar" assembly / assemblyMergeStrategy := { case PathList("META-INF", "versions", "9", "module-info.class") => MergeStrategy.discard case x => val oldStrategy = (assembly / assemblyMergeStrategy).value oldStrategy(x) } buildInfoKeys := Seq[BuildInfoKey](version, scalaVersion, gitDescription) buildInfoPackage := "com.madgag.git.bfg" crossPaths := false Compile / packageBin / publishArtifact := false // replace the conventional main artifact with an uber-jar addArtifact(Compile / packageBin / artifact, assembly) val cliUsageDump = taskKey[File]("Dump the CLI 'usage' output to a file") cliUsageDump := { val usageDumpFile = File.createTempFile("bfg-usage", "dump.txt") val scalaRun = new ForkRun(ForkOptions().withOutputStrategy(CustomOutput(new FileOutputStream(usageDumpFile)))) val mainClassName = (Compile / run / mainClass).value getOrElse sys.error("No main class detected.") val classpath = Attributed.data((Runtime / fullClasspath).value) val args = Seq.empty scalaRun.run(mainClassName, classpath, args, streams.value.log).failed foreach (sys error _.getMessage) usageDumpFile } addArtifact( Artifact("bfg", "usage", "txt"), cliUsageDump ) libraryDependencies ++= Seq( scopt, jgit, scalaGitTest % "test" ) import Tests.* { def isolateTestsWhichRequireTheirOwnJvm(tests: Seq[TestDefinition]) = { val (testsRequiringIsolation, testsNotNeedingIsolation) = tests.partition(_.name.contains("RequiresOwnJvm")) val groups: Seq[Seq[TestDefinition]] = testsRequiringIsolation.map(Seq(_)) :+ testsNotNeedingIsolation groups map { group => Group(group.size.toString, group, SubProcess(ForkOptions())) } } Test / testGrouping := isolateTestsWhichRequireTheirOwnJvm( (Test / definedTests).value ) } Test / fork := true // JGit uses static (ie JVM-wide) config Test / logBuffered := false Test / parallelExecution := false ================================================ FILE: bfg/src/main/scala/com/madgag/git/bfg/cli/CLIConfig.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cli import com.madgag.git.bfg.BuildInfo import com.madgag.git.bfg.GitUtil._ import com.madgag.git.bfg.cleaner._ import com.madgag.git.bfg.cleaner.kit.BlobInserter import com.madgag.git.bfg.cleaner.protection.ProtectedObjectCensus import com.madgag.git.bfg.model.FileName.ImplicitConversions._ import com.madgag.git.bfg.model.{FileName, Tree, TreeBlobEntry, TreeBlobs, TreeSubtrees} import com.madgag.git.{SizedObject, _} import com.madgag.inclusion.{IncExcExpression, _} import com.madgag.text.ByteSize import com.madgag.textmatching.{Glob, TextMatcher, TextMatcherType, TextReplacementConfig} import org.eclipse.jgit.internal.storage.file.FileRepository import org.eclipse.jgit.lib._ import org.eclipse.jgit.storage.file.FileRepositoryBuilder import scopt.{OptionParser, Read} import java.io.File import java.nio.file.Files import scala.jdk.CollectionConverters._ object CLIConfig { val parser = new OptionParser[CLIConfig]("bfg") { def fileMatcher(name: String, defaultType: TextMatcherType = Glob) = { implicit val textMatcherRead: Read[TextMatcher] = Read.reads { TextMatcher(_, defaultType) } opt[TextMatcher](name).valueName(s"<${defaultType.expressionPrefix}>").validate { m => if (m.expression.contains('/')) { failure("*** Can only match on filename, NOT path *** - remove '/' path segments") } else success } } def readLinesFrom(v: File): Seq[String] = Files.readAllLines(v.toPath).asScala.toSeq val exactVersion = BuildInfo.version + (if (BuildInfo.version.contains("-SNAPSHOT")) s" (${BuildInfo.gitDescription})" else "") head("bfg", exactVersion) version("version").hidden() opt[String]('b', "strip-blobs-bigger-than").valueName("").text("strip blobs bigger than X (eg '128K', '1M', etc)").action { (v , c) => c.copy(stripBlobsBiggerThan = Some(ByteSize.parse(v))) } opt[Int]('B', "strip-biggest-blobs").valueName("NUM").text("strip the top NUM biggest blobs").action { (v, c) => c.copy(stripBiggestBlobs = Some(v)) } opt[File]("strip-blobs-with-ids").abbr("bi").valueName("").text("strip blobs with the specified Git object ids").action { (v, c) => c.copy(stripBlobsWithIds = Some(readLinesFrom(v).map(_.trim).filterNot(_.isEmpty).map(_.asObjectId).toSet)) } fileMatcher("delete-files").abbr("D").text("delete files with the specified names (eg '*.class', '*.{txt,log}' - matches on file name, not path within repo)").action { (v, c) => c.copy(deleteFiles = Some(v)) } fileMatcher("delete-folders").text("delete folders with the specified names (eg '.svn', '*-tmp' - matches on folder name, not path within repo)").action { (v, c) => c.copy(deleteFolders = Some(v)) } opt[String]("convert-to-git-lfs").text("extract files with the specified names (eg '*.zip' or '*.mp4') into Git LFS").action { (v, c) => c.copy(lfsConversion = Some(v)) } opt[File]("replace-text").abbr("rt").valueName("").text("filter content of files, replacing matched text. Match expressions should be listed in the file, one expression per line - " + "by default, each expression is treated as a literal, but 'regex:' & 'glob:' prefixes are supported, with '==>' to specify a replacement " + "string other than the default of '***REMOVED***'.").action { (v, c) => c.copy(textReplacementExpressions = readLinesFrom(v).filterNot(_.trim.isEmpty)) } fileMatcher("filter-content-including").abbr("fi").text("do file-content filtering on files that match the specified expression (eg '*.{txt,properties}')").action { (v, c) => c.copy(filenameFilters = c.filenameFilters :+ Include(v)) } fileMatcher("filter-content-excluding").abbr("fe").text("don't do file-content filtering on files that match the specified expression (eg '*.{xml,pdf}')").action { (v, c) => c.copy(filenameFilters = c.filenameFilters :+ Exclude(v)) } opt[String]("filter-content-size-threshold").abbr("fs").valueName("").text("only do file-content filtering on files smaller than (default is %1$d bytes)".format(CLIConfig().filterSizeThreshold)).action { (v, c) => c.copy(filterSizeThreshold = ByteSize.parse(v)) } opt[String]('p', "protect-blobs-from").valueName("").text("protect blobs that appear in the most recent versions of the specified refs (default is 'HEAD')").action { (v, c) => c.copy(protectBlobsFromRevisions = v.split(',').toSet) } opt[Unit]("no-blob-protection").text("allow the BFG to modify even your *latest* commit. Not recommended: you should have already ensured your latest commit is clean.").action { (_, c) => c.copy(protectBlobsFromRevisions = Set.empty) } opt[Unit]("strict-object-checking").text("perform additional checks on integrity of consumed & created objects").hidden().action { (_, c) => c.copy(strictObjectChecking = true) } opt[Unit]("private").text("treat this repo-rewrite as removing private data (for example: omit old commit ids from commit messages)").action { (_, c) => c.copy(sensitiveData = Some(true)) } opt[String]("massive-non-file-objects-sized-up-to").valueName("").text("increase memory usage to handle over-size Commits, Tags, and Trees that are up to X in size (eg '10M')").action { (v, c) => c.copy(massiveNonFileObjects = Some(ByteSize.parse(v))) } opt[String]("fix-filename-duplicates-preferring").valueName("").text("Fix corrupt trees which contain multiple entries with the same filename, favouring the 'tree' or 'blob'").hidden().action { (v, c) => val preferredFileMode = v.toLowerCase match { case "tree" | "folder" => FileMode.TREE case "blob" | "file" => FileMode.REGULAR_FILE case other => throw new IllegalArgumentException(s"'$other' should be 'tree' or 'blob'") } val ord: Option[Ordering[FileMode]] = Some(Ordering.by[FileMode, Int](filemode => if (filemode==preferredFileMode) 0 else 1)) c.copy(fixFilenameDuplicatesPreferring = ord) } arg[File]("").optional().action { (x, c) => c.copy(repoLocation = x) } text("file path for Git repository to clean") } } case class CLIConfig(stripBiggestBlobs: Option[Int] = None, stripBlobsBiggerThan: Option[Long] = None, protectBlobsFromRevisions: Set[String] = Set("HEAD"), deleteFiles: Option[TextMatcher] = None, deleteFolders: Option[TextMatcher] = None, fixFilenameDuplicatesPreferring: Option[Ordering[FileMode]] = None, filenameFilters: Seq[Filter[String]] = Nil, filterSizeThreshold: Long = BlobTextModifier.DefaultSizeThreshold, textReplacementExpressions: Iterable[String] = List.empty, stripBlobsWithIds: Option[Set[ObjectId]] = None, lfsConversion: Option[String] = None, strictObjectChecking: Boolean = false, sensitiveData: Option[Boolean] = None, massiveNonFileObjects: Option[Long] = None, repoLocation: File = new File(System.getProperty("user.dir"))) { lazy val gitdir = resolveGitDirFor(repoLocation) implicit lazy val repo: FileRepository = FileRepositoryBuilder.create(gitdir.get).asInstanceOf[FileRepository] lazy val objectProtection = ProtectedObjectCensus(protectBlobsFromRevisions) lazy val objectChecker = if (strictObjectChecking) Some(new ObjectChecker()) else None lazy val fileDeletion: Option[Cleaner[TreeBlobs]] = deleteFiles.map { textMatcher => new FileDeleter(textMatcher) } lazy val folderDeletion: Option[Cleaner[TreeSubtrees]] = deleteFolders.map { textMatcher => { subtrees: TreeSubtrees => TreeSubtrees(subtrees.entryMap.view.filterKeys(filename => !textMatcher(filename)).toMap) } } lazy val fixFileNameDuplication: Option[Cleaner[Seq[Tree.Entry]]] = fixFilenameDuplicatesPreferring.map { implicit preferredFileModes => { treeEntries: Seq[Tree.Entry] => treeEntries.groupBy(_.name).values.map(_.minBy(_.fileMode)).toSeq } } lazy val lineModifier: Option[String => String] = TextReplacementConfig(textReplacementExpressions, "***REMOVED***") lazy val filterContentPredicate: (FileName => Boolean) = f => IncExcExpression(filenameFilters) includes (f.string) lazy val blobTextModifier: Option[BlobTextModifier] = lineModifier.map { replacer => new BlobTextModifier { override val sizeThreshold = filterSizeThreshold def lineCleanerFor(entry: TreeBlobEntry) = if (filterContentPredicate(entry.filename)) Some(replacer) else None val threadLocalObjectDBResources = repo.getObjectDatabase.threadLocalResources } } lazy val lfsBlobConverter: Option[LfsBlobConverter] = lfsConversion.map { lfsGlobExpr => new LfsBlobConverter(lfsGlobExpr, repo) } lazy val privateDataRemoval = sensitiveData.getOrElse(Seq(fileDeletion, folderDeletion, blobTextModifier).flatten.nonEmpty) lazy val objectIdSubstitutor = if (privateDataRemoval) ObjectIdSubstitutor.OldIdsPrivate else ObjectIdSubstitutor.OldIdsPublic lazy val treeEntryListCleaners = fixFileNameDuplication.toSeq lazy val commitNodeCleaners = { lazy val formerCommitFooter = if (privateDataRemoval) None else Some(FormerCommitFooter) Seq(new CommitMessageObjectIdsUpdater(objectIdSubstitutor)) ++ formerCommitFooter } lazy val treeBlobCleaners: Seq[Cleaner[TreeBlobs]] = { lazy val blobsByIdRemover: Option[BlobRemover] = stripBlobsWithIds.map(new BlobRemover(_)) lazy val blobRemover: Option[Cleaner[TreeBlobs]] = { implicit val progressMonitor: ProgressMonitor = new TextProgressMonitor() val sizeBasedBlobTargetSources = Seq( stripBlobsBiggerThan.map(threshold => (s: LazyList[SizedObject]) => s.takeWhile(_.size > threshold)), stripBiggestBlobs.map(num => (s: LazyList[SizedObject]) => s.take(num)) ).flatten if (sizeBasedBlobTargetSources.isEmpty) None else { val sizedBadIds = sizeBasedBlobTargetSources.flatMap(_(biggestBlobs(repo.getObjectDatabase, progressMonitor))).toSet if (sizedBadIds.isEmpty) { println("Warning : no large blobs matching criteria found in packfiles - does the repo need to be packed?") None } else { println("Found " + sizedBadIds.size + " blob ids for large blobs - biggest=" + sizedBadIds.max.size + " smallest=" + sizedBadIds.min.size) println("Total size (unpacked)=" + sizedBadIds.map(_.size).sum) Some(new BlobReplacer(sizedBadIds.map(_.objectId), new BlobInserter(repo.getObjectDatabase.threadLocalResources.inserter()))) } } } Seq(blobsByIdRemover, blobRemover, fileDeletion, blobTextModifier, lfsBlobConverter).flatten } lazy val definesNoWork = treeBlobCleaners.isEmpty && folderDeletion.isEmpty && treeEntryListCleaners.isEmpty def objectIdCleanerConfig: ObjectIdCleaner.Config = ObjectIdCleaner.Config( objectProtection, objectIdSubstitutor, commitNodeCleaners, treeEntryListCleaners, treeBlobCleaners, folderDeletion.toSeq, objectChecker ) def describe = { if (privateDataRemoval) { "is removing private data, so the '" + FormerCommitFooter.Key + "' footer will not be added to commit messages." } else { "is only removing non-private data (eg, blobs that are just big, not private) : '" + FormerCommitFooter.Key + "' footer will be added to commit messages." } } } ================================================ FILE: bfg/src/main/scala/com/madgag/git/bfg/cli/Main.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cli import com.madgag.git._ import com.madgag.git.bfg.GitUtil._ import com.madgag.git.bfg.cleaner._ object Main extends App { if (args.isEmpty) { CLIConfig.parser.showUsage() } else { CLIConfig.parser.parse(args, CLIConfig()) map { config => tweakStaticJGitConfig(config.massiveNonFileObjects) if (config.gitdir.isEmpty) { CLIConfig.parser.showUsage() Console.err.println("Aborting : " + config.repoLocation + " is not a valid Git repository.\n") } else { implicit val repo = config.repo println("\nUsing repo : " + repo.getDirectory.getAbsolutePath + "\n") // do this before implicitly initiating big-blob search if (hasBeenProcessedByBFGBefore(repo)) { println("\nThis repo has been processed by The BFG before! Will prune repo before proceeding - to avoid unnecessary cleaning work on unused objects...") repo.git.gc.call() println("Completed prune of old objects - will now proceed with the main job!\n") } if (config.definesNoWork) { Console.err.println("Please specify tasks for The BFG :") CLIConfig.parser.showUsage() } else { println("Found " + config.objectProtection.fixedObjectIds.size + " objects to protect") RepoRewriter.rewrite(repo, config.objectIdCleanerConfig) repo.close() } } } } } ================================================ FILE: bfg/src/test/scala/com/madgag/git/bfg/cli/CLIConfigSpecs.scala ================================================ package com.madgag.git.bfg.cli import com.madgag.git.bfg.model.FileName import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class CLIConfigSpecs extends AnyFlatSpec with Matchers { def parse(args: String) = CLIConfig.parser.parse(args.split(' ') :+ "my-repo.git", CLIConfig()).get.filterContentPredicate "CLI config" should "understand lone include" in { val predicate = parse("-fi *.txt") predicate(FileName("panda")) shouldBe false predicate(FileName("foo.txt")) shouldBe true predicate(FileName("foo.java")) shouldBe false } it should "understand lone exclude" in { val predicate = parse("-fe *.txt") predicate(FileName("panda")) shouldBe true predicate(FileName("foo.txt")) shouldBe false predicate(FileName("foo.java")) shouldBe true } it should "understand include followed by exclude" in { val predicate = parse("-fi *.txt -fe Poison.*") predicate(FileName("panda")) shouldBe false predicate(FileName("foo.txt")) shouldBe true predicate(FileName("foo.java")) shouldBe false predicate(FileName("Poison.txt")) shouldBe false } it should "understand exclude followed by include" in { val predicate = parse("-fe *.xml -fi hbm.xml") predicate(FileName("panda")) shouldBe true predicate(FileName("foo.xml")) shouldBe false predicate(FileName("hbm.xml")) shouldBe true } } ================================================ FILE: bfg/src/test/scala/com/madgag/git/bfg/cli/MainSpec.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cli import com.madgag.git._ import com.madgag.git.bfg.cli.test.unpackedRepo import com.madgag.git.bfg.model._ import org.eclipse.jgit.lib.{ObjectId, ObjectReader} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{Inspectors, OptionValues} import java.nio.file.Files import scala.jdk.CollectionConverters._ class MainSpec extends AnyFlatSpec with Matchers with OptionValues with Inspectors { // concurrent testing against scala.App is not safe https://twitter.com/rtyley/status/340376844916387840 "CLI" should "not change commits unnecessarily" in new unpackedRepo("/sample-repos/exampleWithInitialCleanHistory.git.zip") { implicit val r: ObjectReader = reader ensureInvariantValue(commitHist() take 2) { ensureRemovalFrom(commitHist()).ofCommitsThat(haveCommitWhereObjectIds(contain(abbrId("294f")))) { run("--strip-blobs-bigger-than 1K") } } } "removing empty trees" should "work" in new unpackedRepo("/sample-repos/folder-example.git.zip") { ensureRemovalFrom(commitHist()).ofCommitsThat(haveFolder("secret-files")) { run("--delete-files {credentials,passwords}.txt") } } "removing big blobs" should "definitely still remove blobs even if they have identical size" in new unpackedRepo("/sample-repos/moreThanOneBigBlobWithTheSameSize.git.zip") { ensureRemovalOfBadEggs(packedBlobsOfSize(1024), (contain allElementsOf Set(abbrId("06d7"), abbrId("cb2c"))).matcher[Iterable[ObjectId]]) { run("--strip-blobs-bigger-than 512B") } } "converting to Git LFS" should "create a file in lfs/objects" in new unpackedRepo("/sample-repos/repoWithBigBlobs.git.zip") { ensureRemovalOfBadEggs(packedBlobsOfSize(11238), (contain only abbrId("596c")).matcher[Iterable[ObjectId]]) { run("--convert-to-git-lfs *.png --no-blob-protection") } val lfsFile = repo.getDirectory.toPath.resolve(Seq("lfs", "objects", "e0", "eb", "e0ebd49837a1cced34b9e7d3ff2fa68a8100df8f158f165ce139e366a941ba6e")) Files.size(lfsFile) shouldBe 11238 } "removing a folder named '.git'" should "work" in new unpackedRepo("/sample-repos/badRepoContainingDotGitFolder.git.zip") { ensureRemovalFrom(commitHist()).ofCommitsThat(haveFolder(".git")) { run("--delete-folders .git --no-blob-protection") } } "cleaning" should "not crash encountering a protected an annotated tag" in new unpackedRepo("/sample-repos/annotatedTagExample.git.zip") { ensureInvariantCondition(haveRef("chapter1", haveFile("chapter1.txt"))) { ensureRemovalFrom(commitHist("master")).ofCommitsThat(haveFile("chapter2.txt")) { run("--strip-blobs-bigger-than 10B --protect-blobs-from chapter1") } } } "cleaning" should "not crash encountering a protected branch containing a slash in it's name" in new unpackedRepo("/sample-repos/branchNameWithASlash.git.zip") { ensureInvariantCondition(haveRef("feature/slashes-are-ugly", haveFile("bar"))) { ensureRemovalFrom(commitHist("master")).ofCommitsThat(haveFile("bar")) { run("--delete-files bar --protect-blobs-from feature/slashes-are-ugly") } } } "strip blobs by id" should "work" in new unpackedRepo("/sample-repos/example.git.zip") { implicit val r: ObjectReader = reader val badBlobs = Set(abbrId("db59"), abbrId("86f9")) val blobIdsFile = Files.createTempFile("test-strip-blobs",".ids") Files.write(blobIdsFile, badBlobs.map(_.name()).asJava) ensureRemovalFrom(commitHist()).ofCommitsThat(haveCommitWhereObjectIds(contain(abbrId("db59")))) { run(s"--strip-blobs-with-ids $blobIdsFile") } } "deleting a folder" should "not crash encountering a submodule" in new unpackedRepo("/sample-repos/usedToHaveASubmodule.git.zip") { ensureInvariantCondition(haveRef("master", haveFile("alpha"))) { ensureRemovalFrom(commitHist()).ofCommitsThat(haveFolder("shared")) { run("--delete-folders shared") } } } "deleting" should "not crash encountering a protected submodule" in new unpackedRepo("/sample-repos/unwantedSubmodule.git.zip") { ensureRemovalFrom(commitHist()).ofCommitsThat(haveFile("foo.txt")) { run("--delete-folders bar --delete-files foo.txt") } } "deleting" should "not crash on encountering a commit with bad encoding header" in new unpackedRepo("/sample-repos/badEncoding.git.zip") { ensureRemovalFrom(commitHist()).ofCommitsThat(haveFile("test.txt")) { run("--no-blob-protection --delete-files test.txt") } } "Corrupt trees containing duplicate filenames" should "be cleaned by removing the file with the duplicate FileName, leaving the folder" in new unpackedRepo("/sample-repos/corruptTreeDupFileName.git.zip") { ensureRemovalFrom(commitHist()).ofCommitsThat(haveFile("2.0.0")) { run("--fix-filename-duplicates-preferring tree") } } } ================================================ FILE: bfg/src/test/scala/com/madgag/git/bfg/cli/MassiveNonFileObjectsRequiresOwnJvmSpec.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cli import com.madgag.git.bfg.cli.test.unpackedRepo import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers // JGit has JVM-wide configuration for cache window size: https://git.eclipse.org/r/#/q/Ibf2ef604bac08885b2b3bd85f0dc31995132b682,n,z class MassiveNonFileObjectsRequiresOwnJvmSpec extends AnyFlatSpec with Matchers { // concurrent testing against scala.App is not safe https://twitter.com/rtyley/status/340376844916387840 "Massive commit messages" should "be handled without crash (ie LargeObjectException) if the user specifies that the repo contains massive non-file objects" in new unpackedRepo("/sample-repos/huge10MBCommitMessage.git.zip") { ensureRemovalFrom(commitHist("master")).ofCommitsThat(haveFile("16-kb-zeros")) { run("--strip-blobs-bigger-than 1K --massive-non-file-objects-sized-up-to 20M") } } } ================================================ FILE: bfg/src/test/scala/com/madgag/git/bfg/cli/test/unpackedRepo.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cli.test import com.madgag.git.bfg import com.madgag.git.bfg.cli.Main class unpackedRepo(filePath: String) extends bfg.test.unpackedRepo(filePath) { def run(options: String): Unit = { Main.main(options.split(' ') :+ repo.getDirectory.getAbsolutePath) } } ================================================ FILE: bfg-benchmark/build.sbt ================================================ import Dependencies.* libraryDependencies ++= guava ++ Seq( madgagCompress, textmatching, scopt ) ================================================ FILE: bfg-benchmark/resources/jars/grabJars.sh ================================================ #!/bin/bash for i in 4.0 5.0 6.0 7.0 12.0 13.0 13.1 13.2 do VERSION="1.$i" curl -O "https://repo1.maven.org/maven2/com/madgag/bfg/$VERSION/bfg-$VERSION.jar" done ================================================ FILE: bfg-benchmark/resources/repos/chromium-src/commands/issue-23/bfg.txt ================================================ --delete-files *.{52,50,crx,xib,png,pdf,jpg,zip,jar,pdb,psd,jpeg,dylib,dll,DLL,exe,EXE,vcproj,so,sln,scons,nib,graffle,yuv,webm} ================================================ FILE: bfg-benchmark/resources/repos/gcc/commands/delete-file/bfg.txt ================================================ -D README-fixinc ================================================ FILE: bfg-benchmark/resources/repos/gcc/commands/delete-file/gfb.txt ================================================ --index-filter git rm --cached --ignore-unmatch gcc/README-fixinc --prune-empty --tag-name-filter cat -- --all ================================================ FILE: bfg-benchmark/resources/repos/git/commands/delete-file/bfg.txt ================================================ -D object.c ================================================ FILE: bfg-benchmark/resources/repos/git/commands/delete-file/gfb.txt ================================================ --index-filter git rm --cached --ignore-unmatch object.c --prune-empty --tag-name-filter cat -- --all ================================================ FILE: bfg-benchmark/resources/repos/github-gem/commands/delete-file/bfg.txt ================================================ -D Rakefile ================================================ FILE: bfg-benchmark/resources/repos/github-gem/commands/delete-file/gfb.txt ================================================ --index-filter git rm --cached --ignore-unmatch Rakefile --prune-empty --tag-name-filter cat -- --all ================================================ FILE: bfg-benchmark/resources/repos/intellij/commands/delete-binary-resources/bfg.txt ================================================ --delete-files *.{zip,jar} --no-blob-protection ================================================ FILE: bfg-benchmark/resources/repos/intellij/commands/delete-file/bfg.txt ================================================ -D breakgen.dll ================================================ FILE: bfg-benchmark/resources/repos/intellij/commands/delete-file/gfb.txt ================================================ --index-filter git rm --cached --ignore-unmatch bin/breakgen.dll --prune-empty --tag-name-filter cat -- --all ================================================ FILE: bfg-benchmark/resources/repos/intellij/commands/git-lfs-binary-resources/bfg.txt ================================================ --convert-to-git-lfs *.{zip,jar,exe,dll} --no-blob-protection ================================================ FILE: bfg-benchmark/resources/repos/jgit/commands/delete-file/bfg.txt ================================================ -D make_jgit.sh ================================================ FILE: bfg-benchmark/resources/repos/jgit/commands/delete-file/gfb.txt ================================================ --index-filter git rm --cached --ignore-unmatch make_jgit.sh --prune-empty --tag-name-filter cat -- --all ================================================ FILE: bfg-benchmark/resources/repos/jgit/commands/replace-1-existing-string/bfg.txt ================================================ --replace-text passwords.1-existing-string.txt ================================================ FILE: bfg-benchmark/resources/repos/jgit/commands/replace-1-existing-string/passwords.1-existing-string.txt ================================================ invalidAdvertisementOf ================================================ FILE: bfg-benchmark/resources/repos/jgit/commands/replace-20-existing-strings/bfg.txt ================================================ --replace-text passwords.20-existing-strings.txt ================================================ FILE: bfg-benchmark/resources/repos/jgit/commands/replace-20-existing-strings/passwords.20-existing-strings.txt ================================================ invalidAdvertisementOf abbreviationLengthMustBeNonNegative abortingRebase abortingRebaseFailed abortingRebaseFailedNoOrigHead advertisementCameBefore advertisementOfCameBefore amazonS3ActionFailed amazonS3ActionFailedGivingUp ambiguousObjectAbbreviation aNewObjectIdIsRequired anExceptionOccurredWhileTryingToAddTheIdOfHEAD anSSHSessionHasBeenAlreadyCreated applyingCommitnvalidType corruptObjectInvalidType2 corruptObjectMalformedHeader dirCacheIsNotLocked DIRCChecksumMismatch enumValueNotSupported3 errorDecodingFromFile ================================================ FILE: bfg-benchmark/resources/repos/jgit/commands/replace-500-existing-strings/bfg.txt ================================================ --replace-text passwords.500-existing-strings.txt ================================================ FILE: bfg-benchmark/resources/repos/jgit/commands/replace-500-existing-strings/passwords.500-existing-strings.txt ================================================ abbreviationLengthMustBeNonNegative abortingRebase abortingRebaseFailed abortingRebaseFailedNoOrigHead advertisementCameBefore advertisementOfCameBefore amazonS3ActionFailed amazonS3ActionFailedGivingUp ambiguousObjectAbbreviation aNewObjectIdIsRequired anExceptionOccurredWhileTryingToAddTheIdOfHEAD anSSHSessionHasBeenAlreadyCreated applyingCommit archiveFormatAlreadyAbsent archiveFormatAlreadyRegistered atLeastOnePathIsRequired atLeastOnePatternIsRequired atLeastTwoFiltersNeeded authenticationNotSupported badBase64InputCharacterAt badEntryDelimiter badEntryName badEscape badGroupHeader badObjectType badSectionEntry bareRepositoryNoWorkdirAndIndex base64InputNotProperlyPadded baseLengthIncorrect bitmapMissingObject bitmapsMustBePrepared blameNotCommittedYet blobNotFound blobNotFoundForPath branchNameInvalid buildingBitmaps cachedPacksPreventsIndexCreation cachedPacksPreventsListingObjects cannotBeCombined cannotBeRecursiveWhenTreesAreIncluded cannotCombineSquashWithNoff cannotCombineTreeFilterWithRevFilter cannotCommitOnARepoWithState cannotCommitWriteTo cannotConnectPipes cannotConvertScriptToText cannotCreateConfig cannotCreateDirectory cannotCreateHEAD cannotCreateIndexfile cannotDeleteCheckedOutBranch cannotDeleteFile cannotDeleteStaleTrackingRef cannotDeleteStaleTrackingRef2 cannotDetermineProxyFor cannotDownload cannotExecute cannotGet cannotListRefs cannotLock cannotLockPackIn cannotMatchOnEmptyString cannotMoveIndexTo cannotMovePackTo cannotOpenService cannotParseDate cannotParseGitURIish cannotPullOnARepoWithState cannotRead cannotReadBlob cannotReadCommit cannotReadFile cannotReadHEAD cannotReadObject cannotReadTree cannotRebaseWithoutCurrentHead cannotResolveLocalTrackingRefForUpdating cannotStoreObjects cannotUnloadAModifiedTree cannotWorkWithOtherStagesThanZeroRightNow canOnlyCherryPickCommitsWithOneParent canOnlyRevertCommitsWithOneParent cantFindObjectInReversePackIndexForTheSpecifiedOffset cantPassMeATree channelMustBeInRange0_255 characterClassIsNotSupported checkoutConflictWithFile checkoutConflictWithFiles checkoutUnexpectedResult classCastNotA cloneNonEmptyDirectory collisionOn commandWasCalledInTheWrongState commitAlreadyExists commitMessageNotSpecified commitOnRepoWithoutHEADCurrentlyNotSupported commitAmendOnInitialNotPossible compressingObjects connectionFailed connectionTimeOut contextMustBeNonNegative corruptionDetectedReReadingAt corruptObjectBadStream corruptObjectBadStreamCorruptHeader corruptObjectGarbageAfterSize corruptObjectIncorrectLength corruptObjectInvalidEntryMode corruptObjectInvalidMode corruptObjectInvalidMode2 corruptObjectInvalidMode3 corruptObjectInvalidType corruptObjectInvalidType2 corruptObjectMalformedHeader corruptObjectNegativeSize corruptObjectNoAuthor corruptObjectNoCommitter corruptObjectNoHeader corruptObjectNoObject corruptObjectNoTaggerBadHeader corruptObjectNoTaggerHeader corruptObjectNoTagName corruptObjectNotree corruptObjectNoType corruptObjectPackfileChecksumIncorrect couldNotCheckOutBecauseOfConflicts couldNotDeleteLockFileShouldNotHappen couldNotDeleteTemporaryIndexFileShouldNotHappen couldNotGetAdvertisedRef couldNotGetRepoStatistics couldNotLockHEAD couldNotReadIndexInOneGo couldNotReadObjectWhileParsingCommit couldNotRenameDeleteOldIndex couldNotRenameTemporaryFile couldNotRenameTemporaryIndexFileToIndex couldNotURLEncodeToUTF8 couldNotWriteFile countingObjects createBranchFailedUnknownReason createBranchUnexpectedResult createNewFileFailed credentialPassword credentialUsername daemonAlreadyRunning daysAgo deleteBranchUnexpectedResult deleteFileFailed deleteTagUnexpectedResult deletingNotSupported destinationIsNotAWildcard detachedHeadDetected dirCacheDoesNotHaveABackingFile dirCacheFileIsNotLocked dirCacheIsNotLocked DIRCChecksumMismatch DIRCExtensionIsTooLargeAt DIRCExtensionNotSupportedByThisVersion DIRCHasTooManyEntries DIRCUnrecognizedExtendedFlags dirtyFilesExist doesNotHandleMode downloadCancelled downloadCancelledDuringIndexing duplicateAdvertisementsOf duplicateRef duplicateRemoteRefUpdateIsIllegal duplicateStagesNotAllowed eitherGitDirOrWorkTreeRequired emptyCommit emptyPathNotPermitted encryptionError endOfFileInEscape entryNotFoundByPath enumValueNotSupported2 enumValueNotSupported3 enumValuesNotAvailable errorDecodingFromFile errorEncodingFromFile errorInBase64CodeReadingStream errorInPackedRefs errorInvalidProtocolWantedOldNewRef errorListing errorOccurredDuringUnpackingOnTheRemoteEnd errorReadingInfoRefs errorSymlinksNotSupported exceptionCaughtDuringExecutionOfAddCommand exceptionCaughtDuringExecutionOfArchiveCommand exceptionCaughtDuringExecutionOfCherryPickCommand exceptionCaughtDuringExecutionOfCommitCommand exceptionCaughtDuringExecutionOfFetchCommand exceptionCaughtDuringExecutionOfLsRemoteCommand exceptionCaughtDuringExecutionOfMergeCommand exceptionCaughtDuringExecutionOfPullCommand exceptionCaughtDuringExecutionOfPushCommand exceptionCaughtDuringExecutionOfResetCommand exceptionCaughtDuringExecutionOfRevertCommand exceptionCaughtDuringExecutionOfRmCommand exceptionCaughtDuringExecutionOfTagCommand exceptionOccurredDuringAddingOfOptionToALogCommand exceptionOccurredDuringReadingOfGIT_DIR expectedACKNAKFoundEOF expectedACKNAKGot expectedBooleanStringValue expectedCharacterEncodingGuesses expectedEOFReceived expectedGot expectedLessThanGot expectedPktLineWithService expectedReceivedContentType expectedReportForRefNotReceived failedUpdatingRefs failureDueToOneOfTheFollowing failureUpdatingFETCH_HEAD failureUpdatingTrackingRef fileCannotBeDeleted fileIsTooBigForThisConvenienceMethod fileIsTooLarge fileModeNotSetForPath flagIsDisposed flagNotFromThis flagsAlreadyCreated funnyRefname gcFailed gitmodulesNotFound headRequiredToStash hoursAgo hugeIndexesAreNotSupportedByJgitYet hunkBelongsToAnotherFile hunkDisconnectedFromFile hunkHeaderDoesNotMatchBodyLineCountOf illegalArgumentNotA illegalCombinationOfArguments illegalPackingPhase illegalStateExists improperlyPaddedBase64Input incorrectHashFor incorrectOBJECT_ID_LENGTH indexFileIsInUse indexFileIsTooLargeForJgit indexSignatureIsInvalid indexWriteException inMemoryBufferLimitExceeded inputStreamMustSupportMark integerValueOutOfRange internalRevisionError internalServerError interruptedWriting inTheFuture invalidAdvertisementOf invalidAncestryLength invalidBooleanValue invalidChannel invalidCharacterInBase64Data invalidCommitParentNumber invalidEncryption invalidGitdirRef invalidGitType invalidId invalidIdLength invalidIntegerValue invalidKey invalidLineInConfigFile invalidModeFor invalidModeForPath invalidObject invalidOldIdSent invalidPacketLineHeader invalidPath invalidReflogRevision invalidRefName invalidRemote invalidStageForPath invalidTagOption invalidTimeout invalidURL invalidWildcards invalidRefSpec invalidWindowSize isAStaticFlagAndHasNorevWalkInstance JRELacksMD5Implementation kNotInRange largeObjectExceedsByteArray largeObjectExceedsLimit largeObjectException largeObjectOutOfMemory lengthExceedsMaximumArraySize listingAlternates localObjectsIncomplete localRefIsMissingObjects lockCountMustBeGreaterOrEqual1 lockError lockOnNotClosed lockOnNotHeld malformedpersonIdentString maxCountMustBeNonNegative mergeConflictOnNonNoteEntries mergeConflictOnNotes mergeStrategyAlreadyExistsAsDefault mergeStrategyDoesNotSupportHeads mergeUsingStrategyResultedInDescription mergeRecursiveReturnedNoCommit mergeRecursiveTooManyMergeBasesFor messageAndTaggerNotAllowedInUnannotatedTags minutesAgo missingAccesskey missingConfigurationForKey missingDeltaBase missingForwardImageInGITBinaryPatch missingObject missingPrerequisiteCommits missingRequiredParameter missingSecretkey mixedStagesNotAllowed mkDirFailed mkDirsFailed month months monthsAgo multipleMergeBasesFor need2Arguments needPackOut needsAtLeastOneEntry needsWorkdir newlineInQuotesNotAllowed noApplyInDelete noClosingBracket noHEADExistsAndNoExplicitStartingRevisionWasSpecified noHMACsupport noMergeBase noMergeHeadSpecified noSuchRef notABoolean notABundle notADIRCFile notAGitDirectory notAPACKFile notARef notASCIIString notAuthorized notAValidPack notFound nothingToFetch nothingToPush notMergedExceptionMessage noXMLParserAvailable objectAtHasBadZlibStream objectAtPathDoesNotHaveId objectIsCorrupt objectIsNotA objectNotFound objectNotFoundIn obtainingCommitsForCherryPick offsetWrittenDeltaBaseForObjectNotFoundInAPack onlyAlreadyUpToDateAndFastForwardMergesAreAvailable onlyOneFetchSupported onlyOneOperationCallPerConnectionIsSupported openFilesMustBeAtLeast1 openingConnection operationCanceled outputHasAlreadyBeenStarted packChecksumMismatch packCorruptedWhileWritingToFilesystem packDoesNotMatchIndex packetSizeMustBeAtLeast packetSizeMustBeAtMost packfileCorruptionDetected packFileInvalid packfileIsTruncated packHasUnresolvedDeltas packingCancelledDuringObjectsWriting packObjectCountMismatch packRefs packTooLargeForIndexVersion1 packWriterStatistics panicCantRenameIndexFile patchApplyException patchFormatException pathIsNotInWorkingDir pathNotConfigured peeledLineBeforeRef peerDidNotSupplyACompleteObjectGraph prefixRemote problemWithResolvingPushRefSpecsLocally progressMonUploading propertyIsAlreadyNonNull pruneLoosePackedObjects pruneLooseUnreferencedObjects pullOnRepoWithoutHEADCurrentlyNotSupported pullTaskName pushCancelled pushIsNotSupportedForBundleTransport pushNotPermitted rawLogMessageDoesNotParseAsLogEntry readingObjectsFromLocalRepositoryFailed readTimedOut receivePackObjectTooLarge1 receivePackObjectTooLarge2 receivingObjects refAlreadyExists refAlreadyExists1 reflogEntryNotFound refNotResolved refUpdateReturnCodeWas remoteConfigHasNoURIAssociated remoteDoesNotHaveSpec remoteDoesNotSupportSmartHTTPPush remoteHungUpUnexpectedly remoteNameCantBeNull renameBranchFailedBecauseTag renameBranchFailedUnknownReason renameBranchUnexpectedResult renameFileFailed renamesAlreadyFound renamesBreakingModifies renamesFindingByContent renamesFindingExact renamesRejoiningModifies repositoryAlreadyExists repositoryConfigFileInvalid repositoryIsRequired repositoryNotFound repositoryState_applyMailbox repositoryState_bisecting repositoryState_conflicts repositoryState_merged repositoryState_normal repositoryState_rebase repositoryState_rebaseInteractive repositoryState_rebaseOrApplyMailbox repositoryState_rebaseWithMerge requiredHashFunctionNotAvailable resettingHead resolvingDeltas resultLengthIncorrect rewinding searchForReuse searchForSizes secondsAgo selectingCommits sequenceTooLargeForDiffAlgorithm serviceNotEnabledNoName serviceNotPermitted serviceNotPermittedNoName shallowCommitsAlreadyInitialized shortCompressedStreamAt shortReadOfBlock shortReadOfOptionalDIRCExtensionExpectedAnotherBytes shortSkipOfBlock signingNotSupportedOnTag similarityScoreMustBeWithinBounds sizeExceeds2GB skipMustBeNonNegative smartHTTPPushDisabled sourceDestinationMustMatch sourceIsNotAWildcard sourceRefDoesntResolveToAnyObject sourceRefNotSpecifiedForRefspec squashCommitNotUpdatingHEAD staleRevFlagsOn startingReadStageWithoutWrittenRequestDataPendingIsNotSupported stashApplyConflict stashApplyConflictInIndex stashApplyFailed stashApplyOnUnsafeRepository stashApplyWithoutHead stashCommitMissingTwoParents stashDropDeleteRefFailed stashDropFailed stashDropMissingReflog stashFailed stashResolveFailed statelessRPCRequiresOptionToBeEnabled submoduleExists submoduleParentRemoteUrlInvalid submodulesNotSupported symlinkCannotBeWrittenAsTheLinkTarget systemConfigFileInvalid tagAlreadyExists tagNameInvalid tagOnRepoWithoutHEADCurrentlyNotSupported theFactoryMustNotBeNull timerAlreadyTerminated topologicalSortRequired transportExceptionBadRef transportExceptionEmptyRef transportExceptionInvalid transportExceptionMissingAssumed transportExceptionReadRef transportNeedsRepository transportProtoAmazonS3 transportProtoBundleFile transportProtoFTP transportProtoGitAnon transportProtoHTTP transportProtoLocal transportProtoSFTP transportProtoSSH treeEntryAlreadyExists treeFilterMarkerTooManyFilters treeIteratorDoesNotSupportRemove ================================================ FILE: bfg-benchmark/resources/repos/linux/commands/delete-file/bfg.txt ================================================ -D MAINTAINERS ================================================ FILE: bfg-benchmark/resources/repos/linux/commands/delete-file/gfb.txt ================================================ --index-filter git rm --cached --ignore-unmatch MAINTAINERS --prune-empty --tag-name-filter cat -- --all ================================================ FILE: bfg-benchmark/resources/repos/rails/commands/delete-file/bfg.txt ================================================ -D pushgems.rb ================================================ FILE: bfg-benchmark/resources/repos/rails/commands/delete-file/gfb.txt ================================================ --index-filter git rm --cached --ignore-unmatch pushgems.rb --prune-empty --tag-name-filter cat -- --all ================================================ FILE: bfg-benchmark/resources/repos/wine/commands/delete-file/bfg.txt ================================================ -D build-spec.txt ================================================ FILE: bfg-benchmark/resources/repos/wine/commands/delete-file/gfb.txt ================================================ --index-filter git rm --cached --ignore-unmatch build-spec.txt --prune-empty --tag-name-filter cat -- --all ================================================ FILE: bfg-benchmark/src/main/scala/Benchmark.scala ================================================ import lib.Timing.measureTask import lib._ import model._ import java.nio.file.Files import java.nio.file.Files.isDirectory import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent._ import scala.concurrent.duration.Duration import scala.jdk.StreamConverters._ import scala.sys.process._ /* * Vary BFG runs by: * Java version * BFG version (JGit version?) * */ object Benchmark extends App { BenchmarkConfig.parser.parse(args, BenchmarkConfig()) map { config => println(s"Using resources dir : ${config.resourcesDir}") require(Files.exists(config.resourcesDir), s"Resources dir not found : ${config.resourcesDir}") require(Files.exists(config.jarsDir), s"Jars dir not found : ${config.jarsDir}") require(Files.exists(config.reposDir), s"Repos dir not found : ${config.reposDir}") val missingJars = config.bfgJars.filterNot(Files.exists(_)) require(missingJars.isEmpty, s"Missing BFG jars : ${missingJars.mkString(",")}") val tasksFuture = for { bfgInvocableEngineSet <- bfgInvocableEngineSet(config) } yield { val gfbInvocableEngineSetOpt = Option.when(!config.onlyBfg)(InvocableEngineSet[GFBInvocation](GitFilterBranch, Seq(InvocableGitFilterBranch))) boogaloo(config, new RepoExtractor(config.scratchDir), Seq(bfgInvocableEngineSet) ++ gfbInvocableEngineSetOpt.toSeq) } Await.result(tasksFuture, Duration.Inf) } def bfgInvocableEngineSet(config: BenchmarkConfig): Future[InvocableEngineSet[BFGInvocation]] = for { javas <- Future.traverse(config.javaCmds)(jc => JavaVersion.version(jc).map(v => Java(jc, v))) } yield { val invocables = for { java <- javas bfgJar <- config.bfgJars } yield InvocableBFG(java, BFGJar.from(bfgJar)) InvocableEngineSet[BFGInvocation](BFG, invocables) } /* * A Task says "here is something you can do to a given repo, and here is how to do * it with a BFG, and with git-filter-branch" */ def boogaloo(config: BenchmarkConfig, repoExtractor: RepoExtractor, invocableEngineSets: Seq[InvocableEngineSet[_ <: EngineInvocation]]) = { for { repoSpecDir <- config.repoSpecDirs availableCommandDirs = Files.list(repoSpecDir.resolve("commands")).toScala(Seq).filter(isDirectory(_)) // println(s"Available commands for $repoName : ${availableCommandDirs.map(_.name).mkString(", ")}") commandDir <- availableCommandDirs.filter(p => config.commands(p.getFileName.toString)) } yield { val commandName: String = commandDir.getFileName.toString commandName -> (for { invocableEngineSet <- invocableEngineSets } yield for { (invocable, processMaker) <- invocableEngineSet.invocationsFor(commandDir) } yield { val cleanRepoDir = repoExtractor.extractRepoFrom(repoSpecDir.resolve("repo.git.zip")) Files.list(commandDir).toScala(Seq).foreach(p => Files.copy(p, cleanRepoDir.resolve(p.getFileName))) val process = processMaker(cleanRepoDir.toFile) val duration = measureTask(s"$commandName - $invocable") { process ! ProcessLogger(_ => ()) } if (config.dieIfTaskTakesLongerThan.exists(_ < duration.toMillis)) { throw new Exception("This took too long: "+duration) } invocable -> duration }) } } println(s"\n...benchmark finished.") } ================================================ FILE: bfg-benchmark/src/main/scala/BenchmarkConfig.scala ================================================ import java.io.File import com.madgag.textmatching.{Glob, TextMatcher} import scopt.OptionParser import java.nio.file.{Path, Paths} object BenchmarkConfig { val parser = new OptionParser[BenchmarkConfig]("benchmark") { opt[File]("resources-dir").text("benchmark resources folder - contains jars and repos").action { (v, c) => c.copy(resourcesDirOption = v.toPath) } opt[String]("java").text("Java command paths").action { (v, c) => c.copy(javaCmds = v.split(',').toSeq) } opt[String]("versions").text("BFG versions to time - bfg-[version].jar - eg 1.4.0,1.5.0,1.6.0").action { (v, c) => c.copy(bfgVersions = v.split(",").toSeq) } opt[Int]("die-if-longer-than").text("Useful for git-bisect").action { (v, c) => c.copy(dieIfTaskTakesLongerThan = Some(v)) } opt[String]("repos").text("Sample repos to test, eg github-gems,jgit,git").action { (v, c) => c.copy(repoNames = v.split(",").toSeq) } opt[String]("commands").valueName("").text("commands to exercise").action { (v, c) => c.copy(commands = TextMatcher(v, defaultType = Glob)) } opt[File]("scratch-dir").text("Temp-dir for job runs - preferably ramdisk, eg tmpfs.").action { (v, c) => c.copy(scratchDir = v.toPath) } opt[Unit]("only-bfg") action { (_, c) => c.copy(onlyBfg = true) } text "Don't benchmark git-filter-branch" } } case class BenchmarkConfig(resourcesDirOption: Path = Paths.get(System.getProperty("user.dir"), "bfg-benchmark", "resources"), scratchDir: Path = Paths.get("/dev/shm/"), javaCmds: Seq[String] = Seq("java"), bfgVersions: Seq[String] = Seq.empty, commands: TextMatcher = Glob("*"), onlyBfg: Boolean = false, dieIfTaskTakesLongerThan: Option[Int] = None, repoNames: Seq[String] = Seq.empty) { lazy val resourcesDir: Path = resourcesDirOption.toAbsolutePath lazy val jarsDir: Path = resourcesDir.resolve("jars") lazy val reposDir: Path = resourcesDir.resolve("repos") lazy val bfgJars: Seq[Path] = bfgVersions.map(version => jarsDir.resolve(s"bfg-$version.jar")) lazy val repoSpecDirs: Seq[Path] = repoNames.map(reposDir.resolve) } ================================================ FILE: bfg-benchmark/src/main/scala/JavaVersion.scala ================================================ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent._ import scala.sys.process.{Process, ProcessLogger} object JavaVersion { val VersionRegex = """(?:java|openjdk) version "(.*?)"""".r def version(javaCmd: String): Future[String] = { val resultPromise = Promise[String]() Future { val exitCode = Process(s"$javaCmd -version")!ProcessLogger( s => for (v <-versionFrom(s)) resultPromise.success(v) ) resultPromise.tryFailure(new IllegalArgumentException(s"$javaCmd exited with code $exitCode, no Java version found")) } resultPromise.future } def versionFrom(javaVersionLine: String): Option[String] = { VersionRegex.findFirstMatchIn(javaVersionLine).map(_.group(1)) } } ================================================ FILE: bfg-benchmark/src/main/scala/lib/Repo.scala ================================================ package lib import com.google.common.io.MoreFiles import com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE import com.madgag.compress.CompressUtil._ import java.nio.file.{Files, Path} import scala.util.Using class RepoExtractor(scratchDir: Path) { val repoDir = scratchDir.resolve( "repo.git") def extractRepoFrom(zipPath: Path) = { if (Files.exists(repoDir)) MoreFiles.deleteRecursively(repoDir, ALLOW_INSECURE) Files.createDirectories(repoDir) println(s"Extracting repo to ${repoDir.toAbsolutePath}") Using(Files.newInputStream(zipPath)) { stream => unzip(stream, repoDir.toFile) } repoDir } } ================================================ FILE: bfg-benchmark/src/main/scala/lib/Timing.scala ================================================ package lib import java.lang.System._ import java.util.concurrent.TimeUnit._ import scala.concurrent.duration.{Duration, FiniteDuration} object Timing { def measureTask[T](description: String)(block: => T): Duration = { val start = nanoTime val result = block val duration = FiniteDuration(nanoTime - start, NANOSECONDS) println(s"$description completed in %,d ms.".format(duration.toMillis)) duration } } ================================================ FILE: bfg-benchmark/src/main/scala/model/BFGJar.scala ================================================ package model import java.nio.file.Path object BFGJar { def from(path: Path) = BFGJar(path, Map.empty) } case class BFGJar(path: Path, mavenDependencyVersions: Map[String, String]) ================================================ FILE: bfg-benchmark/src/main/scala/model/InvocableEngine.scala ================================================ package model import com.google.common.io.CharSource import com.google.common.io.Files.asCharSource import java.io.File import java.nio.charset.StandardCharsets.UTF_8 import java.nio.file.{Files, Path} import scala.jdk.StreamConverters._ import scala.sys.process.{Process, ProcessBuilder} trait EngineInvocation case class BFGInvocation(args: String) extends EngineInvocation case class GFBInvocation(args: Seq[String]) extends EngineInvocation trait InvocableEngine[InvocationArgs <: EngineInvocation] { def processFor(invocation: InvocationArgs)(repoPath: File): ProcessBuilder } case class InvocableBFG(java: Java, bfgJar: BFGJar) extends InvocableEngine[BFGInvocation] { def processFor(invocation: BFGInvocation)(repoPath: File) = Process(s"${java.javaCmd} -jar ${bfgJar.path} ${invocation.args}", repoPath) } object InvocableGitFilterBranch extends InvocableEngine[GFBInvocation] { def processFor(invocation: GFBInvocation)(repoPath: File) = Process(Seq("git", "filter-branch") ++ invocation.args, repoPath) } /* We want to allow the user to vary: - BFGs (jars, javas) - Tasks (delete a file, replace text) in [selection of repos] Tasks will have a variety of different invocations for different engines */ trait EngineType[InvocationType <: EngineInvocation] { val configName: String def argsFor(config: CharSource): InvocationType def argsOptsFor(commandDir: Path): Option[InvocationType] = { val paramsPath = commandDir.resolve(s"$configName.txt") if (Files.exists(paramsPath)) Some(argsFor(asCharSource(paramsPath.toFile, UTF_8))) else None } } case object BFG extends EngineType[BFGInvocation] { val configName = "bfg" def argsFor(config: CharSource) = BFGInvocation(config.read()) } case object GitFilterBranch extends EngineType[GFBInvocation] { val configName = "gfb" def argsFor(config: CharSource) = GFBInvocation(config.lines().toScala(Seq)) } ================================================ FILE: bfg-benchmark/src/main/scala/model/InvocableEngineSet.scala ================================================ package model import java.io.File import java.nio.file.Path case class InvocableEngineSet[InvocationArgs <: EngineInvocation]( engineType: EngineType[InvocationArgs], invocableEngines: Seq[InvocableEngine[InvocationArgs]] ) { def invocationsFor(commandDir: Path): Seq[(InvocableEngine[InvocationArgs], File => scala.sys.process.ProcessBuilder)] = { for { args <- engineType.argsOptsFor(commandDir).toSeq invocable <- invocableEngines } yield (invocable, invocable.processFor(args) _) } } ================================================ FILE: bfg-benchmark/src/main/scala/model/Java.scala ================================================ package model case class Java(javaCmd: String, version: String) ================================================ FILE: bfg-benchmark/src/test/scala/JavaVersionSpec.scala ================================================ import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers object JavaVersionSpec extends AnyFlatSpec with OptionValues with Matchers { "version" should "parse an example line" in { JavaVersion.versionFrom("""java version "1.7.0_51"""").value shouldBe "1.7.0_51" } it should "parse openjdk weirdness" in { JavaVersion.versionFrom("""openjdk version "1.8.0_40-internal"""").value shouldBe "1.8.0_40-internal" } } ================================================ FILE: bfg-library/build.sbt ================================================ import Dependencies.* libraryDependencies ++= guava ++ Seq( parCollections, scalaCollectionPlus, textmatching, scalaGit, jgit, slf4jSimple, lineSplitting, scalaGitTest % Test, "org.apache.commons" % "commons-text" % "1.13.0" % Test ) ================================================ FILE: bfg-library/src/main/scala/com/madgag/collection/concurrent/ConcurrentMultiMap.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.collection.concurrent import com.madgag.scala.collection.decorators._ class ConcurrentMultiMap[A, B] { val m: collection.concurrent.Map[A, ConcurrentSet[B]] = collection.concurrent.TrieMap.empty def addBinding(key: A, value: B): this.type = { val store = m.getOrElse(key, { val freshStore = new ConcurrentSet[B] m.putIfAbsent(key, freshStore).getOrElse(freshStore) }) store += value this } def toMap: Map[A, Set[B]] = m.toMap.mapV(_.toSet) } ================================================ FILE: bfg-library/src/main/scala/com/madgag/collection/concurrent/ConcurrentSet.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.collection.concurrent import scala.collection.mutable.{AbstractSet, SetOps} import scala.collection.{IterableFactory, IterableFactoryDefaults, mutable} class ConcurrentSet[A]() extends AbstractSet[A] with SetOps[A, ConcurrentSet, ConcurrentSet[A]] with IterableFactoryDefaults[A, ConcurrentSet] { val m: collection.concurrent.Map[A, Boolean] = collection.concurrent.TrieMap.empty override def iterableFactory: IterableFactory[ConcurrentSet] = ConcurrentSet override def clear(): Unit = m.clear() override def addOne(elem: A): ConcurrentSet.this.type = { m.put(elem, true) this } override def subtractOne(elem: A): ConcurrentSet.this.type = { m.remove(elem) this } override def contains(elem: A): Boolean = m.contains(elem) override def iterator: Iterator[A] = m.keysIterator } object ConcurrentSet extends IterableFactory[ConcurrentSet] { @transient private final val EmptySet = new ConcurrentSet() def empty[A]: ConcurrentSet[A] = EmptySet.asInstanceOf[ConcurrentSet[A]] def from[A](source: collection.IterableOnce[A]): ConcurrentSet[A] = source match { case hs: ConcurrentSet[A] => hs case _ if source.knownSize == 0 => empty[A] case _ => (newBuilder[A] ++= source).result() } /** Create a new Builder which can be reused after calling `result()` without an * intermediate call to `clear()` in order to build multiple related results. */ def newBuilder[A]: mutable.Builder[A, ConcurrentSet[A]] = ??? } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/LFS.scala ================================================ /* * Copyright (c) 2015 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git import com.google.common.base.Splitter import com.madgag.git.bfg.model.FileName import org.apache.commons.codec.binary.Hex._ import org.eclipse.jgit.lib.ObjectLoader import java.nio.charset.Charset import java.nio.charset.StandardCharsets.UTF_8 import java.nio.file.{Files, Path} import java.security.{DigestOutputStream, MessageDigest} import scala.jdk.CollectionConverters._ import scala.util.Using object LFS { val ObjectsPath: Seq[String] = Seq("lfs" , "objects") val PointerCharset: Charset = UTF_8 case class Pointer(shaHex: String, blobSize: Long) { lazy val text: String = s"""|version https://git-lfs.github.com/spec/v1 |oid sha256:$shaHex |size $blobSize |""".stripMargin lazy val bytes: Array[Byte] = text.getBytes(PointerCharset) lazy val path: Seq[String] = Seq(shaHex.substring(0, 2), shaHex.substring(2, 4), shaHex) } object Pointer { val splitter = Splitter.on('\n').omitEmptyStrings().trimResults().withKeyValueSeparator(' ') def parse(bytes: Array[Byte]) = { val text = new String(bytes, PointerCharset) val valuesByKey= splitter.split(text).asScala val size = valuesByKey("size").toLong val shaHex = valuesByKey("oid").stripPrefix("sha256:") Pointer(shaHex, size) } } val GitAttributesFileName = FileName(".gitattributes") def pointerFor(loader: ObjectLoader, tmpFile: Path) = { val digest = MessageDigest.getInstance("SHA-256") Using(Files.newOutputStream(tmpFile)) { outStream => loader.copyTo(new DigestOutputStream(outStream, digest)) } Pointer(encodeHexString(digest.digest()), loader.getSize) } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/GitUtil.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg import com.google.common.primitives.Ints import com.madgag.git.bfg.cleaner._ import com.madgag.git.{SizedObject, _} import org.eclipse.jgit.internal.storage.file.ObjectDirectory import org.eclipse.jgit.lib.Constants.OBJ_BLOB import org.eclipse.jgit.lib.ObjectReader._ import org.eclipse.jgit.lib._ import org.eclipse.jgit.revwalk.RevWalk import org.eclipse.jgit.storage.file.WindowCacheConfig import scala.jdk.CollectionConverters._ import scala.jdk.StreamConverters._ import scala.language.implicitConversions trait CleaningMapper[V] extends Cleaner[V] { def isDirty(v: V) = apply(v) != v def substitution(oldId: V): Option[(V, V)] = { val newId = apply(oldId) if (newId == oldId) None else Some((oldId, newId)) } def replacement(oldId: V): Option[V] = { val newId = apply(oldId) if (newId == oldId) None else Some(newId) } } object GitUtil { val ProbablyNoNonFileObjectsOverSizeThreshold: Long = 1024 * 1024 def tweakStaticJGitConfig(massiveNonFileObjects: Option[Long]): Unit = { val wcConfig: WindowCacheConfig = new WindowCacheConfig() wcConfig.setStreamFileThreshold(Ints.saturatedCast(massiveNonFileObjects.getOrElse(ProbablyNoNonFileObjectsOverSizeThreshold))) wcConfig.install() } def hasBeenProcessedByBFGBefore(repo: Repository): Boolean = { // This method just checks the tips of all refs - a good-enough indicator for our purposes... implicit val revWalk = new RevWalk(repo) implicit val objectReader = revWalk.getObjectReader repo.getRefDatabase.getRefs().asScala.map(_.getObjectId).filter(_.open.getType == Constants.OBJ_COMMIT) .map(_.asRevCommit).exists(_.getFooterLines(FormerCommitFooter.Key).asScala.nonEmpty) } implicit def cleaner2CleaningMapper[V](f: Cleaner[V]): CleaningMapper[V] = new CleaningMapper[V] { def apply(v: V) = f(v) } def biggestBlobs(implicit objectDB: ObjectDirectory, progressMonitor: ProgressMonitor = NullProgressMonitor.INSTANCE): LazyList[SizedObject] = { Timing.measureTask("Scanning packfile for large blobs", ProgressMonitor.UNKNOWN) { val reader = objectDB.newReader objectDB.packedObjects.map { objectId => progressMonitor update 1 SizedObject(objectId, reader.getObjectSize(objectId, OBJ_ANY)) }.toSeq.sorted.reverse.to(LazyList).filter { oid => oid.size > ProbablyNoNonFileObjectsOverSizeThreshold || reader.open(oid.objectId).getType == OBJ_BLOB } } } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/BlobCharsetDetector.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.google.common.io.ByteStreams import com.google.common.io.ByteStreams.toByteArray import com.madgag.git.bfg.model.TreeBlobEntry import org.eclipse.jgit.diff.RawText import org.eclipse.jgit.lib.ObjectLoader import java.nio.ByteBuffer import java.nio.charset.Charset import java.nio.charset.CodingErrorAction._ import scala.util.{Try, Using} trait BlobCharsetDetector { // should return None if this is a binary file that can not be converted to text def charsetFor(entry: TreeBlobEntry, objectLoader: ObjectLoader): Option[Charset] } object QuickBlobCharsetDetector extends BlobCharsetDetector { val CharSets: Seq[Charset] = Seq(Charset.forName("UTF-8"), Charset.defaultCharset(), Charset.forName("ISO-8859-1")).distinct def charsetFor(entry: TreeBlobEntry, objectLoader: ObjectLoader): Option[Charset] = { Using(ByteStreams.limit(objectLoader.openStream(), 8000))(toByteArray).toOption.filterNot(RawText.isBinary).flatMap { sampleBytes => val b = ByteBuffer.wrap(sampleBytes) CharSets.find(cs => Try(decode(b, cs)).isSuccess) } } private def decode(b: ByteBuffer, charset: Charset): Unit = { charset.newDecoder.onMalformedInput(REPORT).onUnmappableCharacter(REPORT).decode(b) } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/BlobTextModifier.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.madgag.git.ThreadLocalObjectDatabaseResources import com.madgag.git.bfg.model.TreeBlobEntry import com.madgag.linesplitting.LineBreakPreservingIterator import org.eclipse.jgit.lib.Constants.OBJ_BLOB import org.eclipse.jgit.lib.ObjectLoader import java.io.{ByteArrayOutputStream, InputStreamReader} import java.nio.charset.Charset object BlobTextModifier { val DefaultSizeThreshold: Long = 1024 * 1024 } trait BlobTextModifier extends TreeBlobModifier { val threadLocalObjectDBResources: ThreadLocalObjectDatabaseResources def lineCleanerFor(entry: TreeBlobEntry): Option[String => String] val charsetDetector: BlobCharsetDetector = QuickBlobCharsetDetector val sizeThreshold = BlobTextModifier.DefaultSizeThreshold override def fix(entry: TreeBlobEntry) = { def filterTextIn(e: TreeBlobEntry, lineCleaner: String => String): TreeBlobEntry = { def isDirty(line: String) = lineCleaner(line) != line val loader = threadLocalObjectDBResources.reader().open(e.objectId) val opt = for { charset <- charsetDetector.charsetFor(e, loader) if loader.getSize < sizeThreshold && linesFor(loader, charset).exists(isDirty) } yield { val b = new ByteArrayOutputStream(loader.getSize.toInt) linesFor(loader, charset).map(lineCleaner).foreach(line => b.write(line.getBytes(charset))) val oid = threadLocalObjectDBResources.inserter().insert(OBJ_BLOB, b.toByteArray) e.copy(objectId = oid) } opt.getOrElse(e) } lineCleanerFor(entry) match { case Some(lineCleaner) => filterTextIn(entry, lineCleaner).withoutName case None => entry.withoutName } } private def linesFor(loader: ObjectLoader, charset: Charset): Iterator[String] = { new LineBreakPreservingIterator(new InputStreamReader(loader.openStream(), charset)) } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/LfsBlobConverter.scala ================================================ /* * Copyright (c) 2015 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.google.common.io.ByteSource import com.google.common.io.Files.createParentDirs import com.madgag.git.LFS._ import com.madgag.git._ import com.madgag.git.bfg.model._ import com.madgag.git.bfg.{MemoFunc, MemoUtil} import com.madgag.textmatching.{Glob, TextMatcher} import org.eclipse.jgit.internal.storage.file.FileRepository import org.eclipse.jgit.lib.{ObjectId, ObjectReader} import java.nio.charset.{Charset, StandardCharsets} import java.nio.file.{Files, Path} import scala.jdk.StreamConverters._ import scala.util.{Try, Using} class LfsBlobConverter( lfsGlobExpression: String, repo: FileRepository ) extends TreeBlobModifier { val lfsObjectsDir: Path = repo.getDirectory.toPath.resolve(LFS.ObjectsPath) val threadLocalObjectDBResources = repo.getObjectDatabase.threadLocalResources val lfsGlob = TextMatcher(Glob, lfsGlobExpression) val lfsSuitableFiles: (FileName => Boolean) = f => lfsGlob(f.string) val gitAttributesLine = s"$lfsGlobExpression filter=lfs diff=lfs merge=lfs -text" implicit val UTF_8: Charset = StandardCharsets.UTF_8 val lfsPointerMemo = MemoUtil.concurrentCleanerMemo[ObjectId]() override def apply(dirtyBlobs: TreeBlobs) = { val cleanedBlobs = super.apply(dirtyBlobs) if (cleanedBlobs == dirtyBlobs) cleanedBlobs else ensureGitAttributesSetFor(cleanedBlobs) } def ensureGitAttributesSetFor(cleanedBlobs: TreeBlobs): TreeBlobs = { implicit lazy val inserter = threadLocalObjectDBResources.inserter() val newGitAttributesId = cleanedBlobs.entryMap.get(GitAttributesFileName).fold { storeBlob(gitAttributesLine) } { case (_, oldGitAttributesId) => val objectLoader = threadLocalObjectDBResources.reader().open(oldGitAttributesId) Using(ByteSource.wrap(objectLoader.getCachedBytes).asCharSource(UTF_8).lines()) { oldAttributesStream => val oldAttributes = oldAttributesStream.toScala(Seq) if (oldAttributes.contains(gitAttributesLine)) oldGitAttributesId else { storeBlob((oldAttributes :+ gitAttributesLine).mkString("\n")) } }.get } cleanedBlobs.copy(entryMap = cleanedBlobs.entryMap + (GitAttributesFileName -> (RegularFile, newGitAttributesId))) } override def fix(entry: TreeBlobEntry) = { val cleanId = if (lfsSuitableFiles(entry.filename)) lfsPointerBlobIdForRealBlob(entry.objectId) else entry.objectId (entry.mode, cleanId) } val lfsPointerBlobIdForRealBlob: MemoFunc[ObjectId, ObjectId] = lfsPointerMemo { blobId: ObjectId => implicit val reader = threadLocalObjectDBResources.reader() implicit lazy val inserter = threadLocalObjectDBResources.inserter() (for { blobSize <- blobId.sizeTry if blobSize > 512 pointer <- tryStoringLfsFileFor(blobId) } yield storeBlob(pointer.bytes)).getOrElse(blobId) } def tryStoringLfsFileFor(blobId: ObjectId)(implicit r: ObjectReader): Try[Pointer] = { val loader = blobId.open val tmpFile: Path = Files.createTempFile(s"bfg.git-lfs.conv-${blobId.name}","dat") val pointer = pointerFor(loader, tmpFile) val lfsPath = lfsObjectsDir.resolve(pointer.path) createParentDirs(lfsPath.toFile) val ensureLfsFile = Try(if (!Files.exists(lfsPath)) Files.move(tmpFile, lfsPath)).recover { case _ if Files.exists(lfsPath) && Files.size(lfsPath) == loader.getSize => } Try(Files.deleteIfExists(tmpFile)) ensureLfsFile.map(_ => pointer) } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/ObjectIdCleaner.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.madgag.collection.concurrent.ConcurrentMultiMap import com.madgag.git._ import com.madgag.git.bfg.GitUtil._ import com.madgag.git.bfg.cleaner.protection.{ProtectedObjectCensus, ProtectedObjectDirtReport} import com.madgag.git.bfg.model.{Tree, TreeSubtrees, _} import com.madgag.git.bfg.{CleaningMapper, Memo, MemoFunc, MemoUtil} import org.eclipse.jgit.lib.Constants._ import org.eclipse.jgit.lib._ import org.eclipse.jgit.revwalk.{RevCommit, RevTag, RevWalk} object ObjectIdCleaner { case class Config(protectedObjectCensus: ProtectedObjectCensus, objectIdSubstitutor: ObjectIdSubstitutor = ObjectIdSubstitutor.OldIdsPublic, commitNodeCleaners: Seq[CommitNodeCleaner] = Seq.empty, treeEntryListCleaners: Seq[Cleaner[Seq[Tree.Entry]]] = Seq.empty, treeBlobsCleaners: Seq[Cleaner[TreeBlobs]] = Seq.empty, treeSubtreesCleaners: Seq[Cleaner[TreeSubtrees]] = Seq.empty, // messageCleaners? - covers both Tag and Commits objectChecker: Option[ObjectChecker] = None) { lazy val commitNodeCleaner = CommitNodeCleaner.chain(commitNodeCleaners) lazy val treeEntryListCleaner = Function.chain(treeEntryListCleaners) lazy val treeBlobsCleaner = Function.chain(treeBlobsCleaners) lazy val treeSubtreesCleaner:Cleaner[TreeSubtrees] = Function.chain(treeSubtreesCleaners) } } /* * Knows how to clean an object, and what objects are protected... */ class ObjectIdCleaner(config: ObjectIdCleaner.Config, objectDB: ObjectDatabase, implicit val revWalk: RevWalk) extends CleaningMapper[ObjectId] { import config._ val threadLocalResources = objectDB.threadLocalResources val changesByFilename = new ConcurrentMultiMap[FileName, (ObjectId, ObjectId)] val deletionsByFilename = new ConcurrentMultiMap[FileName, ObjectId] // want to enforce that once any value is returned, it is 'good' and therefore an identity-mapped key as well val memo: Memo[ObjectId, ObjectId] = MemoUtil.concurrentCleanerMemo(protectedObjectCensus.fixedObjectIds) val commitMemo: Memo[ObjectId, ObjectId] = MemoUtil.concurrentCleanerMemo() val tagMemo: Memo[ObjectId, ObjectId] = MemoUtil.concurrentCleanerMemo() val treeMemo: Memo[ObjectId, ObjectId] = MemoUtil.concurrentCleanerMemo(protectedObjectCensus.treeIds.toSet[ObjectId]) def apply(objectId: ObjectId): ObjectId = memoClean(objectId) val memoClean = memo { uncachedClean } def cleanedObjectMap(): Map[ObjectId, ObjectId] = Seq(memoClean, cleanCommit, cleanTag, cleanTree).map(_.asMap()).reduce(_ ++ _) def uncachedClean: (ObjectId) => ObjectId = { objectId => threadLocalResources.reader().open(objectId).getType match { case OBJ_COMMIT => cleanCommit(objectId) case OBJ_TREE => cleanTree(objectId) case OBJ_TAG => cleanTag(objectId) case _ => objectId // we don't currently clean isolated blobs... only clean within a tree context } } def getCommit(commitId: AnyObjectId): RevCommit = revWalk synchronized (commitId asRevCommit) def getTag(tagId: AnyObjectId): RevTag = revWalk synchronized (tagId asRevTag) val cleanCommit: MemoFunc[ObjectId, ObjectId] = commitMemo { commitId => val originalRevCommit = getCommit(commitId) val originalCommit = Commit(originalRevCommit) val cleanedArcs = originalCommit.arcs cleanWith this val kit = new CommitNodeCleaner.Kit(threadLocalResources, originalRevCommit, originalCommit, cleanedArcs, apply) val updatedCommitNode = commitNodeCleaner.fixer(kit)(originalCommit.node) val updatedCommit = Commit(updatedCommitNode, cleanedArcs) if (updatedCommit != originalCommit) { val commitBytes = updatedCommit.toBytes objectChecker.foreach(_.checkCommit(commitBytes)) threadLocalResources.inserter().insert(OBJ_COMMIT, commitBytes) } else { originalRevCommit } } val cleanBlob: Cleaner[ObjectId] = identity // Currently a NO-OP, we only clean at treeblob level val cleanTree: MemoFunc[ObjectId, ObjectId] = treeMemo { originalObjectId => val entries = Tree.entriesFor(originalObjectId)(threadLocalResources.reader()) val cleanedTreeEntries = treeEntryListCleaner(entries) val tree = Tree(cleanedTreeEntries) val originalBlobs = tree.blobs val fixedTreeBlobs = treeBlobsCleaner(originalBlobs) val cleanedSubtrees = TreeSubtrees(treeSubtreesCleaner(tree.subtrees).entryMap.map { case (name, treeId) => (name, cleanTree(treeId)) }).withoutEmptyTrees val treeBlobsChanged = fixedTreeBlobs != originalBlobs if (entries == cleanedTreeEntries && !treeBlobsChanged && cleanedSubtrees == tree.subtrees) originalObjectId else { if (treeBlobsChanged) recordChange(originalBlobs, fixedTreeBlobs) val updatedTree = tree copyWith(cleanedSubtrees, fixedTreeBlobs) val treeFormatter = updatedTree.formatter objectChecker.foreach(_.checkTree(treeFormatter.toByteArray)) treeFormatter.insertTo(threadLocalResources.inserter()) } } def recordChange(originalBlobs: TreeBlobs, fixedTreeBlobs: TreeBlobs): Unit = { val changedFiles: Set[TreeBlobEntry] = originalBlobs.entries.toSet -- fixedTreeBlobs.entries.toSet for (TreeBlobEntry(filename, _, oldId) <- changedFiles) { fixedTreeBlobs.objectId(filename) match { case Some(newId) => changesByFilename.addBinding(filename, (oldId, newId)) case None => deletionsByFilename.addBinding(filename, oldId) } } } case class TreeBlobChange(oldId: ObjectId, newIdOpt: Option[ObjectId], filename: FileName) val cleanTag: MemoFunc[ObjectId, ObjectId] = tagMemo { id => val originalTag = getTag(id) replacement(originalTag.getObject).map { cleanedObj => val tb = new TagBuilder tb.setTag(originalTag.getTagName) tb.setObjectId(cleanedObj, originalTag.getObject.getType) tb.setTagger(originalTag.getTaggerIdent) tb.setMessage(objectIdSubstitutor.replaceOldIds(originalTag.getFullMessage, threadLocalResources.reader(), apply)) val cleanedTag: ObjectId = threadLocalResources.inserter().insert(tb) objectChecker.foreach(_.checkTag(tb.build())) cleanedTag }.getOrElse(originalTag) } lazy val protectedDirt: Seq[ProtectedObjectDirtReport] = { protectedObjectCensus.protectorRevsByObject.map { case (protectedRevObj, refNames) => val originalContentObject = treeOrBlobPointedToBy(protectedRevObj).merge val replacementTreeOrBlob = uncachedClean.replacement(originalContentObject) ProtectedObjectDirtReport(protectedRevObj, originalContentObject, replacementTreeOrBlob) }.toList } def stats() = Map("apply"->memoClean.stats(), "tree" -> cleanTree.stats(), "commit" -> cleanCommit.stats(), "tag" -> cleanTag.stats()) } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/ObjectIdSubstitutor.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.madgag.git._ import com.madgag.git.bfg.GitUtil._ import com.madgag.git.bfg.cleaner.ObjectIdSubstitutor._ import org.eclipse.jgit.lib.{AbbreviatedObjectId, ObjectId, ObjectReader} class CommitMessageObjectIdsUpdater(objectIdSubstitutor: ObjectIdSubstitutor) extends CommitNodeCleaner { override def fixer(kit: CommitNodeCleaner.Kit) = commitNode => commitNode.copy(message = objectIdSubstitutor.replaceOldIds(commitNode.message, kit.threadLocalResources.reader(), kit.mapper)) } object ObjectIdSubstitutor { object OldIdsPrivate extends ObjectIdSubstitutor { def format(oldIdText: String, newIdText: String) = newIdText } object OldIdsPublic extends ObjectIdSubstitutor { def format(oldIdText: String, newIdText: String) = s"$newIdText [formerly $oldIdText]" } val hexRegex = """\b\p{XDigit}{10,40}\b""".r // choose minimum size based on size of project?? } trait ObjectIdSubstitutor { def format(oldIdText: String, newIdText: String): String // slow! def replaceOldIds(message: String, reader: ObjectReader, mapper: Cleaner[ObjectId]): String = { val substitutionOpts = for { m: String <- hexRegex.findAllIn(message).toSet objectId <- reader.resolveExistingUniqueId(AbbreviatedObjectId.fromString(m)).toOption } yield mapper.replacement(objectId).map(newId => m -> format(m, reader.abbreviate(newId, m.length).name)) val substitutions = substitutionOpts.flatten.toMap if (substitutions.isEmpty) message else hexRegex.replaceSomeIn(message, m => substitutions.get(m.matched)) } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/RepoRewriter.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.madgag.git._ import com.madgag.git.bfg.Timing import org.eclipse.jgit.lib.{ObjectId, ProgressMonitor, RefDatabase} import org.eclipse.jgit.revwalk.RevSort._ import org.eclipse.jgit.revwalk.{RevCommit, RevWalk} import org.eclipse.jgit.transport.ReceiveCommand import scala.jdk.CollectionConverters._ import scala.collection.parallel.CollectionConverters._ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future /* Encountering a blob -> BIG-BLOB-DELETION : Either 'good' or 'delete' - or possibly replace, with a different filename (means tree-level) PASSWORD-REMOVAL : Either 'good' or 'replace' Encountering a tree -> BIG-BLOB-DELETION : Either 'good' or 'replace' - possibly adding with a different placeholder blob entry PASSWORD-REMOVAL : Either 'good' or 'replace' - replacing one blob entry with another So if we encounter a tree, we are unlikely to want to remove that tree entirely... SHOULD WE JUST DISALLOW THAT? Obviously, a Commit HAS to have a tree, so it's dangerous to allow a None response to tree transformation An objectId must be either GOOD or BAD, and we must never translate *either* kind of id into a BAD User-customisation interface: TreeBlobs => TreeBlobs User gets no say in adding, renaming, removing directories TWO MAIN USE CASES FOR HISTORY-CHANGING ARE: 1: GETTING RID OF BIG BLOBS 2: REMOVING PASSWORDS IN HISTORICAL FILES possible other use-case: fixing committer names - and possibly removing passwords from commits? (could possibly just be done with rebase) Why else would you want to rewrite HISTORY? Many other changes (ie putting a directory one down) need only be applied in a new commit, we don't care about history. When updating a Tree, the User has no right to muck with sub-trees. They can only alter the blob contents. */ object RepoRewriter { def rewrite(repo: org.eclipse.jgit.lib.Repository, objectIdCleanerConfig: ObjectIdCleaner.Config): Map[ObjectId, ObjectId] = { implicit val refDatabase: RefDatabase = repo.getRefDatabase assert(refDatabase.hasRefs, "Can't find any refs in repo at " + repo.getDirectory.getAbsolutePath) val reporter: Reporter = new CLIReporter(repo) implicit val progressMonitor: ProgressMonitor = reporter.progressMonitor val allRefs = refDatabase.getRefs().asScala def createRevWalk: RevWalk = { val revWalk = new RevWalk(repo) revWalk.sort(TOPO) // crucial to ensure we visit parents BEFORE children, otherwise blow stack revWalk.sort(REVERSE, true) // we want to start with the earliest commits and work our way up... val startCommits = allRefs.map(_.targetObjectId.asRevObject(revWalk)).collect { case c: RevCommit => c } revWalk.markStart(startCommits.asJavaCollection) revWalk } implicit val revWalk = createRevWalk implicit val reader = revWalk.getObjectReader reporter.reportRefsForScan(allRefs) reporter.reportObjectProtection(objectIdCleanerConfig)(repo.getObjectDatabase, revWalk) val objectIdCleaner = new ObjectIdCleaner(objectIdCleanerConfig, repo.getObjectDatabase, revWalk) val commits = revWalk.asScala.toSeq def clean(commits: Seq[RevCommit]): Unit = { reporter.reportCleaningStart(commits) Timing.measureTask("Cleaning commits", commits.size) { Future { commits.par.foreach { commit => objectIdCleaner(commit.getTree) } } commits.foreach { commit => objectIdCleaner(commit) progressMonitor update 1 } } } def updateRefsWithCleanedIds(): Unit = { val refUpdateCommands = for (ref <- repo.nonSymbolicRefs; (oldId, newId) <- objectIdCleaner.substitution(ref.getObjectId) ) yield new ReceiveCommand(oldId, newId, ref.getName) if (refUpdateCommands.isEmpty) { println("\nBFG aborting: No refs to update - no dirty commits found??\n") } else { reporter.reportRefUpdateStart(refUpdateCommands) Timing.measureTask("...Ref update", refUpdateCommands.size) { // Hack a fix for issue #23 : Short-cut the calculation that determines an update is NON-FF val quickMergeCalcRevWalk = new RevWalk(revWalk.getObjectReader) { override def isMergedInto(base: RevCommit, tip: RevCommit) = if (tip == objectIdCleaner(base)) false else super.isMergedInto(base, tip) } refDatabase.newBatchUpdate.setAllowNonFastForwards(true).addCommand(refUpdateCommands.asJavaCollection) .execute(quickMergeCalcRevWalk, progressMonitor) } reporter.reportResults(commits, objectIdCleaner) } } clean(commits) updateRefsWithCleanedIds() objectIdCleaner.stats() objectIdCleaner.cleanedObjectMap() } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/Reporter.scala ================================================ package com.madgag.git.bfg.cleaner import com.google.common.io.Files.asCharSink import com.madgag.collection.concurrent.ConcurrentMultiMap import com.madgag.git._ import com.madgag.git.bfg.cleaner.Reporter.dump import com.madgag.git.bfg.cleaner.protection.{ProtectedObjectCensus, ProtectedObjectDirtReport} import com.madgag.git.bfg.model.FileName import com.madgag.text.Text._ import com.madgag.text.{ByteSize, Tables, Text} import org.eclipse.jgit.diff.DiffEntry.ChangeType._ import org.eclipse.jgit.diff._ import org.eclipse.jgit.lib.FileMode._ import org.eclipse.jgit.lib._ import org.eclipse.jgit.revwalk.{RevCommit, RevWalk} import org.eclipse.jgit.transport.ReceiveCommand import java.nio.charset.StandardCharsets.UTF_8 import java.nio.file.Files.createDirectories import java.nio.file.Path import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import scala.collection.immutable.SortedMap import scala.jdk.CollectionConverters._ object Reporter { def dump(path: Path, iter: Iterable[String]): Unit = { val sink = asCharSink(path.toFile, UTF_8) sink.writeLines(iter.asJava, "\n") } } trait Reporter { val progressMonitor: ProgressMonitor def reportRefsForScan(allRefs: Iterable[Ref])(implicit objReader: ObjectReader): Unit def reportRefUpdateStart(refUpdateCommands: Iterable[ReceiveCommand]): Unit def reportObjectProtection(objectIdCleanerConfig: ObjectIdCleaner.Config)(implicit objectDB: ObjectDatabase, revWalk: RevWalk): Unit def reportCleaningStart(commits: Seq[RevCommit]): Unit def reportResults(commits: Seq[RevCommit], objectIdCleaner: ObjectIdCleaner): Unit } class CLIReporter(repo: Repository) extends Reporter { lazy val reportsDir: Path = { val now = ZonedDateTime.now() val topDirPath = repo.topDirectory.toPath.toAbsolutePath val reportsDir = topDirPath.resolveSibling(s"${topDirPath.getFileName}.bfg-report") val dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd") val timeFormatter = DateTimeFormatter.ofPattern("HH-mm-ss") val dir = reportsDir.resolve(now.format(dateFormatter)).resolve(now.format(timeFormatter)) createDirectories(dir) dir } lazy val progressMonitor = new TextProgressMonitor def reportRefUpdateStart(refUpdateCommands: Iterable[ReceiveCommand]): Unit = { println(title("Updating " + plural(refUpdateCommands, "Ref"))) val summaryTableCells = refUpdateCommands.map(update => (update.getRefName, update.getOldId.shortName, update.getNewId.shortName)) Tables.formatTable(("Ref", "Before", "After"), summaryTableCells.toSeq).map("\t" + _).foreach(println) println() } def reportRefsForScan(allRefs: Iterable[Ref])(implicit objReader: ObjectReader): Unit = { val refsByObjType = allRefs.groupBy { ref => objReader.open(ref.getObjectId).getType } withDefault Seq.empty refsByObjType.foreach { case (typ, refs) => println("Found " + refs.size + " " + Constants.typeString(typ) + "-pointing refs : " + abbreviate(refs.map(_.getName).toSeq, "...", 4).mkString(", ")) } } // abort due to Dirty Tips on Private run - user needs to manually clean // warn due to Dirty Tips on Public run - it's not so serious if users publicise dirty tips. // if no protection def reportObjectProtection(objectIdCleanerConfig: ObjectIdCleaner.Config)(implicit objectDB: ObjectDatabase, revWalk: RevWalk): Unit = { println(title("Protected commits")) if (objectIdCleanerConfig.protectedObjectCensus.isEmpty) { println("You're not protecting any commits, which means the BFG will modify the contents of even *current* commits.\n\n" + "This isn't recommended - ideally, if your current commits are dirty, you should fix up your working copy and " + "commit that, check that your build still works, and only then run the BFG to clean up your history.") } else { println("These are your protected commits, and so their contents will NOT be altered:\n") val unprotectedConfig = objectIdCleanerConfig.copy(protectedObjectCensus = ProtectedObjectCensus.None) reportProtectedCommitsAndTheirDirt(objectIdCleanerConfig) } } case class DiffSideDetails(id: ObjectId, path: String, mode: FileMode, size: Option[Long]) def reportProtectedCommitsAndTheirDirt(objectIdCleanerConfig: ObjectIdCleaner.Config)(implicit objectDB: ObjectDatabase, revWalk: RevWalk): Unit = { implicit val reader = revWalk.getObjectReader def diffDetails(d: DiffEntry) = { val side = DiffEntry.Side.OLD val id: ObjectId = d.getId(side).toObjectId DiffSideDetails(id, d.getPath(side), d.getMode(side), id.sizeOpt) } def fileInfo(d: DiffSideDetails) = { val extraInfo = (d.mode match { case GITLINK => Some("submodule") case _ => d.size.map(ByteSize.format(_)) }).map(e => s"($e)") (d.path +: extraInfo.toSeq).mkString(" ") } val protectedDirtDir = reportsDir.resolve("protected-dirt") createDirectories(protectedDirtDir) val reports = ProtectedObjectDirtReport.reportsFor(objectIdCleanerConfig, objectDB) reports.foreach { report => val protectorRevs = objectIdCleanerConfig.protectedObjectCensus.protectorRevsByObject(report.revObject) val objectTitle = s" * ${report.revObject.typeString} ${report.revObject.shortName} (protected by '${protectorRevs.mkString("', '")}')" report.dirt match { case None => println(objectTitle) case Some(diffEntries) => if (diffEntries.isEmpty) { println(objectTitle + " - dirty") } else { println(objectTitle + " - contains " + plural(diffEntries, "dirty file") + " : ") abbreviate(diffEntries.view.map(diffDetails).map(fileInfo), "...").foreach { dirtyFile => println("\t- " + dirtyFile) } val protectorRefsFileNameSafe: String = protectorRevs.mkString("_").replace( protectedDirtDir.getFileSystem.getSeparator, "-" ) val diffFile = protectedDirtDir.resolve(s"${report.revObject.shortName}-$protectorRefsFileNameSafe.csv") dump(diffFile, diffEntries.map { diffEntry => val de = diffDetails(diffEntry) val modifiedLines = if (diffEntry.getChangeType == MODIFY) diffEntry.editList.map(changedLinesFor) else None val elems = Seq(de.id.name, diffEntry.getChangeType.name, de.mode.name, de.path, de.size.getOrElse(""), modifiedLines.getOrElse("")) elems.mkString(",") }) } } } val dirtyReports = reports.filter(_.objectProtectsDirt) if (dirtyReports.nonEmpty) { println(s""" |WARNING: The dirty content above may be removed from other commits, but as |the *protected* commits still use it, it will STILL exist in your repository. | |Details of protected dirty content have been recorded here : | |${protectedDirtDir.toAbsolutePath.toString + protectedDirtDir.getFileSystem.getSeparator} | |If you *really* want this content gone, make a manual commit that removes it, |and then run the BFG on a fresh copy of your repo. """.stripMargin) // TODO would like to abort here if we are cleaning 'private' data. } } def changedLinesFor(edits: EditList): String = { edits.asScala.map { edit => Seq(edit.getBeginA + 1, edit.getEndA).distinct.mkString("-") }.mkString(";") } def reportCleaningStart(commits: Seq[RevCommit]): Unit = { println(title("Cleaning")) println("Found " + commits.size + " commits") } def reportResults(commits: Seq[RevCommit], objectIdCleaner: ObjectIdCleaner): Unit = { def reportTreeDirtHistory(): Unit = { val dirtHistoryElements = math.max(20, math.min(60, commits.size)) def cut[A](xs: Seq[A], n: Int) = { val avgSize = xs.size.toFloat / n def startOf(unit: Int): Int = math.round(unit * avgSize) (0 until n).view.map(u => xs.slice(startOf(u), startOf(u + 1))) } val treeDirtHistory = cut(commits, dirtHistoryElements).map { case commits if commits.isEmpty => ' ' case commits if (commits.exists(c => objectIdCleaner.isDirty(c.getTree))) => 'D' case commits if (commits.exists(objectIdCleaner.isDirty)) => 'm' case _ => '.' }.mkString def leftRight(markers: Seq[String]) = markers.mkString(" " * (treeDirtHistory.length - markers.map(_.size).sum)) println(title("Commit Tree-Dirt History")) println("\t" + leftRight(Seq("Earliest", "Latest"))) println("\t" + leftRight(Seq("|", "|"))) println("\t" + treeDirtHistory) println("\n\tD = dirty commits (file tree fixed)") println("\tm = modified commits (commit message or parents changed)") println("\t. = clean commits (no changes to file tree)\n") val firstModifiedCommit = commits.find(objectIdCleaner.isDirty).map(_ -> "First modified commit") val lastDirtyCommit = commits.reverse.find(c => objectIdCleaner.isDirty(c.getTree)).map(_ -> "Last dirty commit") val items = for { (commit, desc) <- firstModifiedCommit ++ lastDirtyCommit (before, after) <- objectIdCleaner.substitution(commit) } yield (desc, before.shortName, after.shortName) Tables.formatTable(("", "Before", "After"), items.toSeq).map("\t" + _).foreach(println) } reportTreeDirtHistory() lazy val mapFile: Path = reportsDir.resolve("object-id-map.old-new.txt") lazy val cacheStatsFile: Path = reportsDir.resolve("cache-stats.txt") val changedIds = objectIdCleaner.cleanedObjectMap() def reportFiles[FI]( fileData: ConcurrentMultiMap[FileName, FI], actionType: String, tableTitles: Product )(f: ((FileName,Set[FI])) => Product)(fi: FI => Seq[String]): Unit = { implicit val fileNameOrdering = Ordering[String].on[FileName](_.string) val dataByFilename = SortedMap[FileName, Set[FI]](fileData.toMap.toSeq: _*) if (dataByFilename.nonEmpty) { println(title(s"$actionType files")) Tables.formatTable(tableTitles, dataByFilename.map(f).toSeq).map("\t" + _).foreach(println) val actionFile = reportsDir.resolve(s"${actionType.toLowerCase}-files.txt") dump(actionFile, dataByFilename.flatMap { case (filename, changes) => changes.map(fi.andThen(fid => (fid :+ filename).mkString(" "))) }) } } reportFiles(objectIdCleaner.changesByFilename, "Changed", ("Filename", "Before & After")) { case (filename, changes) => (filename, Text.abbreviate(changes.map {case (oldId, newId) => oldId.shortName+" ⇒ "+newId.shortName}, "...").mkString(", ")) } { case (oldId, newId) => Seq(oldId.name, newId.name) } implicit val reader = objectIdCleaner.threadLocalResources.reader() reportFiles(objectIdCleaner.deletionsByFilename, "Deleted", ("Filename", "Git id")) { case (filename, oldIds) => (filename, Text.abbreviate(oldIds.map(oldId => oldId.shortName + oldId.sizeOpt.map(size => s" (${ByteSize.format(size)})").mkString), "...").mkString(", ")) } { oldId => Seq(oldId.name, oldId.sizeOpt.mkString) } println(s"\n\nIn total, ${changedIds.size} object ids were changed. Full details are logged here:\n\n\t$reportsDir") dump(mapFile,SortedMap[AnyObjectId, ObjectId](changedIds.toSeq: _*).view.map { case (o,n) => s"${o.name} ${n.name}"}) dump(cacheStatsFile,objectIdCleaner.stats().map(_.toString())) println("\nBFG run is complete! When ready, run: git reflog expire --expire=now --all && git gc --prune=now --aggressive") } def title(text: String) = s"\n$text\n" + ("-" * text.size) + "\n" } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/TreeBlobModifier.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.madgag.git.bfg.MemoUtil import com.madgag.git.bfg.model.{TreeBlobEntry, _} import org.eclipse.jgit.lib.ObjectId trait TreeBlobModifier extends Cleaner[TreeBlobs] { val memoisedCleaner: Cleaner[TreeBlobEntry] = MemoUtil.concurrentCleanerMemo[TreeBlobEntry](Set.empty) { entry => val (mode, objectId) = fix(entry) TreeBlobEntry(entry.filename, mode, objectId) } def fix(entry: TreeBlobEntry): (BlobFileMode, ObjectId) // implementing code can not safely know valid filename override def apply(treeBlobs: TreeBlobs) = treeBlobs.entries.map(memoisedCleaner) } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/commits.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.madgag.git.ThreadLocalObjectDatabaseResources import com.madgag.git.bfg.model._ import org.eclipse.jgit.lib._ import org.eclipse.jgit.revwalk.RevCommit object CommitNodeCleaner { class Kit(val threadLocalResources: ThreadLocalObjectDatabaseResources, val originalRevCommit: RevCommit, val originalCommit: Commit, val updatedArcs: CommitArcs, val mapper: Cleaner[ObjectId]) { val arcsChanged = originalCommit.arcs != updatedArcs def commitIsChanged(withThisNode: CommitNode) = arcsChanged || originalCommit.node != withThisNode } def chain(cleaners: Seq[CommitNodeCleaner]) = new CommitNodeCleaner { def fixer(kit: CommitNodeCleaner.Kit) = Function.chain(cleaners.map(_.fixer(kit))) } } trait CommitNodeCleaner { def fixer(kit: CommitNodeCleaner.Kit): Cleaner[CommitNode] } object FormerCommitFooter extends CommitNodeCleaner { val Key = "Former-commit-id" override def fixer(kit: CommitNodeCleaner.Kit) = modifyIf(kit.commitIsChanged) { _ add Footer(Key, kit.originalRevCommit.name) } def modifyIf[A](predicate: A => Boolean)(modifier: A => A): (A => A) = v => if (predicate(v)) modifier(v) else v } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/kit/BlobInserter.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner.kit import java.io.InputStream import org.eclipse.jgit.lib.Constants._ import org.eclipse.jgit.lib.{ObjectId, ObjectInserter} class BlobInserter(objectInserter: ObjectInserter) { def insert(data: Array[Byte]): ObjectId = objectInserter.insert(OBJ_BLOB, data) def insert(length: Long, in: InputStream): ObjectId = objectInserter.insert(OBJ_BLOB, length, in) } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/package.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg package object cleaner { type Cleaner[V] = V => V } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/protection/ProtectedObjectCensus.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner.protection import com.madgag.git._ import com.madgag.scala.collection.decorators._ import org.eclipse.jgit.lib.{ObjectId, Repository} import org.eclipse.jgit.revwalk._ /** * PROTECTING TREES : * Want to leave the tree unchanged for all commits at the tips of refs the user thinks are important. * What if you think a Tag is important? Or a tree? * * If a tag points to a: * - commit - that commit may change, but it's tree must stay the same * - tree - who the fuck tags tree anyway? if I've been asked to protect it, that suggests that it's supposed to be inviolate * - blob - that blob will continue to be referenced by the repo, not disappear, but not be cleaned either, as we currently clean at TreeBlob level * * We can take a shortcut here by just pushing all hallowed trees straight into the memo collection * This does mean that we will never notice, or be able to report, if somebody sets a rule that 'cleans' (alters) a hallowed tree * It might also have somewhat unexpected consequences if someone hallows a very 'simple' directory that occurs often * * * PROTECTING BLOBS : * If a user wants to protect the tip of a ref, all blobs will be retained. There is no space-saving or secrets-kept * by deleting, tampering with those blobs elsewhere. And if you have some big-old blob like a jar that you have * used consistently throughout the history of your project, it benefits no-one to remove it- in fact it's actively * harmful. * * We explicitly protect blobs (rather than just allowing them to fall under the protection given to Trees) precisely * because these blobs may historically have existed in other directories (trees) that did not appear in the * protected tips, and so would not be protected by Tree protection. * * * PROTECTING TAGS & COMMITS : * This just means protecting the Trees & Blobs under those Tags and Commits, as specified above. Changing other * state - such as the message, or author, or referenced commit Ids (and consequently the object Id of the target * object itself) is very much up for grabs. I gotta change your history, or I've no business being here. */ object ProtectedObjectCensus { val None = ProtectedObjectCensus() def apply(revisions: Set[String])(implicit repo: Repository): ProtectedObjectCensus = { implicit val (revWalk, reader) = repo.singleThreadedReaderTuple val objectProtection = revisions.groupBy { revision => Option(repo.resolve(revision)).getOrElse { throw new IllegalArgumentException( s"Couldn't find '$revision' in ${repo.topDirectory.getAbsolutePath} - are you sure that exists?" )}.asRevObject } // blobs come from direct blob references and tag references // trees come from direct tree references, commit & tag references val treeAndBlobProtection = objectProtection.keys.groupUp(treeOrBlobPointedToBy)(_.toSet) // use Either? val directBlobProtection = treeAndBlobProtection collect { case (Left(blob), p) => blob.getId -> p } val treeProtection = treeAndBlobProtection collect { case (Right(tree), p) => tree -> p } val indirectBlobProtection = treeProtection.keys.flatMap(tree => allBlobsUnder(tree).map(_ -> tree)).groupUp(_._1)(_.map(_._2).toSet) ProtectedObjectCensus(objectProtection, treeProtection, directBlobProtection, indirectBlobProtection) } } case class ProtectedObjectCensus(protectorRevsByObject: Map[RevObject, Set[String]] = Map.empty, treeProtection: Map[RevTree, Set[RevObject]] = Map.empty, directBlobProtection: Map[ObjectId, Set[RevObject]] = Map.empty, indirectBlobProtection: Map[ObjectId, Set[RevTree]] = Map.empty) { val isEmpty = protectorRevsByObject.isEmpty lazy val blobIds: Set[ObjectId] = directBlobProtection.keySet ++ indirectBlobProtection.keySet lazy val treeIds = treeProtection.keySet // blobs only for completeness here lazy val fixedObjectIds: Set[ObjectId] = treeIds ++ blobIds } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/protection/ProtectedObjectDirtReport.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner.protection import com.madgag.git._ import com.madgag.git.bfg.GitUtil._ import com.madgag.git.bfg.cleaner.ObjectIdCleaner import org.eclipse.jgit.diff.DiffEntry import org.eclipse.jgit.diff.DiffEntry.ChangeType._ import org.eclipse.jgit.lib.{ObjectDatabase, ObjectId} import org.eclipse.jgit.revwalk.{RevObject, RevWalk} import org.eclipse.jgit.treewalk.TreeWalk import org.eclipse.jgit.treewalk.filter.TreeFilter import scala.jdk.CollectionConverters._ object ProtectedObjectDirtReport { def reportsFor(objectIdCleanerConfig: ObjectIdCleaner.Config, objectDB: ObjectDatabase)(implicit revWalk: RevWalk) = { val uncaringCleaner: ObjectIdCleaner = new ObjectIdCleaner( objectIdCleanerConfig.copy(protectedObjectCensus = ProtectedObjectCensus.None), objectDB, revWalk ) for (protectedRevObj <- objectIdCleanerConfig.protectedObjectCensus.protectorRevsByObject.keys) yield { val originalContentTreeOrBlob = treeOrBlobPointedToBy(protectedRevObj) val replacementTreeOrBlob = originalContentTreeOrBlob.fold(uncaringCleaner.cleanBlob.replacement, uncaringCleaner.cleanTree.replacement) ProtectedObjectDirtReport(protectedRevObj, originalContentTreeOrBlob.merge, replacementTreeOrBlob) } } } /** * The function of the ProtectedObjectDirtReport is tell the user that this is the stuff they've decided * to protect in their latest commits - it's the stuff The BFG /would/ remove if you hadn't told it to * hold back, * * @param revObject - the protected object (eg protected because it is the HEAD commit, or even by additional refs) * @param originalTreeOrBlob - the unmodified content-object referred to by the protected object (may be same object) * @param replacementTreeOrBlob - an option, populated if cleaning creates a replacement for the content-object */ case class ProtectedObjectDirtReport(revObject: RevObject, originalTreeOrBlob: RevObject, replacementTreeOrBlob: Option[ObjectId]) { val objectProtectsDirt: Boolean = replacementTreeOrBlob.isDefined def dirt(implicit revWalk: RevWalk): Option[Seq[DiffEntry]] = replacementTreeOrBlob.map { newId => val tw = new TreeWalk(revWalk.getObjectReader) tw.setRecursive(true) tw.reset tw.addTree(originalTreeOrBlob.asRevTree) tw.addTree(newId.asRevTree) tw.setFilter(TreeFilter.ANY_DIFF) DiffEntry.scan(tw).asScala.filterNot(_.getChangeType == ADD).toSeq } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/treeblobs.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.madgag.git.bfg.cleaner.kit.BlobInserter import com.madgag.git.bfg.model.FileName.ImplicitConversions._ import com.madgag.git.bfg.model.{TreeBlobEntry, _} import com.madgag.textmatching.TextMatcher import org.eclipse.jgit.lib.ObjectId class FileDeleter(fileNameMatcher: TextMatcher) extends Cleaner[TreeBlobs] { override def apply(tbs: TreeBlobs) = tbs.entries.filterNot(e => fileNameMatcher(e.filename)) } class BlobRemover(blobIds: Set[ObjectId]) extends Cleaner[TreeBlobs] { override def apply(treeBlobs: TreeBlobs) = treeBlobs.entries.filter(e => !blobIds.contains(e.objectId)) } class BlobReplacer(badBlobs: Set[ObjectId], blobInserter: => BlobInserter) extends Cleaner[TreeBlobs] { override def apply(treeBlobs: TreeBlobs) = treeBlobs.entries.map { case e if badBlobs.contains(e.objectId) => TreeBlobEntry(FileName(e.filename + ".REMOVED.git-id"), RegularFile, blobInserter.insert(e.objectId.name.getBytes)) case e => e } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/memo.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg import scala.jdk.CollectionConverters._ import com.google.common.cache.{CacheBuilder, CacheLoader, CacheStats, LoadingCache} import com.madgag.git.bfg.cleaner._ trait Memo[K, V] { def apply(z: K => V): MemoFunc[K, V] } trait MemoFunc[K,V] extends (K => V) { def asMap(): Map[K,V] def stats(): CacheStats } object MemoUtil { def memo[K, V](f: (K => V) => MemoFunc[K, V]): Memo[K, V] = new Memo[K, V] { def apply(z: K => V) = f(z) } /** * * A caching wrapper for a function (V => V), backed by a no-eviction LoadingCache from Google Collections. */ def concurrentCleanerMemo[V](fixedEntries: Set[V] = Set.empty[V]): Memo[V, V] = { memo[V, V] { (f: Cleaner[V]) => lazy val permanentCache = loaderCacheFor(f)(fix) def fix(v: V): Unit = { // enforce that once any value is returned, it is 'good' and therefore an identity-mapped key as well permanentCache.put(v, v) } fixedEntries foreach fix new MemoFunc[V, V] { def apply(k: V) = permanentCache.get(k) def asMap() = permanentCache.asMap().asScala.view.filter { case (oldId, newId) => newId != oldId }.toMap override def stats(): CacheStats = permanentCache.stats() } } } def loaderCacheFor[K, V](calc: K => V)(postCalc: V => Unit): LoadingCache[K, V] = CacheBuilder.newBuilder.asInstanceOf[CacheBuilder[K, V]].recordStats().build(new CacheLoader[K, V] { def load(key: K): V = { val v = calc(key) postCalc(v) v } }) } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/model/Commit.scala ================================================ package com.madgag.git.bfg.model import com.madgag.git._ import com.madgag.git.bfg.cleaner._ import org.eclipse.jgit.lib.Constants.OBJ_COMMIT import org.eclipse.jgit.lib._ import org.eclipse.jgit.revwalk.RevCommit import java.nio.charset.StandardCharsets.UTF_8 import java.nio.charset.{Charset, IllegalCharsetNameException, UnsupportedCharsetException} import scala.jdk.CollectionConverters._ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ object Commit { def apply(revCommit: RevCommit): Commit = Commit(CommitNode(revCommit), revCommit.arcs) } case class Commit(node: CommitNode, arcs: CommitArcs) { def toBytes: Array[Byte] = { val c = new CommitBuilder c.setParentIds(arcs.parents.asJava) c.setTreeId(arcs.tree) c.setAuthor(node.author) c.setCommitter(node.committer) c.setEncoding(node.encoding) c.setMessage(node.message) c.toByteArray } lazy val id = new ObjectInserter.Formatter().idFor(OBJ_COMMIT, toBytes) override lazy val toString = s"commit[${id.shortName}${node.subject.map(s=> s" '${s.take(50)}'").getOrElse("")}]" } case class CommitArcs(parents: Seq[ObjectId], tree: ObjectId) { def cleanWith(cleaner: ObjectIdCleaner) = CommitArcs(parents map cleaner.cleanCommit, cleaner.cleanTree(tree)) } object CommitNode { def apply(c: RevCommit): CommitNode = CommitNode(c.getAuthorIdent, c.getCommitterIdent, c.getFullMessage, try c.getEncoding catch {case e @ (_ : IllegalCharsetNameException | _ : UnsupportedCharsetException) => UTF_8}) } case class CommitNode(author: PersonIdent, committer: PersonIdent, message: String, encoding: Charset = UTF_8) { lazy val subject = message.linesIterator.to(LazyList).headOption lazy val lastParagraphBreak = message.lastIndexOf("\n\n") lazy val messageWithoutFooters = if (footers.isEmpty) message else (message take lastParagraphBreak) lazy val footers: List[Footer] = message.drop(lastParagraphBreak).linesIterator.collect { case Footer.FooterPattern(key, value) => Footer(key, value) }.toList def add(footer: Footer) = copy(message = message + "\n" + (if (footers.isEmpty) "\n" else "") + footer.toString) } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/model/Footer.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.model object Footer { // ^[A-Za-z0-9-]+: val FooterPattern = """([\p{Alnum}-]+): *(.*)""".r def apply(footerLine: String): Option[Footer] = footerLine match { case FooterPattern(key, value) => Some(Footer(key, value)) case _ => None } } case class Footer(key: String, value: String) { override lazy val toString = key + ": " + value } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/model/package.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg import org.eclipse.jgit.revwalk.RevCommit import java.nio.file.Path package object model { implicit class RichRevCommit(revCommit: RevCommit) { lazy val arcs: CommitArcs = CommitArcs(revCommit.getParents.toIndexedSeq, revCommit.getTree) } implicit class RichPath(path: Path) { def resolve(pathSegments: Seq[String]): Path = pathSegments.foldLeft(path)(_ resolve _) } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/git/bfg/timing.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg import java.lang.System._ import java.util.concurrent.TimeUnit.NANOSECONDS import org.eclipse.jgit.lib.ProgressMonitor object Timing { // def measure[T](block: => T) = { // val start = nanoTime // val result = block // val duration = nanoTime - start // println("duration="+duration) // result // } def measureTask[T](taskName: String, workSize: Int)(block: => T)(implicit progressMonitor: ProgressMonitor) = { progressMonitor.beginTask(taskName, workSize) val start = nanoTime val result = block val duration = nanoTime - start progressMonitor.endTask() println(taskName + " completed in %,d ms.".format(NANOSECONDS.toMillis(duration))) result } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/inclusion/inclusion.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.inclusion import scala.Function.const case class IncExcExpression[-A](filters: Seq[Filter[A]]) { lazy val searchPath = (filters.headOption.map(_.impliedPredecessor).getOrElse(Include.everything) +: filters).reverse def includes(a: A): Boolean = searchPath.find(_.predicate(a)).get.included } sealed trait Filter[-A] { val included: Boolean val predicate: A => Boolean val impliedPredecessor: Filter[A] def isDefinedAt(a: A) = predicate(a) } object Include { def everything = Include(const(true)) } object Exclude { def everything = Exclude(const(true)) } case class Include[A](predicate: A => Boolean) extends Filter[A] { lazy val impliedPredecessor = Exclude.everything val included = true } case class Exclude[A](predicate: A => Boolean) extends Filter[A] { lazy val impliedPredecessor = Include.everything val included = false } ================================================ FILE: bfg-library/src/main/scala/com/madgag/text/ByteSize.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.text object ByteSize { import math._ val magnitudeChars = Seq('B', 'K', 'M', 'G', 'T', 'P') val unit = 1024 def parse(v: String): Long = magnitudeChars.indexOf(v.takeRight(1)(0).toUpper) match { case -1 => throw new IllegalArgumentException(s"Size unit is missing (ie ${magnitudeChars.mkString(", ")})") case index => v.dropRight(1).toLong << (index * 10) } def format(bytes: Long): String = { if (bytes < unit) s"$bytes B " else { val exp = (log(bytes.toDouble) / log(unit)).toInt val pre = magnitudeChars(exp) "%.1f %sB".format(bytes / pow(unit, exp), pre) } } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/text/Tables.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.text object Tables { def formatTable(header: Product, data: Seq[Product], maxDataRows: Int = 16): Seq[String] = { val numColumns = data.head.productArity val sizes: Seq[Int] = (0 until numColumns).map(i => (data :+ header).map(_.productElement(i).toString.length).max) def padLine(l: Product): IndexedSeq[String] = { (0 until numColumns).map(c => l.productElement(c).toString.padTo(sizes(c), ' ')) } val headerLine = padLine(header).mkString(" ") Text.abbreviate(headerLine +: "-" * headerLine.size +: data.map { l => padLine(l).mkString(" | ") }, "...", maxDataRows+2).toSeq } } ================================================ FILE: bfg-library/src/main/scala/com/madgag/text/text.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.text object Text { def abbreviate[A](elems: Iterable[A], truncationToken: A, maxElements: Int = 3) = { val firstElems = elems.take(maxElements + 1) if (firstElems.size > maxElements) { firstElems.take(maxElements-1).toSeq :+ truncationToken } else { elems } } def plural[A](list: Iterable[A], noun: String) = s"${list.size} $noun${if (list.size == 1) "" else "s"}" } ================================================ FILE: bfg-library/src/test/scala/com/madgag/git/LFSSpec.scala ================================================ /* * Copyright (c) 2015 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git import com.madgag.git.LFS.Pointer import com.madgag.git.test._ import org.eclipse.jgit.lib.Constants._ import org.eclipse.jgit.lib.ObjectInserter import org.scalatest.OptionValues import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import java.nio.file.Files import java.nio.file.Files.createTempFile class LFSSpec extends AnyFlatSpec with Matchers with OptionValues { "Our implementation of Git LFS Pointers" should "create pointers that have the same Git id as the ones produced by `git lfs pointer`" in { val pointer = LFS.Pointer("b2893eddd9b394bfb7efadafda2ae0be02c573fdd83a70f26c781a943f3b7016", 21616) val pointerObjectId = new ObjectInserter.Formatter().idFor(OBJ_BLOB, pointer.bytes) pointerObjectId shouldBe "1d90744cffd9e9f324870ed60b6d1258e56a39e1".asObjectId } it should "have the correctly sharded path" in { val pointer = LFS.Pointer("b2893eddd9b394bfb7efadafda2ae0be02c573fdd83a70f26c781a943f3b7016", 21616) pointer.path shouldBe Seq("b2", "89", "b2893eddd9b394bfb7efadafda2ae0be02c573fdd83a70f26c781a943f3b7016") } it should "calculate pointers correctly directly from the Git database, creating a temporary file" in { implicit val repo = unpackRepo("/sample-repos/example.git.zip") implicit val (revWalk, reader) = repo.singleThreadedReaderTuple val tmpFile = createTempFile(s"bfg.test.git-lfs",".conv") val pointer = LFS.pointerFor(abbrId("06d7").open, tmpFile) pointer shouldBe Pointer("5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef", 1024) Files.size(tmpFile) shouldBe 1024 } } ================================================ FILE: bfg-library/src/test/scala/com/madgag/git/bfg/GitUtilSpec.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg import com.madgag.git._ import com.madgag.git.test._ import org.eclipse.jgit.internal.storage.file.FileRepository import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class GitUtilSpec extends AnyFlatSpec with Matchers { implicit val repo: FileRepository = unpackRepo("/sample-repos/example.git.zip") "reachable blobs" should "match expectations" in { implicit val (revWalk, reader) = repo.singleThreadedReaderTuple allBlobsReachableFrom(abbrId("475d") asRevCommit) shouldBe Set("d8d1", "34bd", "e69d", "c784", "d004").map(abbrId) } } ================================================ FILE: bfg-library/src/test/scala/com/madgag/git/bfg/MessageFooterSpec.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg import com.madgag.git.bfg.model.{CommitNode, Footer} import org.eclipse.jgit.lib.PersonIdent import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class MessageFooterSpec extends AnyFlatSpec with Matchers { val person = new PersonIdent("Dave Eg", "dave@e.com") def commit(m: String) = CommitNode(person, person, m) "Message footers" should "append footer without new paragraph if footers already present" in { val updatedCommit = commit("Sub\n\nmessage\n\nSigned-off-by: Joe Eg ") add Footer("Foo", "Bar") updatedCommit.message shouldBe "Sub\n\nmessage\n\nSigned-off-by: Joe Eg \nFoo: Bar" } it should "create paragraph break if no footers already present" in { val updatedCommit = commit("Sub\n\nmessage") add Footer("Foo", "Bar") updatedCommit.message shouldBe "Sub\n\nmessage\n\nFoo: Bar" } // def footersViaJGit(commit: RevCommit) = commit.getFooterLines.map(f => Footer(f.getKey, f.getValue)).toList } ================================================ FILE: bfg-library/src/test/scala/com/madgag/git/bfg/TreeEntrySpec.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg import com.madgag.git.bfg.model.{FileName, Tree} import org.eclipse.jgit.lib.FileMode import org.eclipse.jgit.lib.FileMode._ import org.eclipse.jgit.lib.ObjectId.zeroId import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class TreeEntrySpec extends AnyFlatSpec with Matchers { def a(mode: FileMode, name: String) = Tree.Entry(FileName(name), mode, zeroId) "Tree entry ordering" should "match ordering used by Git" in { a(TREE, "agit-test-utils") should be < a(TREE, "agit") } } ================================================ FILE: bfg-library/src/test/scala/com/madgag/git/bfg/cleaner/LfsBlobConverterSpec.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.madgag.diff.{After, Before, MapDiff} import com.madgag.git.LFS.Pointer import com.madgag.git._ import com.madgag.git.bfg.model.{BlobFileMode, FileName, Tree, TreeBlobs, _} import com.madgag.git.test._ import com.madgag.scala.collection.decorators._ import org.eclipse.jgit.internal.storage.file.FileRepository import org.eclipse.jgit.lib.ObjectId import org.scalatest.concurrent.Eventually import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{Inspectors, OptionValues} import java.nio.file.Files.readAllBytes import java.nio.file.{Files, Path} class LfsBlobConverterSpec extends AnyFlatSpec with Matchers with OptionValues with Inspectors with Eventually { "LfsBlobConverter" should "successfully shift the blob to the LFS store" in { implicit val repo = unpackRepo("/sample-repos/example.git.zip") implicit val (revWalk, reader) = repo.singleThreadedReaderTuple val oldTreeBlobs = Tree(repo.resolve("early-release^{tree}")).blobs val newTreeBlobs = clean(oldTreeBlobs, "*ero*") val diff = oldTreeBlobs.diff(newTreeBlobs) diff.changed shouldBe Set(FileName("one-kb-zeros")) diff.unchanged should contain allOf(FileName("hero"), FileName("zero")) verifyPointersForChangedFiles(diff) } it should "not do damage if run twice - ie don't create a pointer for a pointer!" in { implicit val repo = unpackRepo("/sample-repos/example.git.zip") implicit val (revWalk, reader) = repo.singleThreadedReaderTuple val oldTreeBlobs = Tree(repo.resolve("early-release^{tree}")).blobs val treeBlobsAfterRun1 = clean(oldTreeBlobs, "*ero*") val firstDiff = oldTreeBlobs.diff(treeBlobsAfterRun1) firstDiff.changed shouldBe Set(FileName("one-kb-zeros")) val treeBlobsAfterRun2 = clean(treeBlobsAfterRun1, "*ero*") treeBlobsAfterRun1.diff(treeBlobsAfterRun2).changed shouldBe empty verifyPointersForChangedFiles(firstDiff) // Are the LFS files still intact? } def clean(oldTreeBlobs: TreeBlobs, glob: String)(implicit repo: FileRepository): TreeBlobs = { val converter = new LfsBlobConverter(glob, repo) converter(oldTreeBlobs) } def verifyPointerInsertedFor(fileName: FileName, diff: MapDiff[FileName, (BlobFileMode, ObjectId)])(implicit repo: FileRepository) = { implicit val (revWalk, reader) = repo.singleThreadedReaderTuple diff.changed should contain(fileName) val fileBeforeAndAfter = diff.changedMap(fileName) fileBeforeAndAfter(After)._1 shouldBe fileBeforeAndAfter(Before)._1 val fileIds = fileBeforeAndAfter.mapV(_._2) val (originalFileId, pointerObjectId) = (fileIds(Before), fileIds(After)) verifyPointerFileFor(originalFileId, pointerObjectId) } def verifyPointerFileFor(originalFileId: ObjectId, pointerObjectId: ObjectId)(implicit repo: FileRepository) = { implicit val (revWalk, reader) = repo.singleThreadedReaderTuple val pointer = Pointer.parse(pointerObjectId.open.getCachedBytes) val lfsStoredFile: Path = repo.getDirectory.toPath.resolve(Seq("lfs", "objects") ++ pointer.path) Files.exists(lfsStoredFile) shouldBe true Files.size(lfsStoredFile) shouldBe pointer.blobSize eventually { readAllBytes(lfsStoredFile).blobId } shouldBe originalFileId } def verifyPointersForChangedFiles(diff: MapDiff[FileName, (BlobFileMode, ObjectId)])(implicit repo: FileRepository) = { diff.only(Before) shouldBe empty diff.only(After).keys shouldBe Set(FileName(".gitattributes")) forAll(diff.changed) { fileName => verifyPointerInsertedFor(fileName, diff) } } } ================================================ FILE: bfg-library/src/test/scala/com/madgag/git/bfg/cleaner/ObjectIdCleanerSpec.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.madgag.git._ import com.madgag.git.bfg.cleaner.protection.ProtectedObjectCensus import com.madgag.textmatching.Literal import org.eclipse.jgit.lib.ObjectId import org.eclipse.jgit.revwalk.RevCommit import org.scalatest.Inspectors import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.Matcher import org.scalatest.matchers.should.Matchers import scala.jdk.CollectionConverters._ class ObjectIdCleanerSpec extends AnyFlatSpec with Matchers { "cleaning" should "not have a StackOverflowError cleaning a repo with deep history" ignore new unpackedRepo("/sample-repos/deep-history.zip") { val dirtyCommitWithDeepHistory = "d88ac4f99511667fc0617ea026f3a0ce8a25fd07".asObjectId val config = ObjectIdCleaner.Config( ProtectedObjectCensus.None, treeBlobsCleaners = Seq(new FileDeleter(Literal("foo"))) ) ensureCleanerWith(config).removesDirtOfCommitsThat(haveFile("foo")).whenCleaning(dirtyCommitWithDeepHistory) } } class unpackedRepo(filePath: String) extends bfg.test.unpackedRepo(filePath) { class EnsureCleanerWith(config: ObjectIdCleaner.Config) { class RemoveDirtOfCommitsThat(commitM: Matcher[RevCommit]) extends Inspectors with Matchers { def histOf(c: ObjectId) = repo.git.log.add(c).call.asScala.toSeq.reverse def whenCleaning(oldCommit: ObjectId): Unit = { val cleaner = new ObjectIdCleaner(config, repo.getObjectDatabase, revWalk) forAtLeast(1, histOf(oldCommit)) { commit => commit should commitM } val cleanCommit = cleaner.cleanCommit(oldCommit) forAll(histOf(cleanCommit)) { commit => commit shouldNot commitM } } } def removesDirtOfCommitsThat[T](commitM: Matcher[RevCommit]) = new RemoveDirtOfCommitsThat(commitM) } def ensureCleanerWith(config: ObjectIdCleaner.Config) = new EnsureCleanerWith(config) } ================================================ FILE: bfg-library/src/test/scala/com/madgag/git/bfg/cleaner/ObjectIdSubstitutorSpec.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.madgag.git._ import com.madgag.git.bfg.cleaner.ObjectIdSubstitutor.hexRegex import com.madgag.git.test._ import org.eclipse.jgit.lib.ObjectId import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ObjectIdSubstitutorSpec extends AnyFlatSpec with Matchers { "Object Id Substitutor regex" should "match hex strings" in { "01234567890" should include regex hexRegex "decade2001" should include regex hexRegex "This is decade2001" should include regex hexRegex "This is decade2001 I say" should include regex hexRegex "This is Gdecade2001 I say" shouldNot include regex hexRegex "This is decade2001X I say" shouldNot include regex hexRegex } "Object Id" should "be substituted in commit message" in { implicit val repo = unpackRepo("/sample-repos/example.git.zip") implicit val reader = repo.newObjectReader val cleanedMessage = ObjectIdSubstitutor.OldIdsPublic.replaceOldIds("See 3699910d2baab1 for backstory", reader, (_: ObjectId) => abbrId("06d7405020018d")) cleanedMessage shouldBe "See 06d7405020018d [formerly 3699910d2baab1] for backstory" } } ================================================ FILE: bfg-library/src/test/scala/com/madgag/git/bfg/cleaner/RepoRewriteSpec.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.madgag.git._ import com.madgag.git.bfg.GitUtil._ import com.madgag.git.bfg.cleaner.ObjectIdSubstitutor._ import com.madgag.git.bfg.cleaner.protection.ProtectedObjectCensus import com.madgag.git.bfg.model.{FileName, RegularFile, TreeBlobEntry} import com.madgag.git.test._ import com.madgag.textmatching._ import org.apache.commons.io.FilenameUtils import org.eclipse.jgit.lib.ObjectId import org.eclipse.jgit.revwalk.RevWalk import org.eclipse.jgit.util.RawParseUtils import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import java.io.StringReader import java.net.URLEncoder import java.util.Properties import java.util.regex.Pattern._ import scala.PartialFunction.condOpt import scala.jdk.CollectionConverters._ class RepoRewriteSpec extends AnyFlatSpec with Matchers { "Git repo" should "not explode" in { implicit val repo = unpackRepo("/sample-repos/example.git.zip") implicit val reader = repo.newObjectReader hasBeenProcessedByBFGBefore(repo) shouldBe false val blobsToRemove = Set(abbrId("06d740")) RepoRewriter.rewrite(repo, ObjectIdCleaner.Config(ProtectedObjectCensus(Set("HEAD")), OldIdsPublic, Seq(FormerCommitFooter), treeBlobsCleaners = Seq(new BlobRemover(blobsToRemove)))) val allCommits = repo.git.log.all.call.asScala.toSeq val unwantedBlobsByCommit = allCommits.flatMap(commit => { val unwantedBlobs = allBlobsReachableFrom(commit).intersect(blobsToRemove).map(_.shortName) if (!unwantedBlobs.isEmpty) Some(commit.shortName -> unwantedBlobs) else None }).toMap unwantedBlobsByCommit shouldBe empty allCommits.head.getFullMessage should include(FormerCommitFooter.Key) hasBeenProcessedByBFGBefore(repo) shouldBe true } "Repo rewriter" should "clean commit messages even on clean branches, because commit messages may reference commits from dirty ones" in { implicit val repo = unpackRepo("/sample-repos/taleOfTwoBranches.git.zip") implicit val revWalk = new RevWalk(repo) def commitMessageForRev(rev: String) = repo.resolve(rev).asRevCommit.getFullMessage commitMessageForRev("pure") should include("6e76960ede2addbbe7e") RepoRewriter.rewrite(repo, ObjectIdCleaner.Config(ProtectedObjectCensus.None, OldIdsPrivate, Seq(new CommitMessageObjectIdsUpdater(OldIdsPrivate)), treeBlobsCleaners = Seq(new FileDeleter(Literal("sin"))))) commitMessageForRev("pure") should not include "6e76960ede2addbbe7e" } it should "remove passwords" in { implicit val repo = unpackRepo("/sample-repos/example.git.zip") implicit val (revWalk, reader) = repo.singleThreadedReaderTuple def propertiesIn(contents: String) = { val p = new Properties() p.load(new StringReader(contents)) p } def passwordFileContentsIn(id: ObjectId) = { val cleanedPasswordFile = repo.resolve(id.name + ":folder/secret-passwords.txt") RawParseUtils.decode(reader.open(cleanedPasswordFile).getCachedBytes) } object FileExt { def unapply(fileName: String) = Option(FilenameUtils.getExtension(fileName)) } val blobTextModifier = new BlobTextModifier { override def lineCleanerFor(entry: TreeBlobEntry) = condOpt(entry.filename.string) { case FileExt("txt") | FileExt("scala") => """(\.password=).*""".r --> (_.group(1) + "*** PASSWORD ***") } val threadLocalObjectDBResources = repo.getObjectDatabase.threadLocalResources } val cleanedObjectMap = RepoRewriter.rewrite(repo, ObjectIdCleaner.Config(ProtectedObjectCensus(Set("HEAD")), treeBlobsCleaners = Seq(blobTextModifier))) val oldCommitContainingPasswords = abbrId("37bcc89") val cleanedCommitWithPasswordsRemoved = cleanedObjectMap(oldCommitContainingPasswords).asRevCommit val originalContents = passwordFileContentsIn(oldCommitContainingPasswords) val cleanedContents = passwordFileContentsIn(cleanedCommitWithPasswordsRemoved) cleanedContents should (include("science") and include("database.password=")) originalContents should include("correcthorse") cleanedContents should not include "correcthorse" propertiesIn(cleanedContents).asScala.toMap should have size propertiesIn(originalContents).size } def textReplacementOf(parentPath: String, fileNamePrefix: String, fileNamePostfix: String, before: String, after: String) = { implicit val repo = unpackRepo("/sample-repos/encodings.git.zip") val beforeAndAfter = Seq(before, after).map(URLEncoder.encode(_, "UTF-8")).mkString("-") val filename = s"$fileNamePrefix-ORIGINAL.$fileNamePostfix" val beforeFile = s"$parentPath/$filename" val afterFile = s"$parentPath/$fileNamePrefix-MODIFIED-$beforeAndAfter.$fileNamePostfix" val blobTextModifier = new BlobTextModifier { def lineCleanerFor(entry: TreeBlobEntry) = Some(quote(before).r --> (_ => after)) val threadLocalObjectDBResources = repo.getObjectDatabase.threadLocalResources } RepoRewriter.rewrite(repo, ObjectIdCleaner.Config(ProtectedObjectCensus.None, treeBlobsCleaners = Seq(blobTextModifier))) val cleanedFile = repo.resolve(s"master:$beforeFile") val expectedFile = repo.resolve(s"master:$afterFile") expectedFile should not be null implicit val threadLocalObjectReader = repo.getObjectDatabase.threadLocalResources.reader() val cleaned = cleanedFile.open.getBytes val expected = expectedFile.open.getBytes val cleanedStr = new String(cleaned) val expectedStr = new String(expected) cleanedStr shouldBe expectedStr cleanedFile shouldBe expectedFile } "Text modifier" should "handle the short UTF-8" in textReplacementOf("UTF-8", "bushhidthefacts", "txt", "facts", "toffee") it should "handle the long UTF-8" in textReplacementOf("UTF-8", "big", "scala", "good", "blessed") it should "handle ASCII in SHIFT JIS" in textReplacementOf("SHIFT-JIS", "japanese", "txt", "EUC", "BOOM") it should "handle ASCII in ISO-8859-1" in textReplacementOf("ISO-8859-1", "laparabla", "txt", "palpitando", "buscando") it should "handle converting Windows newlines to Unix" in textReplacementOf("newlines", "windows", "txt", "\r\n", "\n") it should "handle a file that uses LF for newlines" in textReplacementOf("newlines", "using-LF", "txt", "file", "blob") it should "handle a file that uses CRLF for newlines" in textReplacementOf("newlines", "using-CRLF", "txt", "file", "blob") } ================================================ FILE: bfg-library/src/test/scala/com/madgag/git/bfg/cleaner/TreeBlobModifierSpec.scala ================================================ /* * Copyright (c) 2012 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.cleaner import com.google.common.util.concurrent.AtomicLongMap import com.madgag.git.bfg.cleaner.ObjectIdSubstitutor._ import com.madgag.git.bfg.cleaner.protection.ProtectedObjectCensus import com.madgag.git.bfg.model.TreeBlobEntry import com.madgag.git.test._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import scala.jdk.CollectionConverters._ class TreeBlobModifierSpec extends AnyFlatSpec with Matchers { "TreeBlobModifier" should "only clean a given tree entry once" in { class CountingTreeBlobModifier extends TreeBlobModifier { val counts = AtomicLongMap.create[TreeBlobEntry] def fix(entry: TreeBlobEntry) = { counts.incrementAndGet(entry) (entry.mode, entry.objectId) } } implicit val repo = unpackRepo("/sample-repos/taleOfTwoBranches.git.zip") val countingTreeBlobModifier = new CountingTreeBlobModifier() RepoRewriter.rewrite(repo, ObjectIdCleaner.Config(ProtectedObjectCensus(Set("HEAD")), OldIdsPublic, treeBlobsCleaners = Seq(countingTreeBlobModifier))) val endCounts = countingTreeBlobModifier.counts.asMap().asScala.toMap endCounts.size should be >= 4 all (endCounts.values) shouldBe 1 } } ================================================ FILE: bfg-library/src/test/scala/com/madgag/git/bfg/model/CommitSpec.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.git.bfg.model import com.madgag.git.bfg.test.unpackedRepo import org.scalatest.Inspectors import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class CommitSpec extends AnyFlatSpec with Matchers with Inspectors { "Commit model" should "calculate the same Git commit id for any given commit" in new unpackedRepo("/sample-repos/example.git.zip") { forAll (commitHist()) { revCommit => Commit(revCommit).id shouldBe revCommit.toObjectId } } } ================================================ FILE: bfg-library/src/test/scala/com/madgag/text/ByteSizeSpecs.scala ================================================ /* * Copyright (c) 2012, 2013 Roberto Tyley * * This file is part of 'BFG Repo-Cleaner' - a tool for removing large * or troublesome blobs from Git repositories. * * BFG Repo-Cleaner 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. * * BFG Repo-Cleaner 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 http://www.gnu.org/licenses/ . */ package com.madgag.text import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class ByteSizeSpecs extends AnyFlatSpec with Matchers { "Size parser" should "understand 1B" in { ByteSize.parse("0B") shouldBe 0 ByteSize.parse("1B") shouldBe 1 ByteSize.parse("2B") shouldBe 2 ByteSize.parse("10B") shouldBe 10 } it should "understand 3G" in { ByteSize.parse("3G") shouldBe 3L * 1024 * 1024 * 1024 } it should "understand 1G" in { ByteSize.parse("1G") shouldBe 1024 * 1024 * 1024 } it should "understand 1M" in { ByteSize.parse("1M") shouldBe 1024 * 1024 } it should "understand 3500M" in { ByteSize.parse("3500M") shouldBe 3500L * 1024 * 1024 } it should "understand 1K" in { ByteSize.parse("1K") shouldBe 1024 } it should "understand 5K" in { ByteSize.parse("5K") shouldBe 5 * 1024 } it should "reject strings without a unit" in { an[IllegalArgumentException] should be thrownBy ByteSize.parse("1232") } "Size formatter" should "correctly format" in { ByteSize.format(1024) shouldBe "1.0 KB" } } ================================================ FILE: bfg-test/build.sbt ================================================ import Dependencies._ libraryDependencies ++= Seq(scalatest, jgit, scalaGit, scalaGitTest) ================================================ FILE: bfg-test/src/main/scala/com/madgag/git/bfg/test/unpackedRepo.scala ================================================ package com.madgag.git.bfg.test import com.madgag.git._ import com.madgag.git.test._ import org.eclipse.jgit.internal.storage.file.{FileRepository, GC, ObjectDirectory} import org.eclipse.jgit.lib.Constants.OBJ_BLOB import org.eclipse.jgit.lib.{ObjectId, ObjectReader, Repository} import org.eclipse.jgit.revwalk.{RevCommit, RevTree, RevWalk} import org.eclipse.jgit.treewalk.TreeWalk import org.scalatest.Inspectors import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.matchers.{MatchResult, Matcher} import scala.jdk.CollectionConverters._ class unpackedRepo(filePath: String) extends AnyFlatSpec with Matchers { implicit val repo: FileRepository = unpackRepo(filePath) implicit val objectDirectory: ObjectDirectory = repo.getObjectDatabase implicit lazy val (revWalk: RevWalk, reader: ObjectReader) = repo.singleThreadedReaderTuple def blobOfSize(sizeInBytes: Int): Matcher[ObjectId] = Matcher { (objectId: ObjectId) => val objectLoader = objectId.open val hasThatSize = objectLoader.getType == OBJ_BLOB && objectLoader.getSize == sizeInBytes def thing(boo: String) = s"${objectId.shortName} $boo size of $sizeInBytes" MatchResult(hasThatSize, thing("did not have"), thing("had")) } def packedBlobsOfSize(sizeInBytes: Long): Set[ObjectId] = { implicit val reader: ObjectReader = repo.newObjectReader() repo.getObjectDatabase.packedObjects.filter { objectId => val objectLoader = objectId.open objectLoader.getType == OBJ_BLOB && objectLoader.getSize == sizeInBytes }.toSet } def haveFile(name: String): Matcher[ObjectId] = haveTreeEntry(name, !_.isSubtree) def haveFolder(name: String): Matcher[ObjectId] = haveTreeEntry(name, _.isSubtree) def haveTreeEntry(name: String, p: TreeWalk => Boolean)= new Matcher[ObjectId] { def apply(treeish: ObjectId) = { treeOrBlobPointedToBy(treeish.asRevObject) match { case Right(tree) => def thing(boo: String) = s"tree ${treeish.shortName} $boo a '$name' entry" MatchResult( treeEntryNames(tree, p).contains(name), thing("did not contain"), thing("contained") ) case Left(blob) => MatchResult( false, s"blob ${treeish.shortName} was not a tree containing '$name'", s"""When does this happen??!"""" ) } } } def treeEntryNames(t: RevTree, p: TreeWalk => Boolean): Seq[String] = t.walk(postOrderTraversal = true).withFilter(p).map(_.getNameString).toList def commitHist(specificRefs: String*)(implicit repo: Repository): Seq[RevCommit] = { val logCommand = repo.git.log if (specificRefs.isEmpty) logCommand.all else specificRefs.foldLeft(logCommand)((lc, ref) => lc.add(repo.resolve(ref))) }.call.asScala.toSeq.reverse def haveCommitWhereObjectIds(boom: Matcher[Iterable[ObjectId]])(implicit reader: ObjectReader): Matcher[RevCommit] = boom compose { (c: RevCommit) => c.getTree.walk().map(_.getObjectId(0)).toSeq } def haveRef(refName: String, objectIdMatcher: Matcher[ObjectId]): Matcher[Repository] = objectIdMatcher compose { (r: Repository) => r resolve refName // aka s"Ref [$refName]" } def commitHistory(histMatcher: Matcher[Seq[RevCommit]]) = histMatcher compose { r: Repository => commitHist()(r) } def commitHistoryFor(refs: String*)(histMatcher: Matcher[Seq[RevCommit]]) = histMatcher compose { r: Repository => commitHist(refs:_*)(r) } def ensureRemovalOfBadEggs[S,T](expr : => Iterable[S], exprResultMatcher: Matcher[Iterable[S]])(block: => T) = { gc() expr should exprResultMatcher block gc() expr shouldBe empty } def gc() = { val gc = new GC(repo) gc.setPackExpireAgeMillis(0) gc.gc() } class CheckRemovalFromCommits(commits: => Seq[RevCommit]) extends Inspectors { def ofCommitsThat[T](commitM: Matcher[RevCommit])(block: => T): Unit = { forAtLeast(1, commits) { commit => commit should commitM } block forAll(commits) { commit => commit shouldNot commitM } } } def ensureRemovalFrom(commits: => Seq[RevCommit]): CheckRemovalFromCommits = new CheckRemovalFromCommits(commits) def ensureInvariantValue[T, S](f: => S)(block: => T) = { val originalValue = f block f should equal(originalValue) } def ensureInvariantCondition[T, S](cond: Matcher[Repository])(block: => T) = { repo should cond block repo should cond } } ================================================ FILE: build.sbt ================================================ import ReleaseTransformations.* import Dependencies.* ThisBuild / organization := "com.madgag" ThisBuild / scalaVersion := "2.13.16" ThisBuild / scalacOptions ++= Seq("-deprecation", "-feature", "-language:postfixOps", "-release:11") ThisBuild / licenses := Seq(License.GPL3_or_later) ThisBuild / resolvers ++= jgitVersionOverride.map(_ => Resolver.mavenLocal).toSeq ThisBuild / libraryDependencies += scalatest % Test ThisBuild / Test/ testOptions += Tests.Argument( TestFrameworks.ScalaTest, "-u", s"test-results/scala-${scalaVersion.value}" ) lazy val root = Project(id = "bfg-parent", base = file(".")).aggregate (bfg, `bfg-test`, `bfg-library`).settings( publish / skip := true, releaseCrossBuild := true, // true if you cross-build the project for multiple Scala versions releaseProcess := Seq[ReleaseStep]( checkSnapshotDependencies, inquireVersions, runClean, runTest, setReleaseVersion, commitReleaseVersion, tagRelease, setNextVersion, commitNextVersion ) ) lazy val `bfg-test` = project lazy val `bfg-library` = project.dependsOn(`bfg-test` % Test) lazy val bfg = project.enablePlugins(BuildInfoPlugin).dependsOn(`bfg-library`, `bfg-test` % Test) lazy val `bfg-benchmark` = project ================================================ FILE: project/build.properties ================================================ sbt.version=1.10.7 ================================================ FILE: project/dependencies.scala ================================================ import sbt._ object Dependencies { val scalaGitVersion = "5.0.3" val jgitVersionOverride = Option(System.getProperty("jgit.version")) val jgitVersion = jgitVersionOverride.getOrElse("6.10.0.202406032230-r") val jgit = "org.eclipse.jgit" % "org.eclipse.jgit" % jgitVersion // this matches slf4j-api in jgit's dependencies val slf4jSimple = "org.slf4j" % "slf4j-simple" % "1.7.36" val scalaCollectionPlus = "com.madgag" %% "scala-collection-plus" % "0.11" val parCollections = "org.scala-lang.modules" %% "scala-parallel-collections" % "1.2.0" val scalaGit = "com.madgag.scala-git" %% "scala-git" % scalaGitVersion exclude("org.eclipse.jgit", "org.eclipse.jgit") val scalaGitTest = "com.madgag.scala-git" %% "scala-git-test" % scalaGitVersion val scalatest = "org.scalatest" %% "scalatest" % "3.2.19" val madgagCompress = "com.madgag" % "util-compress" % "1.35" val textmatching = "com.madgag" %% "scala-textmatching" % "2.8" val scopt = "com.github.scopt" %% "scopt" % "3.7.1" val guava = Seq("com.google.guava" % "guava" % "33.4.0-jre", "com.google.code.findbugs" % "jsr305" % "3.0.2") val useNewerJava = "com.madgag" % "use-newer-java" % "1.0.2" val lineSplitting = "com.madgag" %% "line-break-preserving-line-splitting" % "0.1.6" } ================================================ FILE: project/plugins.sbt ================================================ addSbtPlugin("com.github.sbt" % "sbt-release" % "1.4.0") addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.12.2") addSbtPlugin("ch.epfl.scala" % "sbt-version-policy" % "3.2.1") addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.3.0") addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.13.1") addDependencyTreePlugin ================================================ FILE: version.sbt ================================================ ThisBuild / version := "1.15.1-SNAPSHOT"