[
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "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):\n\n_(choose 1 of these 2 options)_\n\n- [ ] I assign the copyright on this contribution to Roberto Tyley\n- [ ] I disclaim copyright and thus place this contribution in the public domain\n\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\non:\n  workflow_dispatch:\n  pull_request:\n\n  # triggering CI default branch improves caching\n  # see https://docs.github.com/en/free-pro-team@latest/actions/guides/caching-dependencies-to-speed-up-workflows#restrictions-for-accessing-a-cache\n  push:\n    branches:\n      - main\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: guardian/setup-scala@v1\n      - name: Build and Test\n        run: sbt -v test\n      - name: Test Summary\n        uses: test-summary/action@v2\n        with:\n          paths: \"test-results/**/TEST-*.xml\"\n        if: always()"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: Release\n\non:\n  workflow_dispatch:\n\njobs:\n  release:\n    uses: guardian/gha-scala-library-release-workflow/.github/workflows/reusable-release.yml@v1\n    permissions: { contents: write, pull-requests: write }\n    with:\n      GITHUB_APP_ID: 930725\n      SONATYPE_PROFILE_NAME: 'com.madgag'\n      SONATYPE_CREDENTIAL_HOST: 's01.oss.sonatype.org'\n    secrets:\n      SONATYPE_TOKEN: ${{ secrets.AUTOMATED_MAVEN_RELEASE_SONATYPE_TOKEN }}\n      PGP_PRIVATE_KEY: ${{ secrets.AUTOMATED_MAVEN_RELEASE_PGP_SECRET }}\n      GITHUB_APP_PRIVATE_KEY: ${{ secrets.AUTOMATED_MAVEN_RELEASE_GITHUB_APP_PRIVATE_KEY }}\n"
  },
  {
    "path": ".gitignore",
    "content": "target\n*~\n.idea\n.idea_modules\n*.iml\n*.jar\nrepo.git.zip\n**/.project\n**/.classpath\n**/.settings\n.bsp\n\n.DS_Store\ntest-results/\n"
  },
  {
    "path": ".tool-versions",
    "content": "java corretto-11.0.25.9.1\n"
  },
  {
    "path": "BUILD.md",
    "content": "The BFG is written in Scala, a modern functional language that runs on the JVM - so it\ncan run anywhere Java can.\n\nHere's a rough set of instructions for building the BFG, if you don't want to use the\npre-built [downloads](http://rtyley.github.io/bfg-repo-cleaner/#download):\n\n* Install Java JDK 11 or above\n* Install [sbt](https://www.scala-sbt.org/1.x/docs/Setup.html)\n* `git clone git@github.com:rtyley/bfg-repo-cleaner.git`\n* `cd bfg-repo-cleaner`\n* `sbt`<- start the sbt console\n* `bfg/assembly` <- download dependencies, run the tests, build the jar\n\nTo find the jar once it's built, just look at the last few lines of output from the\n`assembly` task - it'll say something like this:\n\n```\n[info] Packaging /Users/roberto/development/bfg-repo-cleaner/bfg/target/bfg-1.11.9-SNAPSHOT-master-21d2115.jar ...\n[info] Done packaging.\n[success] Total time: 19 s, completed 26-Sep-2014 16:05:11\n```\n\nIf you're going to make changes to the Scala code, you may want to use IntelliJ and it's Scala\nplugin to help with the Scala syntax...!\n\nIf you use [Eclipse IDE](http://www.eclipse.org/), you can set-up your development environment by following these instructions:\n\n* Install `sbt` and build as-above\n* Install [Scala IDE for Eclipse](http://scala-ide.org/) into your Eclipse installation if not already installed\n* Add the `sbteclipse-plugin` to your set of local sbt plugins:\n\n```\nmkdir -p ~/.sbt/1.0/plugins && tee ~/.sbt/1.0/plugins/plugins.sbt <<EOF\naddSbtPlugin(\"com.typesafe.sbteclipse\" % \"sbteclipse-plugin\" % \"5.2.2\")\nEOF\n```\n\n* `sbt`<- start the sbt console\n* `eclipse` <- first-time only setup of the Eclipse plugin\n* `eclipse` <- again, generate Eclipse project files (note that these are `.gitignore`d)\n* In Eclipse, `File -> Import -> Existing Projects into Workspace`, browse to your `bfg` working-copy, and ensure that you select `Search for nested projects`\n* You should now have the 4 `sbt` projects imported into your Eclipse workspace.\n\nI personally found Coursera's [online Scala course](https://www.coursera.org/course/progfun) very helpful in\nlearning Scala, YMMV.\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "Issues and Questions\n--------------------\n\nIf you've found what looks like a bug, or have a feature request for the BFG, please check\n[issues on GitHub](https://github.com/rtyley/bfg-repo-cleaner/issues), and create a new issue\nif necessary.\n\nIf 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\n[`bfg-repo-cleaner`](http://stackoverflow.com/questions/tagged/bfg-repo-cleaner) so I see it) - there are\nmany more people who can answer that sort of question on Stackoverflow, you stand a good chance\nof getting your question answered quicker!\n\nPull Requests\n-------------\n\nBFG 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:\n\na) Assign the copyright on the contribution to myself, Roberto Tyley\n\n**or**\n\nb) Disclaim copyright on it and thus put it in the public domain\n\n**Please specify which option you want to use when creating your pull request.**\n\nSee 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.\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "BFG Repo-Cleaner \n================\n\n[![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)\n[![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)\n\n_Removes large or troublesome blobs like git-filter-branch does, but faster - and written in Scala_ - [Fund the BFG](https://j.mp/fund-bfg)\n\n```\n$ bfg --strip-blobs-bigger-than 1M --replace-text banned.txt repo.git\n```\n\nThe BFG is a simpler, faster ([10 - 720x](https://docs.google.com/spreadsheet/ccc?key=0AsR1d5Zpes8HdER3VGU1a3dOcmVHMmtzT2dsS2xNenc) faster)\nalternative to `git-filter-branch` for cleansing bad data out of your Git repository:\n\n* Removing **Crazy Big Files**\n* Removing **Passwords, Credentials** & other **Private data**\n\nMain documentation for The BFG is here : **https://rtyley.github.io/bfg-repo-cleaner/**\n"
  },
  {
    "path": "backers.md",
    "content": "Many thanks to supporters of the BFG!\n-----\n\nContribute towards the open-source development of the BFG on [**BountySource**](https://www.bountysource.com/teams/bfg-repo-cleaner)\n\n* [Thomas Ferris Nicolaisen](http://www.tfnico.com/) - host of the excellent [GitMinutes](http://www.gitminutes.com) podcast\n* [Alec Clews](https://alecthegeek.github.io/)\n* [ramtej](https://github.com/ramtej)\n"
  },
  {
    "path": "bfg/build.sbt",
    "content": "import java.io.{File, FileOutputStream}\n\nimport Dependencies.*\nimport sbt.taskKey\n\nimport scala.sys.process.Process\nimport scala.util.Try\n\nval gitDescription = taskKey[String](\"Git description of working dir\")\n\ngitDescription := Try[String](Process(\"git describe --all --always --dirty --long\").lineStream.head.replace(\"heads/\",\"\").replace(\"-0-g\",\"-\")).getOrElse(\"unknown\")\n\nlibraryDependencies += useNewerJava\n\nmainClass := Some(\"use.newer.java.Version8\")\nCompile / packageBin / packageOptions +=\n  Package.ManifestAttributes( \"Main-Class-After-UseNewerJava-Check\" -> \"com.madgag.git.bfg.cli.Main\" )\n\n// note you don't want the jar name to collide with the non-assembly jar, otherwise confusion abounds.\nassembly / assemblyJarName := s\"${name.value}-${version.value}-${gitDescription.value}${jgitVersionOverride.map(\"-jgit-\" + _).mkString}.jar\"\n\nassembly / assemblyMergeStrategy := {\n  case PathList(\"META-INF\", \"versions\", \"9\", \"module-info.class\") => MergeStrategy.discard\n  case x =>\n    val oldStrategy = (assembly / assemblyMergeStrategy).value\n    oldStrategy(x)\n}\n\nbuildInfoKeys := Seq[BuildInfoKey](version, scalaVersion, gitDescription)\n\nbuildInfoPackage := \"com.madgag.git.bfg\"\n\ncrossPaths := false\n\nCompile / packageBin / publishArtifact := false\n\n// replace the conventional main artifact with an uber-jar\naddArtifact(Compile / packageBin / artifact, assembly)\n\nval cliUsageDump = taskKey[File](\"Dump the CLI 'usage' output to a file\")\n\ncliUsageDump := {\n  val usageDumpFile = File.createTempFile(\"bfg-usage\", \"dump.txt\")\n  val scalaRun = new ForkRun(ForkOptions().withOutputStrategy(CustomOutput(new FileOutputStream(usageDumpFile))))\n\n  val mainClassName = (Compile / run / mainClass).value getOrElse sys.error(\"No main class detected.\")\n  val classpath = Attributed.data((Runtime / fullClasspath).value)\n  val args = Seq.empty\n\n  scalaRun.run(mainClassName, classpath, args, streams.value.log).failed foreach (sys error _.getMessage)\n  usageDumpFile\n}\n\naddArtifact( Artifact(\"bfg\", \"usage\", \"txt\"), cliUsageDump )\n\nlibraryDependencies ++= Seq(\n  scopt,\n  jgit,\n  scalaGitTest % \"test\"\n)\n\nimport Tests.*\n{\n  def isolateTestsWhichRequireTheirOwnJvm(tests: Seq[TestDefinition]) = {\n    val (testsRequiringIsolation, testsNotNeedingIsolation) = tests.partition(_.name.contains(\"RequiresOwnJvm\"))\n\n    val groups: Seq[Seq[TestDefinition]] = testsRequiringIsolation.map(Seq(_)) :+ testsNotNeedingIsolation\n\n    groups map { group =>\n      Group(group.size.toString, group, SubProcess(ForkOptions()))\n    }\n  }\n\n  Test / testGrouping := isolateTestsWhichRequireTheirOwnJvm( (Test / definedTests).value )\n}\n\nTest / fork := true // JGit uses static (ie JVM-wide) config\n\nTest / logBuffered := false\n\nTest / parallelExecution := false\n\n"
  },
  {
    "path": "bfg/src/main/scala/com/madgag/git/bfg/cli/CLIConfig.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cli\n\nimport com.madgag.git.bfg.BuildInfo\nimport com.madgag.git.bfg.GitUtil._\nimport com.madgag.git.bfg.cleaner._\nimport com.madgag.git.bfg.cleaner.kit.BlobInserter\nimport com.madgag.git.bfg.cleaner.protection.ProtectedObjectCensus\nimport com.madgag.git.bfg.model.FileName.ImplicitConversions._\nimport com.madgag.git.bfg.model.{FileName, Tree, TreeBlobEntry, TreeBlobs, TreeSubtrees}\nimport com.madgag.git.{SizedObject, _}\nimport com.madgag.inclusion.{IncExcExpression, _}\nimport com.madgag.text.ByteSize\nimport com.madgag.textmatching.{Glob, TextMatcher, TextMatcherType, TextReplacementConfig}\nimport org.eclipse.jgit.internal.storage.file.FileRepository\nimport org.eclipse.jgit.lib._\nimport org.eclipse.jgit.storage.file.FileRepositoryBuilder\nimport scopt.{OptionParser, Read}\n\nimport java.io.File\nimport java.nio.file.Files\nimport scala.jdk.CollectionConverters._\n\n\nobject CLIConfig {\n  val parser = new OptionParser[CLIConfig](\"bfg\") {\n\n    def fileMatcher(name: String, defaultType: TextMatcherType = Glob) = {\n      implicit val textMatcherRead: Read[TextMatcher] = Read.reads { TextMatcher(_, defaultType) }\n\n      opt[TextMatcher](name).valueName(s\"<${defaultType.expressionPrefix}>\").validate { m =>\n        if (m.expression.contains('/')) {\n          failure(\"*** Can only match on filename, NOT path *** - remove '/' path segments\")\n        } else success\n      }\n    }\n\n    def readLinesFrom(v: File): Seq[String] = Files.readAllLines(v.toPath).asScala.toSeq\n\n    val exactVersion = BuildInfo.version + (if (BuildInfo.version.contains(\"-SNAPSHOT\")) s\" (${BuildInfo.gitDescription})\" else \"\")\n\n    head(\"bfg\", exactVersion)\n    version(\"version\").hidden()\n\n    opt[String]('b', \"strip-blobs-bigger-than\").valueName(\"<size>\").text(\"strip blobs bigger than X (eg '128K', '1M', etc)\").action {\n      (v , c) => c.copy(stripBlobsBiggerThan = Some(ByteSize.parse(v)))\n    }\n    opt[Int]('B', \"strip-biggest-blobs\").valueName(\"NUM\").text(\"strip the top NUM biggest blobs\").action {\n      (v, c) => c.copy(stripBiggestBlobs = Some(v))\n    }\n    opt[File](\"strip-blobs-with-ids\").abbr(\"bi\").valueName(\"<blob-ids-file>\").text(\"strip blobs with the specified Git object ids\").action {\n      (v, c) =>\n        c.copy(stripBlobsWithIds = Some(readLinesFrom(v).map(_.trim).filterNot(_.isEmpty).map(_.asObjectId).toSet))\n    }\n    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 {\n      (v, c) => c.copy(deleteFiles = Some(v))\n    }\n    fileMatcher(\"delete-folders\").text(\"delete folders with the specified names (eg '.svn', '*-tmp' - matches on folder name, not path within repo)\").action {\n      (v, c) => c.copy(deleteFolders = Some(v))\n    }\n    opt[String](\"convert-to-git-lfs\").text(\"extract files with the specified names (eg '*.zip' or '*.mp4') into Git LFS\").action {\n      (v, c) => c.copy(lfsConversion = Some(v))\n    }\n    opt[File](\"replace-text\").abbr(\"rt\").valueName(\"<expressions-file>\").text(\"filter content of files, replacing matched text. Match expressions should be listed in the file, one expression per line - \" +\n      \"by default, each expression is treated as a literal, but 'regex:' & 'glob:' prefixes are supported, with '==>' to specify a replacement \" +\n      \"string other than the default of '***REMOVED***'.\").action {\n      (v, c) => c.copy(textReplacementExpressions = readLinesFrom(v).filterNot(_.trim.isEmpty))\n    }\n    fileMatcher(\"filter-content-including\").abbr(\"fi\").text(\"do file-content filtering on files that match the specified expression (eg '*.{txt,properties}')\").action {\n      (v, c) => c.copy(filenameFilters = c.filenameFilters :+ Include(v))\n    }\n    fileMatcher(\"filter-content-excluding\").abbr(\"fe\").text(\"don't do file-content filtering on files that match the specified expression (eg '*.{xml,pdf}')\").action {\n      (v, c) => c.copy(filenameFilters = c.filenameFilters :+ Exclude(v))\n    }\n    opt[String](\"filter-content-size-threshold\").abbr(\"fs\").valueName(\"<size>\").text(\"only do file-content filtering on files smaller than <size> (default is %1$d bytes)\".format(CLIConfig().filterSizeThreshold)).action {\n      (v, c) => c.copy(filterSizeThreshold = ByteSize.parse(v))\n    }\n    opt[String]('p', \"protect-blobs-from\").valueName(\"<refs>\").text(\"protect blobs that appear in the most recent versions of the specified refs (default is 'HEAD')\").action {\n      (v, c) => c.copy(protectBlobsFromRevisions = v.split(',').toSet)\n    }\n    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 {\n      (_, c) => c.copy(protectBlobsFromRevisions = Set.empty)\n    }\n    opt[Unit](\"strict-object-checking\").text(\"perform additional checks on integrity of consumed & created objects\").hidden().action {\n      (_, c) => c.copy(strictObjectChecking = true)\n    }\n    opt[Unit](\"private\").text(\"treat this repo-rewrite as removing private data (for example: omit old commit ids from commit messages)\").action {\n      (_, c) => c.copy(sensitiveData = Some(true))\n    }\n    opt[String](\"massive-non-file-objects-sized-up-to\").valueName(\"<size>\").text(\"increase memory usage to handle over-size Commits, Tags, and Trees that are up to X in size (eg '10M')\").action {\n      (v, c) => c.copy(massiveNonFileObjects = Some(ByteSize.parse(v)))\n    }\n    opt[String](\"fix-filename-duplicates-preferring\").valueName(\"<filemode>\").text(\"Fix corrupt trees which contain multiple entries with the same filename, favouring the 'tree' or 'blob'\").hidden().action {\n      (v, c) =>\n        val preferredFileMode = v.toLowerCase match {\n          case \"tree\" | \"folder\" => FileMode.TREE\n          case \"blob\" | \"file\" => FileMode.REGULAR_FILE\n          case other => throw new IllegalArgumentException(s\"'$other' should be 'tree' or 'blob'\")\n        }\n        val ord: Option[Ordering[FileMode]] = Some(Ordering.by[FileMode, Int](filemode => if (filemode==preferredFileMode) 0 else 1))\n\n        c.copy(fixFilenameDuplicatesPreferring = ord)\n    }\n    arg[File](\"<repo>\").optional().action { (x, c) =>\n      c.copy(repoLocation = x) } text(\"file path for Git repository to clean\")\n  }\n}\n\ncase class CLIConfig(stripBiggestBlobs: Option[Int] = None,\n                     stripBlobsBiggerThan: Option[Long] = None,\n                     protectBlobsFromRevisions: Set[String] = Set(\"HEAD\"),\n                     deleteFiles: Option[TextMatcher] = None,\n                     deleteFolders: Option[TextMatcher] = None,\n                     fixFilenameDuplicatesPreferring: Option[Ordering[FileMode]] = None,\n                     filenameFilters: Seq[Filter[String]] = Nil,\n                     filterSizeThreshold: Long = BlobTextModifier.DefaultSizeThreshold,\n                     textReplacementExpressions: Iterable[String] = List.empty,\n                     stripBlobsWithIds: Option[Set[ObjectId]] = None,\n                     lfsConversion: Option[String] = None,\n                     strictObjectChecking: Boolean = false,\n                     sensitiveData: Option[Boolean] = None,\n                     massiveNonFileObjects: Option[Long] = None,\n                     repoLocation: File = new File(System.getProperty(\"user.dir\"))) {\n\n  lazy val gitdir = resolveGitDirFor(repoLocation)\n\n  implicit lazy val repo: FileRepository = FileRepositoryBuilder.create(gitdir.get).asInstanceOf[FileRepository]\n\n  lazy val objectProtection = ProtectedObjectCensus(protectBlobsFromRevisions)\n\n  lazy val objectChecker = if (strictObjectChecking) Some(new ObjectChecker()) else None\n\n  lazy val fileDeletion: Option[Cleaner[TreeBlobs]] = deleteFiles.map {\n    textMatcher => new FileDeleter(textMatcher)\n  }\n\n  lazy val folderDeletion: Option[Cleaner[TreeSubtrees]] = deleteFolders.map {\n    textMatcher => { subtrees: TreeSubtrees =>\n      TreeSubtrees(subtrees.entryMap.view.filterKeys(filename => !textMatcher(filename)).toMap)\n    }\n  }\n\n  lazy val fixFileNameDuplication: Option[Cleaner[Seq[Tree.Entry]]] = fixFilenameDuplicatesPreferring.map {\n    implicit preferredFileModes =>\n    { treeEntries: Seq[Tree.Entry] => treeEntries.groupBy(_.name).values.map(_.minBy(_.fileMode)).toSeq }\n  }\n\n  lazy val lineModifier: Option[String => String] =\n    TextReplacementConfig(textReplacementExpressions, \"***REMOVED***\")\n\n  lazy val filterContentPredicate: (FileName => Boolean) = f => IncExcExpression(filenameFilters) includes (f.string)\n\n  lazy val blobTextModifier: Option[BlobTextModifier] = lineModifier.map {\n    replacer =>\n      new BlobTextModifier {\n        override val sizeThreshold = filterSizeThreshold\n\n        def lineCleanerFor(entry: TreeBlobEntry) = if (filterContentPredicate(entry.filename)) Some(replacer) else None\n\n        val threadLocalObjectDBResources = repo.getObjectDatabase.threadLocalResources\n      }\n  }\n\n  lazy val lfsBlobConverter: Option[LfsBlobConverter] = lfsConversion.map { lfsGlobExpr =>\n    new LfsBlobConverter(lfsGlobExpr, repo)\n  }\n\n  lazy val privateDataRemoval = sensitiveData.getOrElse(Seq(fileDeletion, folderDeletion, blobTextModifier).flatten.nonEmpty)\n\n  lazy val objectIdSubstitutor = if (privateDataRemoval) ObjectIdSubstitutor.OldIdsPrivate else ObjectIdSubstitutor.OldIdsPublic\n\n  lazy val treeEntryListCleaners = fixFileNameDuplication.toSeq\n\n  lazy val commitNodeCleaners = {\n    lazy val formerCommitFooter = if (privateDataRemoval) None else Some(FormerCommitFooter)\n\n    Seq(new CommitMessageObjectIdsUpdater(objectIdSubstitutor)) ++ formerCommitFooter\n  }\n\n  lazy val treeBlobCleaners: Seq[Cleaner[TreeBlobs]] = {\n\n    lazy val blobsByIdRemover: Option[BlobRemover] = stripBlobsWithIds.map(new BlobRemover(_))\n\n    lazy val blobRemover: Option[Cleaner[TreeBlobs]] = {\n      implicit val progressMonitor: ProgressMonitor = new TextProgressMonitor()\n\n      val sizeBasedBlobTargetSources = Seq(\n        stripBlobsBiggerThan.map(threshold => (s: LazyList[SizedObject]) => s.takeWhile(_.size > threshold)),\n        stripBiggestBlobs.map(num => (s: LazyList[SizedObject]) => s.take(num))\n      ).flatten\n\n      if (sizeBasedBlobTargetSources.isEmpty) None else {\n        val sizedBadIds = sizeBasedBlobTargetSources.flatMap(_(biggestBlobs(repo.getObjectDatabase, progressMonitor))).toSet\n        if (sizedBadIds.isEmpty) {\n          println(\"Warning : no large blobs matching criteria found in packfiles - does the repo need to be packed?\")\n          None\n        } else {\n          println(\"Found \" + sizedBadIds.size + \" blob ids for large blobs - biggest=\" + sizedBadIds.max.size + \" smallest=\" + sizedBadIds.min.size)\n          println(\"Total size (unpacked)=\" + sizedBadIds.map(_.size).sum)\n          Some(new BlobReplacer(sizedBadIds.map(_.objectId), new BlobInserter(repo.getObjectDatabase.threadLocalResources.inserter())))\n        }\n      }\n    }\n\n    Seq(blobsByIdRemover, blobRemover, fileDeletion, blobTextModifier, lfsBlobConverter).flatten\n  }\n\n  lazy val definesNoWork = treeBlobCleaners.isEmpty && folderDeletion.isEmpty && treeEntryListCleaners.isEmpty\n\n  def objectIdCleanerConfig: ObjectIdCleaner.Config =\n    ObjectIdCleaner.Config(\n      objectProtection,\n      objectIdSubstitutor,\n      commitNodeCleaners,\n      treeEntryListCleaners,\n      treeBlobCleaners,\n      folderDeletion.toSeq,\n      objectChecker\n    )\n\n  def describe = {\n    if (privateDataRemoval) {\n      \"is removing private data, so the '\" + FormerCommitFooter.Key + \"' footer will not be added to commit messages.\"\n    } else {\n      \"is only removing non-private data (eg, blobs that are just big, not private) : '\" + FormerCommitFooter.Key + \"' footer will be added to commit messages.\"\n    }\n  }\n}\n"
  },
  {
    "path": "bfg/src/main/scala/com/madgag/git/bfg/cli/Main.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cli\n\nimport com.madgag.git._\nimport com.madgag.git.bfg.GitUtil._\nimport com.madgag.git.bfg.cleaner._\n\nobject Main extends App {\n\n  if (args.isEmpty) {\n    CLIConfig.parser.showUsage()\n  } else {\n\n    CLIConfig.parser.parse(args, CLIConfig()) map {\n      config =>\n\n        tweakStaticJGitConfig(config.massiveNonFileObjects)\n\n        if (config.gitdir.isEmpty) {\n          CLIConfig.parser.showUsage()\n          Console.err.println(\"Aborting : \" + config.repoLocation + \" is not a valid Git repository.\\n\")\n        } else {\n          implicit val repo = config.repo\n\n          println(\"\\nUsing repo : \" + repo.getDirectory.getAbsolutePath + \"\\n\")\n\n          // do this before implicitly initiating big-blob search\n          if (hasBeenProcessedByBFGBefore(repo)) {\n            println(\"\\nThis repo has been processed by The BFG before! Will prune repo before proceeding - to avoid unnecessary cleaning work on unused objects...\")\n            repo.git.gc.call()\n            println(\"Completed prune of old objects - will now proceed with the main job!\\n\")\n          }\n\n          if (config.definesNoWork) {\n            Console.err.println(\"Please specify tasks for The BFG :\")\n            CLIConfig.parser.showUsage()\n          } else {\n            println(\"Found \" + config.objectProtection.fixedObjectIds.size + \" objects to protect\")\n\n            RepoRewriter.rewrite(repo, config.objectIdCleanerConfig)\n            repo.close()\n          }\n        }\n    }\n  }\n\n}"
  },
  {
    "path": "bfg/src/test/scala/com/madgag/git/bfg/cli/CLIConfigSpecs.scala",
    "content": "package com.madgag.git.bfg.cli\n\nimport com.madgag.git.bfg.model.FileName\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\nclass CLIConfigSpecs extends AnyFlatSpec with Matchers {\n\n\n  def parse(args: String) = CLIConfig.parser.parse(args.split(' ') :+ \"my-repo.git\", CLIConfig()).get.filterContentPredicate\n\n  \"CLI config\" should \"understand lone include\" in {\n    val predicate = parse(\"-fi *.txt\")\n    predicate(FileName(\"panda\")) shouldBe false\n    predicate(FileName(\"foo.txt\")) shouldBe true\n    predicate(FileName(\"foo.java\")) shouldBe false\n  }\n\n  it should \"understand lone exclude\" in {\n    val predicate = parse(\"-fe *.txt\")\n    predicate(FileName(\"panda\")) shouldBe true\n    predicate(FileName(\"foo.txt\")) shouldBe false\n    predicate(FileName(\"foo.java\")) shouldBe true\n  }\n\n  it should \"understand include followed by exclude\" in {\n    val predicate = parse(\"-fi *.txt -fe Poison.*\")\n    predicate(FileName(\"panda\")) shouldBe false\n    predicate(FileName(\"foo.txt\")) shouldBe true\n    predicate(FileName(\"foo.java\")) shouldBe false\n    predicate(FileName(\"Poison.txt\")) shouldBe false\n  }\n\n  it should \"understand exclude followed by include\" in {\n    val predicate = parse(\"-fe *.xml -fi hbm.xml\")\n    predicate(FileName(\"panda\")) shouldBe true\n    predicate(FileName(\"foo.xml\")) shouldBe false\n    predicate(FileName(\"hbm.xml\")) shouldBe true\n  }\n\n}\n"
  },
  {
    "path": "bfg/src/test/scala/com/madgag/git/bfg/cli/MainSpec.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cli\n\nimport com.madgag.git._\nimport com.madgag.git.bfg.cli.test.unpackedRepo\nimport com.madgag.git.bfg.model._\nimport org.eclipse.jgit.lib.{ObjectId, ObjectReader}\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\nimport org.scalatest.{Inspectors, OptionValues}\n\nimport java.nio.file.Files\nimport scala.jdk.CollectionConverters._\n\nclass MainSpec extends AnyFlatSpec with Matchers with OptionValues with Inspectors {\n\n  // concurrent testing against scala.App is not safe https://twitter.com/rtyley/status/340376844916387840\n\n  \"CLI\" should \"not change commits unnecessarily\" in new unpackedRepo(\"/sample-repos/exampleWithInitialCleanHistory.git.zip\") {\n    implicit val r: ObjectReader = reader\n\n    ensureInvariantValue(commitHist() take 2) {\n      ensureRemovalFrom(commitHist()).ofCommitsThat(haveCommitWhereObjectIds(contain(abbrId(\"294f\")))) {\n        run(\"--strip-blobs-bigger-than 1K\")\n      }\n    }\n  }\n\n\n  \"removing empty trees\" should \"work\" in new unpackedRepo(\"/sample-repos/folder-example.git.zip\") {\n    ensureRemovalFrom(commitHist()).ofCommitsThat(haveFolder(\"secret-files\")) {\n      run(\"--delete-files {credentials,passwords}.txt\")\n    }\n  }\n\n  \"removing big blobs\" should \"definitely still remove blobs even if they have identical size\" in new unpackedRepo(\"/sample-repos/moreThanOneBigBlobWithTheSameSize.git.zip\") {\n    ensureRemovalOfBadEggs(packedBlobsOfSize(1024), (contain allElementsOf Set(abbrId(\"06d7\"), abbrId(\"cb2c\"))).matcher[Iterable[ObjectId]]) {\n      run(\"--strip-blobs-bigger-than 512B\")\n    }\n  }\n\n  \"converting to Git LFS\" should \"create a file in lfs/objects\" in new unpackedRepo(\"/sample-repos/repoWithBigBlobs.git.zip\") {\n    ensureRemovalOfBadEggs(packedBlobsOfSize(11238), (contain only abbrId(\"596c\")).matcher[Iterable[ObjectId]]) {\n      run(\"--convert-to-git-lfs *.png --no-blob-protection\")\n    }\n    val lfsFile = repo.getDirectory.toPath.resolve(Seq(\"lfs\", \"objects\", \"e0\", \"eb\", \"e0ebd49837a1cced34b9e7d3ff2fa68a8100df8f158f165ce139e366a941ba6e\"))\n\n    Files.size(lfsFile) shouldBe 11238\n  }\n\n  \"removing a folder named '.git'\" should \"work\" in new unpackedRepo(\"/sample-repos/badRepoContainingDotGitFolder.git.zip\") {\n    ensureRemovalFrom(commitHist()).ofCommitsThat(haveFolder(\".git\")) {\n      run(\"--delete-folders .git --no-blob-protection\")\n    }\n  }\n\n  \"cleaning\" should \"not crash encountering a protected an annotated tag\" in new unpackedRepo(\"/sample-repos/annotatedTagExample.git.zip\") {\n    ensureInvariantCondition(haveRef(\"chapter1\", haveFile(\"chapter1.txt\"))) {\n      ensureRemovalFrom(commitHist(\"master\")).ofCommitsThat(haveFile(\"chapter2.txt\")) {\n        run(\"--strip-blobs-bigger-than 10B --protect-blobs-from chapter1\")\n      }\n    }\n  }\n\n  \"cleaning\" should \"not crash encountering a protected branch containing a slash in it's name\" in new unpackedRepo(\"/sample-repos/branchNameWithASlash.git.zip\") {\n    ensureInvariantCondition(haveRef(\"feature/slashes-are-ugly\", haveFile(\"bar\"))) {\n      ensureRemovalFrom(commitHist(\"master\")).ofCommitsThat(haveFile(\"bar\")) {\n        run(\"--delete-files bar --protect-blobs-from feature/slashes-are-ugly\")\n      }\n    }\n  }\n\n  \"strip blobs by id\" should \"work\" in new unpackedRepo(\"/sample-repos/example.git.zip\") {\n    implicit val r: ObjectReader = reader\n\n    val badBlobs = Set(abbrId(\"db59\"), abbrId(\"86f9\"))\n    val blobIdsFile = Files.createTempFile(\"test-strip-blobs\",\".ids\")\n    Files.write(blobIdsFile, badBlobs.map(_.name()).asJava)\n\n    ensureRemovalFrom(commitHist()).ofCommitsThat(haveCommitWhereObjectIds(contain(abbrId(\"db59\")))) {\n      run(s\"--strip-blobs-with-ids $blobIdsFile\")\n    }\n  }\n\n  \"deleting a folder\" should \"not crash encountering a submodule\" in new unpackedRepo(\"/sample-repos/usedToHaveASubmodule.git.zip\") {\n    ensureInvariantCondition(haveRef(\"master\", haveFile(\"alpha\"))) {\n      ensureRemovalFrom(commitHist()).ofCommitsThat(haveFolder(\"shared\")) {\n        run(\"--delete-folders shared\")\n      }\n    }\n  }\n\n  \"deleting\" should \"not crash encountering a protected submodule\" in new unpackedRepo(\"/sample-repos/unwantedSubmodule.git.zip\") {\n    ensureRemovalFrom(commitHist()).ofCommitsThat(haveFile(\"foo.txt\")) {\n      run(\"--delete-folders bar --delete-files foo.txt\")\n    }\n  }\n\n  \"deleting\" should \"not crash on encountering a commit with bad encoding header\" in new unpackedRepo(\"/sample-repos/badEncoding.git.zip\") {\n    ensureRemovalFrom(commitHist()).ofCommitsThat(haveFile(\"test.txt\")) {\n      run(\"--no-blob-protection --delete-files test.txt\")\n    }\n  }\n\n  \"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\") {\n    ensureRemovalFrom(commitHist()).ofCommitsThat(haveFile(\"2.0.0\")) {\n      run(\"--fix-filename-duplicates-preferring tree\")\n    }\n  }\n}\n\n"
  },
  {
    "path": "bfg/src/test/scala/com/madgag/git/bfg/cli/MassiveNonFileObjectsRequiresOwnJvmSpec.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cli\n\nimport com.madgag.git.bfg.cli.test.unpackedRepo\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\n// JGit has JVM-wide configuration for cache window size: https://git.eclipse.org/r/#/q/Ibf2ef604bac08885b2b3bd85f0dc31995132b682,n,z\nclass MassiveNonFileObjectsRequiresOwnJvmSpec extends AnyFlatSpec with Matchers {\n\n  // concurrent testing against scala.App is not safe https://twitter.com/rtyley/status/340376844916387840\n\n  \"Massive commit messages\" should \"be handled without crash (ie LargeObjectException) if the user specifies that the repo contains massive non-file objects\" in\n    new unpackedRepo(\"/sample-repos/huge10MBCommitMessage.git.zip\") {\n      ensureRemovalFrom(commitHist(\"master\")).ofCommitsThat(haveFile(\"16-kb-zeros\")) {\n        run(\"--strip-blobs-bigger-than 1K --massive-non-file-objects-sized-up-to 20M\")\n      }\n    }\n\n}\n"
  },
  {
    "path": "bfg/src/test/scala/com/madgag/git/bfg/cli/test/unpackedRepo.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cli.test\n\nimport com.madgag.git.bfg\nimport com.madgag.git.bfg.cli.Main\n\nclass unpackedRepo(filePath: String) extends bfg.test.unpackedRepo(filePath) {\n  def run(options: String): Unit = {\n    Main.main(options.split(' ') :+ repo.getDirectory.getAbsolutePath)\n  }\n}"
  },
  {
    "path": "bfg-benchmark/build.sbt",
    "content": "import Dependencies.*\n\nlibraryDependencies ++= guava ++ Seq(\n  madgagCompress,\n  textmatching,\n  scopt\n)"
  },
  {
    "path": "bfg-benchmark/resources/jars/grabJars.sh",
    "content": "#!/bin/bash\nfor i in 4.0 5.0 6.0 7.0 12.0 13.0 13.1 13.2\ndo\n\tVERSION=\"1.$i\"\n\tcurl -O \"https://repo1.maven.org/maven2/com/madgag/bfg/$VERSION/bfg-$VERSION.jar\"\ndone\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/chromium-src/commands/issue-23/bfg.txt",
    "content": "--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}\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/gcc/commands/delete-file/bfg.txt",
    "content": "-D README-fixinc\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/gcc/commands/delete-file/gfb.txt",
    "content": "--index-filter\ngit rm --cached --ignore-unmatch gcc/README-fixinc\n--prune-empty\n--tag-name-filter\ncat\n--\n--all\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/git/commands/delete-file/bfg.txt",
    "content": "-D object.c\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/git/commands/delete-file/gfb.txt",
    "content": "--index-filter\ngit rm --cached --ignore-unmatch object.c\n--prune-empty\n--tag-name-filter\ncat\n--\n--all\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/github-gem/commands/delete-file/bfg.txt",
    "content": "-D Rakefile\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/github-gem/commands/delete-file/gfb.txt",
    "content": "--index-filter\ngit rm --cached --ignore-unmatch Rakefile\n--prune-empty\n--tag-name-filter\ncat\n--\n--all\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/intellij/commands/delete-binary-resources/bfg.txt",
    "content": "--delete-files *.{zip,jar} --no-blob-protection\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/intellij/commands/delete-file/bfg.txt",
    "content": "-D breakgen.dll\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/intellij/commands/delete-file/gfb.txt",
    "content": "--index-filter\ngit rm --cached --ignore-unmatch bin/breakgen.dll\n--prune-empty\n--tag-name-filter\ncat\n--\n--all\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/intellij/commands/git-lfs-binary-resources/bfg.txt",
    "content": "--convert-to-git-lfs *.{zip,jar,exe,dll} --no-blob-protection\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/jgit/commands/delete-file/bfg.txt",
    "content": "-D make_jgit.sh\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/jgit/commands/delete-file/gfb.txt",
    "content": "--index-filter\ngit rm --cached --ignore-unmatch make_jgit.sh\n--prune-empty\n--tag-name-filter\ncat\n--\n--all\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/jgit/commands/replace-1-existing-string/bfg.txt",
    "content": "--replace-text passwords.1-existing-string.txt\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/jgit/commands/replace-1-existing-string/passwords.1-existing-string.txt",
    "content": "invalidAdvertisementOf\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/jgit/commands/replace-20-existing-strings/bfg.txt",
    "content": "--replace-text passwords.20-existing-strings.txt\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/jgit/commands/replace-20-existing-strings/passwords.20-existing-strings.txt",
    "content": "invalidAdvertisementOf\nabbreviationLengthMustBeNonNegative\nabortingRebase\nabortingRebaseFailed\nabortingRebaseFailedNoOrigHead\nadvertisementCameBefore\nadvertisementOfCameBefore\namazonS3ActionFailed\namazonS3ActionFailedGivingUp\nambiguousObjectAbbreviation\naNewObjectIdIsRequired\nanExceptionOccurredWhileTryingToAddTheIdOfHEAD\nanSSHSessionHasBeenAlreadyCreated\napplyingCommitnvalidType\ncorruptObjectInvalidType2\ncorruptObjectMalformedHeader\ndirCacheIsNotLocked\nDIRCChecksumMismatch\nenumValueNotSupported3\nerrorDecodingFromFile\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/jgit/commands/replace-500-existing-strings/bfg.txt",
    "content": "--replace-text passwords.500-existing-strings.txt\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/jgit/commands/replace-500-existing-strings/passwords.500-existing-strings.txt",
    "content": "abbreviationLengthMustBeNonNegative\nabortingRebase\nabortingRebaseFailed\nabortingRebaseFailedNoOrigHead\nadvertisementCameBefore\nadvertisementOfCameBefore\namazonS3ActionFailed\namazonS3ActionFailedGivingUp\nambiguousObjectAbbreviation\naNewObjectIdIsRequired\nanExceptionOccurredWhileTryingToAddTheIdOfHEAD\nanSSHSessionHasBeenAlreadyCreated\napplyingCommit\narchiveFormatAlreadyAbsent\narchiveFormatAlreadyRegistered\natLeastOnePathIsRequired\natLeastOnePatternIsRequired\natLeastTwoFiltersNeeded\nauthenticationNotSupported\nbadBase64InputCharacterAt\nbadEntryDelimiter\nbadEntryName\nbadEscape\nbadGroupHeader\nbadObjectType\nbadSectionEntry\nbareRepositoryNoWorkdirAndIndex\nbase64InputNotProperlyPadded\nbaseLengthIncorrect\nbitmapMissingObject\nbitmapsMustBePrepared\nblameNotCommittedYet\nblobNotFound\nblobNotFoundForPath\nbranchNameInvalid\nbuildingBitmaps\ncachedPacksPreventsIndexCreation\ncachedPacksPreventsListingObjects\ncannotBeCombined\ncannotBeRecursiveWhenTreesAreIncluded\ncannotCombineSquashWithNoff\ncannotCombineTreeFilterWithRevFilter\ncannotCommitOnARepoWithState\ncannotCommitWriteTo\ncannotConnectPipes\ncannotConvertScriptToText\ncannotCreateConfig\ncannotCreateDirectory\ncannotCreateHEAD\ncannotCreateIndexfile\ncannotDeleteCheckedOutBranch\ncannotDeleteFile\ncannotDeleteStaleTrackingRef\ncannotDeleteStaleTrackingRef2\ncannotDetermineProxyFor\ncannotDownload\ncannotExecute\ncannotGet\ncannotListRefs\ncannotLock\ncannotLockPackIn\ncannotMatchOnEmptyString\ncannotMoveIndexTo\ncannotMovePackTo\ncannotOpenService\ncannotParseDate\ncannotParseGitURIish\ncannotPullOnARepoWithState\ncannotRead\ncannotReadBlob\ncannotReadCommit\ncannotReadFile\ncannotReadHEAD\ncannotReadObject\ncannotReadTree\ncannotRebaseWithoutCurrentHead\ncannotResolveLocalTrackingRefForUpdating\ncannotStoreObjects\ncannotUnloadAModifiedTree\ncannotWorkWithOtherStagesThanZeroRightNow\ncanOnlyCherryPickCommitsWithOneParent\ncanOnlyRevertCommitsWithOneParent\ncantFindObjectInReversePackIndexForTheSpecifiedOffset\ncantPassMeATree\nchannelMustBeInRange0_255\ncharacterClassIsNotSupported\ncheckoutConflictWithFile\ncheckoutConflictWithFiles\ncheckoutUnexpectedResult\nclassCastNotA\ncloneNonEmptyDirectory\ncollisionOn\ncommandWasCalledInTheWrongState\ncommitAlreadyExists\ncommitMessageNotSpecified\ncommitOnRepoWithoutHEADCurrentlyNotSupported\ncommitAmendOnInitialNotPossible\ncompressingObjects\nconnectionFailed\nconnectionTimeOut\ncontextMustBeNonNegative\ncorruptionDetectedReReadingAt\ncorruptObjectBadStream\ncorruptObjectBadStreamCorruptHeader\ncorruptObjectGarbageAfterSize\ncorruptObjectIncorrectLength\ncorruptObjectInvalidEntryMode\ncorruptObjectInvalidMode\ncorruptObjectInvalidMode2\ncorruptObjectInvalidMode3\ncorruptObjectInvalidType\ncorruptObjectInvalidType2\ncorruptObjectMalformedHeader\ncorruptObjectNegativeSize\ncorruptObjectNoAuthor\ncorruptObjectNoCommitter\ncorruptObjectNoHeader\ncorruptObjectNoObject\ncorruptObjectNoTaggerBadHeader\ncorruptObjectNoTaggerHeader\ncorruptObjectNoTagName\ncorruptObjectNotree\ncorruptObjectNoType\ncorruptObjectPackfileChecksumIncorrect\ncouldNotCheckOutBecauseOfConflicts\ncouldNotDeleteLockFileShouldNotHappen\ncouldNotDeleteTemporaryIndexFileShouldNotHappen\ncouldNotGetAdvertisedRef\ncouldNotGetRepoStatistics\ncouldNotLockHEAD\ncouldNotReadIndexInOneGo\ncouldNotReadObjectWhileParsingCommit\ncouldNotRenameDeleteOldIndex\ncouldNotRenameTemporaryFile\ncouldNotRenameTemporaryIndexFileToIndex\ncouldNotURLEncodeToUTF8\ncouldNotWriteFile\ncountingObjects\ncreateBranchFailedUnknownReason\ncreateBranchUnexpectedResult\ncreateNewFileFailed\ncredentialPassword\ncredentialUsername\ndaemonAlreadyRunning\ndaysAgo\ndeleteBranchUnexpectedResult\ndeleteFileFailed\ndeleteTagUnexpectedResult\ndeletingNotSupported\ndestinationIsNotAWildcard\ndetachedHeadDetected\ndirCacheDoesNotHaveABackingFile\ndirCacheFileIsNotLocked\ndirCacheIsNotLocked\nDIRCChecksumMismatch\nDIRCExtensionIsTooLargeAt\nDIRCExtensionNotSupportedByThisVersion\nDIRCHasTooManyEntries\nDIRCUnrecognizedExtendedFlags\ndirtyFilesExist\ndoesNotHandleMode\ndownloadCancelled\ndownloadCancelledDuringIndexing\nduplicateAdvertisementsOf\nduplicateRef\nduplicateRemoteRefUpdateIsIllegal\nduplicateStagesNotAllowed\neitherGitDirOrWorkTreeRequired\nemptyCommit\nemptyPathNotPermitted\nencryptionError\nendOfFileInEscape\nentryNotFoundByPath\nenumValueNotSupported2\nenumValueNotSupported3\nenumValuesNotAvailable\nerrorDecodingFromFile\nerrorEncodingFromFile\nerrorInBase64CodeReadingStream\nerrorInPackedRefs\nerrorInvalidProtocolWantedOldNewRef\nerrorListing\nerrorOccurredDuringUnpackingOnTheRemoteEnd\nerrorReadingInfoRefs\nerrorSymlinksNotSupported\nexceptionCaughtDuringExecutionOfAddCommand\nexceptionCaughtDuringExecutionOfArchiveCommand\nexceptionCaughtDuringExecutionOfCherryPickCommand\nexceptionCaughtDuringExecutionOfCommitCommand\nexceptionCaughtDuringExecutionOfFetchCommand\nexceptionCaughtDuringExecutionOfLsRemoteCommand\nexceptionCaughtDuringExecutionOfMergeCommand\nexceptionCaughtDuringExecutionOfPullCommand\nexceptionCaughtDuringExecutionOfPushCommand\nexceptionCaughtDuringExecutionOfResetCommand\nexceptionCaughtDuringExecutionOfRevertCommand\nexceptionCaughtDuringExecutionOfRmCommand\nexceptionCaughtDuringExecutionOfTagCommand\nexceptionOccurredDuringAddingOfOptionToALogCommand\nexceptionOccurredDuringReadingOfGIT_DIR\nexpectedACKNAKFoundEOF\nexpectedACKNAKGot\nexpectedBooleanStringValue\nexpectedCharacterEncodingGuesses\nexpectedEOFReceived\nexpectedGot\nexpectedLessThanGot\nexpectedPktLineWithService\nexpectedReceivedContentType\nexpectedReportForRefNotReceived\nfailedUpdatingRefs\nfailureDueToOneOfTheFollowing\nfailureUpdatingFETCH_HEAD\nfailureUpdatingTrackingRef\nfileCannotBeDeleted\nfileIsTooBigForThisConvenienceMethod\nfileIsTooLarge\nfileModeNotSetForPath\nflagIsDisposed\nflagNotFromThis\nflagsAlreadyCreated\nfunnyRefname\ngcFailed\ngitmodulesNotFound\nheadRequiredToStash\nhoursAgo\nhugeIndexesAreNotSupportedByJgitYet\nhunkBelongsToAnotherFile\nhunkDisconnectedFromFile\nhunkHeaderDoesNotMatchBodyLineCountOf\nillegalArgumentNotA\nillegalCombinationOfArguments\nillegalPackingPhase\nillegalStateExists\nimproperlyPaddedBase64Input\nincorrectHashFor\nincorrectOBJECT_ID_LENGTH\nindexFileIsInUse\nindexFileIsTooLargeForJgit\nindexSignatureIsInvalid\nindexWriteException\ninMemoryBufferLimitExceeded\ninputStreamMustSupportMark\nintegerValueOutOfRange\ninternalRevisionError\ninternalServerError\ninterruptedWriting\ninTheFuture\ninvalidAdvertisementOf\ninvalidAncestryLength\ninvalidBooleanValue\ninvalidChannel\ninvalidCharacterInBase64Data\ninvalidCommitParentNumber\ninvalidEncryption\ninvalidGitdirRef \ninvalidGitType\ninvalidId\ninvalidIdLength\ninvalidIntegerValue\ninvalidKey\ninvalidLineInConfigFile\ninvalidModeFor\ninvalidModeForPath\ninvalidObject\ninvalidOldIdSent\ninvalidPacketLineHeader\ninvalidPath\ninvalidReflogRevision\ninvalidRefName\ninvalidRemote\ninvalidStageForPath\ninvalidTagOption\ninvalidTimeout\ninvalidURL\ninvalidWildcards\ninvalidRefSpec\ninvalidWindowSize\nisAStaticFlagAndHasNorevWalkInstance\nJRELacksMD5Implementation\nkNotInRange\nlargeObjectExceedsByteArray\nlargeObjectExceedsLimit\nlargeObjectException\nlargeObjectOutOfMemory\nlengthExceedsMaximumArraySize\nlistingAlternates\nlocalObjectsIncomplete\nlocalRefIsMissingObjects\nlockCountMustBeGreaterOrEqual1\nlockError\nlockOnNotClosed\nlockOnNotHeld\nmalformedpersonIdentString\nmaxCountMustBeNonNegative\nmergeConflictOnNonNoteEntries\nmergeConflictOnNotes\nmergeStrategyAlreadyExistsAsDefault\nmergeStrategyDoesNotSupportHeads\nmergeUsingStrategyResultedInDescription\nmergeRecursiveReturnedNoCommit\nmergeRecursiveTooManyMergeBasesFor \nmessageAndTaggerNotAllowedInUnannotatedTags \nminutesAgo\nmissingAccesskey\nmissingConfigurationForKey\nmissingDeltaBase\nmissingForwardImageInGITBinaryPatch\nmissingObject\nmissingPrerequisiteCommits\nmissingRequiredParameter\nmissingSecretkey\nmixedStagesNotAllowed\nmkDirFailed\nmkDirsFailed\nmonth\nmonths\nmonthsAgo\nmultipleMergeBasesFor\nneed2Arguments\nneedPackOut\nneedsAtLeastOneEntry\nneedsWorkdir\nnewlineInQuotesNotAllowed\nnoApplyInDelete\nnoClosingBracket\nnoHEADExistsAndNoExplicitStartingRevisionWasSpecified\nnoHMACsupport\nnoMergeBase\nnoMergeHeadSpecified\nnoSuchRef\nnotABoolean\nnotABundle\nnotADIRCFile\nnotAGitDirectory\nnotAPACKFile\nnotARef\nnotASCIIString\nnotAuthorized\nnotAValidPack\nnotFound\nnothingToFetch\nnothingToPush\nnotMergedExceptionMessage\nnoXMLParserAvailable\nobjectAtHasBadZlibStream\nobjectAtPathDoesNotHaveId\nobjectIsCorrupt\nobjectIsNotA\nobjectNotFound\nobjectNotFoundIn\nobtainingCommitsForCherryPick\noffsetWrittenDeltaBaseForObjectNotFoundInAPack\nonlyAlreadyUpToDateAndFastForwardMergesAreAvailable\nonlyOneFetchSupported\nonlyOneOperationCallPerConnectionIsSupported\nopenFilesMustBeAtLeast1\nopeningConnection\noperationCanceled\noutputHasAlreadyBeenStarted\npackChecksumMismatch\npackCorruptedWhileWritingToFilesystem\npackDoesNotMatchIndex\npacketSizeMustBeAtLeast\npacketSizeMustBeAtMost\npackfileCorruptionDetected\npackFileInvalid\npackfileIsTruncated\npackHasUnresolvedDeltas\npackingCancelledDuringObjectsWriting\npackObjectCountMismatch\npackRefs\npackTooLargeForIndexVersion1\npackWriterStatistics\npanicCantRenameIndexFile\npatchApplyException\npatchFormatException\npathIsNotInWorkingDir\npathNotConfigured\npeeledLineBeforeRef\npeerDidNotSupplyACompleteObjectGraph\nprefixRemote\nproblemWithResolvingPushRefSpecsLocally\nprogressMonUploading\npropertyIsAlreadyNonNull\npruneLoosePackedObjects\npruneLooseUnreferencedObjects\npullOnRepoWithoutHEADCurrentlyNotSupported\npullTaskName\npushCancelled\npushIsNotSupportedForBundleTransport\npushNotPermitted\nrawLogMessageDoesNotParseAsLogEntry\nreadingObjectsFromLocalRepositoryFailed\nreadTimedOut\nreceivePackObjectTooLarge1\nreceivePackObjectTooLarge2\nreceivingObjects\nrefAlreadyExists\nrefAlreadyExists1\nreflogEntryNotFound\nrefNotResolved\nrefUpdateReturnCodeWas\nremoteConfigHasNoURIAssociated\nremoteDoesNotHaveSpec\nremoteDoesNotSupportSmartHTTPPush\nremoteHungUpUnexpectedly\nremoteNameCantBeNull\nrenameBranchFailedBecauseTag\nrenameBranchFailedUnknownReason\nrenameBranchUnexpectedResult\nrenameFileFailed\nrenamesAlreadyFound\nrenamesBreakingModifies\nrenamesFindingByContent\nrenamesFindingExact\nrenamesRejoiningModifies\nrepositoryAlreadyExists\nrepositoryConfigFileInvalid\nrepositoryIsRequired\nrepositoryNotFound\nrepositoryState_applyMailbox\nrepositoryState_bisecting\nrepositoryState_conflicts\nrepositoryState_merged\nrepositoryState_normal\nrepositoryState_rebase\nrepositoryState_rebaseInteractive\nrepositoryState_rebaseOrApplyMailbox\nrepositoryState_rebaseWithMerge\nrequiredHashFunctionNotAvailable\nresettingHead\nresolvingDeltas\nresultLengthIncorrect\nrewinding\nsearchForReuse\nsearchForSizes\nsecondsAgo\nselectingCommits\nsequenceTooLargeForDiffAlgorithm\nserviceNotEnabledNoName\nserviceNotPermitted\nserviceNotPermittedNoName\nshallowCommitsAlreadyInitialized\nshortCompressedStreamAt\nshortReadOfBlock\nshortReadOfOptionalDIRCExtensionExpectedAnotherBytes\nshortSkipOfBlock\nsigningNotSupportedOnTag\nsimilarityScoreMustBeWithinBounds\nsizeExceeds2GB\nskipMustBeNonNegative\nsmartHTTPPushDisabled\nsourceDestinationMustMatch\nsourceIsNotAWildcard\nsourceRefDoesntResolveToAnyObject\nsourceRefNotSpecifiedForRefspec\nsquashCommitNotUpdatingHEAD\nstaleRevFlagsOn\nstartingReadStageWithoutWrittenRequestDataPendingIsNotSupported\nstashApplyConflict\nstashApplyConflictInIndex\nstashApplyFailed\nstashApplyOnUnsafeRepository\nstashApplyWithoutHead\nstashCommitMissingTwoParents\nstashDropDeleteRefFailed\nstashDropFailed\nstashDropMissingReflog\nstashFailed\nstashResolveFailed\nstatelessRPCRequiresOptionToBeEnabled\nsubmoduleExists\nsubmoduleParentRemoteUrlInvalid\nsubmodulesNotSupported\nsymlinkCannotBeWrittenAsTheLinkTarget\nsystemConfigFileInvalid\ntagAlreadyExists\ntagNameInvalid\ntagOnRepoWithoutHEADCurrentlyNotSupported\ntheFactoryMustNotBeNull\ntimerAlreadyTerminated\ntopologicalSortRequired\ntransportExceptionBadRef\ntransportExceptionEmptyRef\ntransportExceptionInvalid\ntransportExceptionMissingAssumed\ntransportExceptionReadRef\ntransportNeedsRepository\ntransportProtoAmazonS3\ntransportProtoBundleFile\ntransportProtoFTP\ntransportProtoGitAnon\ntransportProtoHTTP\ntransportProtoLocal\ntransportProtoSFTP\ntransportProtoSSH\ntreeEntryAlreadyExists\ntreeFilterMarkerTooManyFilters\ntreeIteratorDoesNotSupportRemove\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/linux/commands/delete-file/bfg.txt",
    "content": "-D MAINTAINERS\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/linux/commands/delete-file/gfb.txt",
    "content": "--index-filter\ngit rm --cached --ignore-unmatch MAINTAINERS\n--prune-empty\n--tag-name-filter\ncat\n--\n--all\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/rails/commands/delete-file/bfg.txt",
    "content": "-D pushgems.rb\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/rails/commands/delete-file/gfb.txt",
    "content": "--index-filter\ngit rm --cached --ignore-unmatch pushgems.rb\n--prune-empty\n--tag-name-filter\ncat\n--\n--all\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/wine/commands/delete-file/bfg.txt",
    "content": "-D build-spec.txt\n"
  },
  {
    "path": "bfg-benchmark/resources/repos/wine/commands/delete-file/gfb.txt",
    "content": "--index-filter\ngit rm --cached --ignore-unmatch build-spec.txt\n--prune-empty\n--tag-name-filter\ncat\n--\n--all\n"
  },
  {
    "path": "bfg-benchmark/src/main/scala/Benchmark.scala",
    "content": "import lib.Timing.measureTask\nimport lib._\nimport model._\n\nimport java.nio.file.Files\nimport java.nio.file.Files.isDirectory\nimport scala.concurrent.ExecutionContext.Implicits.global\nimport scala.concurrent._\nimport scala.concurrent.duration.Duration\nimport scala.jdk.StreamConverters._\nimport scala.sys.process._\n\n/*\n * Vary BFG runs by:\n * Java version\n * BFG version (JGit version?)\n *\n */\nobject Benchmark extends App {\n\n  BenchmarkConfig.parser.parse(args, BenchmarkConfig()) map {\n    config =>\n      println(s\"Using resources dir : ${config.resourcesDir}\")\n\n      require(Files.exists(config.resourcesDir), s\"Resources dir not found : ${config.resourcesDir}\")\n      require(Files.exists(config.jarsDir), s\"Jars dir not found : ${config.jarsDir}\")\n      require(Files.exists(config.reposDir), s\"Repos dir not found : ${config.reposDir}\")\n\n      val missingJars = config.bfgJars.filterNot(Files.exists(_))\n      require(missingJars.isEmpty, s\"Missing BFG jars : ${missingJars.mkString(\",\")}\")\n\n      val tasksFuture = for {\n        bfgInvocableEngineSet <- bfgInvocableEngineSet(config)\n      } yield {\n        val gfbInvocableEngineSetOpt =\n          Option.when(!config.onlyBfg)(InvocableEngineSet[GFBInvocation](GitFilterBranch, Seq(InvocableGitFilterBranch)))\n        boogaloo(config, new RepoExtractor(config.scratchDir), Seq(bfgInvocableEngineSet) ++ gfbInvocableEngineSetOpt.toSeq)\n      }\n\n      Await.result(tasksFuture, Duration.Inf)\n  }\n\n  def bfgInvocableEngineSet(config: BenchmarkConfig): Future[InvocableEngineSet[BFGInvocation]] = for {\n      javas <- Future.traverse(config.javaCmds)(jc => JavaVersion.version(jc).map(v => Java(jc, v)))\n    } yield {\n      val invocables = for {\n        java <- javas\n        bfgJar <- config.bfgJars\n      } yield InvocableBFG(java, BFGJar.from(bfgJar))\n\n      InvocableEngineSet[BFGInvocation](BFG, invocables)\n    }\n\n  /*\n * A Task says \"here is something you can do to a given repo, and here is how to do\n * it with a BFG, and with git-filter-branch\"\n */\n  def boogaloo(config: BenchmarkConfig, repoExtractor: RepoExtractor, invocableEngineSets: Seq[InvocableEngineSet[_ <: EngineInvocation]]) = {\n\n    for {\n      repoSpecDir <- config.repoSpecDirs\n      availableCommandDirs = Files.list(repoSpecDir.resolve(\"commands\")).toScala(Seq).filter(isDirectory(_))\n      // println(s\"Available commands for $repoName : ${availableCommandDirs.map(_.name).mkString(\", \")}\")\n      commandDir <- availableCommandDirs.filter(p => config.commands(p.getFileName.toString))\n    } yield {\n      val commandName: String = commandDir.getFileName.toString\n      \n      commandName -> (for {\n        invocableEngineSet <- invocableEngineSets\n      } yield for {\n          (invocable, processMaker) <- invocableEngineSet.invocationsFor(commandDir)\n        } yield {\n        val cleanRepoDir = repoExtractor.extractRepoFrom(repoSpecDir.resolve(\"repo.git.zip\"))\n        Files.list(commandDir).toScala(Seq).foreach(p => Files.copy(p, cleanRepoDir.resolve(p.getFileName)))\n        val process = processMaker(cleanRepoDir.toFile)\n\n            val duration = measureTask(s\"$commandName - $invocable\") {\n              process ! ProcessLogger(_ => ())\n            }\n\n            if (config.dieIfTaskTakesLongerThan.exists(_ < duration.toMillis)) {\n              throw new Exception(\"This took too long: \"+duration)\n            }\n\n            invocable -> duration\n      })\n    }\n  }\n\n  println(s\"\\n...benchmark finished.\")\n}\n"
  },
  {
    "path": "bfg-benchmark/src/main/scala/BenchmarkConfig.scala",
    "content": "import java.io.File\nimport com.madgag.textmatching.{Glob, TextMatcher}\nimport scopt.OptionParser\n\nimport java.nio.file.{Path, Paths}\n\nobject BenchmarkConfig {\n  val parser = new OptionParser[BenchmarkConfig](\"benchmark\") {\n    opt[File](\"resources-dir\").text(\"benchmark resources folder - contains jars and repos\").action {\n      (v, c) => c.copy(resourcesDirOption = v.toPath)\n    }\n    opt[String](\"java\").text(\"Java command paths\").action {\n      (v, c) => c.copy(javaCmds = v.split(',').toSeq)\n    }\n    opt[String](\"versions\").text(\"BFG versions to time - bfg-[version].jar - eg 1.4.0,1.5.0,1.6.0\").action {\n      (v, c) => c.copy(bfgVersions = v.split(\",\").toSeq)\n    }\n    opt[Int](\"die-if-longer-than\").text(\"Useful for git-bisect\").action {\n      (v, c) => c.copy(dieIfTaskTakesLongerThan = Some(v))\n    }\n    opt[String](\"repos\").text(\"Sample repos to test, eg github-gems,jgit,git\").action {\n      (v, c) => c.copy(repoNames = v.split(\",\").toSeq)\n    }\n    opt[String](\"commands\").valueName(\"<glob>\").text(\"commands to exercise\").action {\n      (v, c) => c.copy(commands = TextMatcher(v, defaultType = Glob))\n    }\n    opt[File](\"scratch-dir\").text(\"Temp-dir for job runs - preferably ramdisk, eg tmpfs.\").action {\n      (v, c) => c.copy(scratchDir = v.toPath)\n    }\n    opt[Unit](\"only-bfg\") action { (_, c) => c.copy(onlyBfg = true) } text \"Don't benchmark git-filter-branch\"\n  }\n}\ncase class BenchmarkConfig(resourcesDirOption: Path = Paths.get(System.getProperty(\"user.dir\"), \"bfg-benchmark\", \"resources\"),\n                           scratchDir: Path = Paths.get(\"/dev/shm/\"),\n                           javaCmds: Seq[String] = Seq(\"java\"),\n                           bfgVersions: Seq[String] = Seq.empty,\n                           commands: TextMatcher = Glob(\"*\"),\n                           onlyBfg: Boolean = false,\n                           dieIfTaskTakesLongerThan: Option[Int] = None,\n                           repoNames: Seq[String] = Seq.empty) {\n\n  lazy val resourcesDir: Path = resourcesDirOption.toAbsolutePath\n\n  lazy val jarsDir: Path = resourcesDir.resolve(\"jars\")\n\n  lazy val reposDir: Path = resourcesDir.resolve(\"repos\")\n\n  lazy val bfgJars: Seq[Path] = bfgVersions.map(version => jarsDir.resolve(s\"bfg-$version.jar\"))\n\n  lazy val repoSpecDirs: Seq[Path] = repoNames.map(reposDir.resolve)\n}\n"
  },
  {
    "path": "bfg-benchmark/src/main/scala/JavaVersion.scala",
    "content": "import scala.concurrent.ExecutionContext.Implicits.global\nimport scala.concurrent._\nimport scala.sys.process.{Process, ProcessLogger}\n\nobject JavaVersion {\n  val VersionRegex = \"\"\"(?:java|openjdk) version \"(.*?)\"\"\"\".r\n\n  def version(javaCmd: String): Future[String] = {\n    val resultPromise = Promise[String]()\n\n    Future {\n      val exitCode = Process(s\"$javaCmd -version\")!ProcessLogger(\n        s => for (v <-versionFrom(s)) resultPromise.success(v)\n      )\n      resultPromise.tryFailure(new IllegalArgumentException(s\"$javaCmd exited with code $exitCode, no Java version found\"))\n    }\n\n    resultPromise.future\n  }\n\n  def versionFrom(javaVersionLine: String): Option[String] = {\n    VersionRegex.findFirstMatchIn(javaVersionLine).map(_.group(1))\n  }\n}\n"
  },
  {
    "path": "bfg-benchmark/src/main/scala/lib/Repo.scala",
    "content": "package lib\n\nimport com.google.common.io.MoreFiles\nimport com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE\nimport com.madgag.compress.CompressUtil._\n\nimport java.nio.file.{Files, Path}\nimport scala.util.Using\n\nclass RepoExtractor(scratchDir: Path) {\n\n  val repoDir = scratchDir.resolve( \"repo.git\")\n\n  def extractRepoFrom(zipPath: Path) = {\n    if (Files.exists(repoDir)) MoreFiles.deleteRecursively(repoDir, ALLOW_INSECURE)\n\n    Files.createDirectories(repoDir)\n\n    println(s\"Extracting repo to ${repoDir.toAbsolutePath}\")\n\n    Using(Files.newInputStream(zipPath)) {\n      stream => unzip(stream, repoDir.toFile)\n    }\n\n    repoDir\n  }\n}\n"
  },
  {
    "path": "bfg-benchmark/src/main/scala/lib/Timing.scala",
    "content": "package lib\n\nimport java.lang.System._\nimport java.util.concurrent.TimeUnit._\n\nimport scala.concurrent.duration.{Duration, FiniteDuration}\n\nobject Timing {\n\n  def measureTask[T](description: String)(block: => T): Duration = {\n    val start = nanoTime\n    val result = block\n    val duration = FiniteDuration(nanoTime - start, NANOSECONDS)\n    println(s\"$description completed in %,d ms.\".format(duration.toMillis))\n    duration\n  }\n}\n"
  },
  {
    "path": "bfg-benchmark/src/main/scala/model/BFGJar.scala",
    "content": "package model\n\nimport java.nio.file.Path\n\nobject BFGJar {\n  def from(path: Path) = BFGJar(path, Map.empty)\n}\n\ncase class BFGJar(path: Path, mavenDependencyVersions: Map[String, String])\n"
  },
  {
    "path": "bfg-benchmark/src/main/scala/model/InvocableEngine.scala",
    "content": "package model\n\nimport com.google.common.io.CharSource\nimport com.google.common.io.Files.asCharSource\n\nimport java.io.File\nimport java.nio.charset.StandardCharsets.UTF_8\nimport java.nio.file.{Files, Path}\nimport scala.jdk.StreamConverters._\nimport scala.sys.process.{Process, ProcessBuilder}\n\ntrait EngineInvocation\n\ncase class BFGInvocation(args: String) extends EngineInvocation\n\ncase class GFBInvocation(args: Seq[String]) extends EngineInvocation\n\n\ntrait InvocableEngine[InvocationArgs <: EngineInvocation] {\n\n    def processFor(invocation: InvocationArgs)(repoPath: File): ProcessBuilder\n}\n\ncase class InvocableBFG(java: Java, bfgJar: BFGJar) extends InvocableEngine[BFGInvocation] {\n\n  def processFor(invocation: BFGInvocation)(repoPath: File) =\n    Process(s\"${java.javaCmd} -jar ${bfgJar.path} ${invocation.args}\", repoPath)\n\n}\n\nobject InvocableGitFilterBranch extends InvocableEngine[GFBInvocation] {\n\n  def processFor(invocation: GFBInvocation)(repoPath: File) =\n    Process(Seq(\"git\", \"filter-branch\") ++ invocation.args, repoPath)\n}\n\n/*\nWe want to allow the user to vary:\n - BFGs (jars, javas)\n - Tasks (delete a file, replace text) in [selection of repos]\n\n Tasks will have a variety of different invocations for different engines\n */\n\ntrait EngineType[InvocationType <: EngineInvocation] {\n  val configName: String\n\n  def argsFor(config: CharSource): InvocationType\n\n  def argsOptsFor(commandDir: Path): Option[InvocationType] = {\n    val paramsPath = commandDir.resolve(s\"$configName.txt\")\n    if (Files.exists(paramsPath)) Some(argsFor(asCharSource(paramsPath.toFile, UTF_8))) else None\n  }\n}\n\ncase object BFG extends EngineType[BFGInvocation] {\n\n  val configName = \"bfg\"\n\n  def argsFor(config: CharSource) = BFGInvocation(config.read())\n}\n\ncase object GitFilterBranch extends EngineType[GFBInvocation] {\n\n  val configName = \"gfb\"\n\n  def argsFor(config: CharSource) = GFBInvocation(config.lines().toScala(Seq))\n}\n"
  },
  {
    "path": "bfg-benchmark/src/main/scala/model/InvocableEngineSet.scala",
    "content": "package model\n\nimport java.io.File\nimport java.nio.file.Path\n\ncase class InvocableEngineSet[InvocationArgs <: EngineInvocation](\n  engineType: EngineType[InvocationArgs],\n  invocableEngines: Seq[InvocableEngine[InvocationArgs]]\n) {\n\n  def invocationsFor(commandDir: Path): Seq[(InvocableEngine[InvocationArgs], File => scala.sys.process.ProcessBuilder)] = {\n    for {\n      args <- engineType.argsOptsFor(commandDir).toSeq\n      invocable <- invocableEngines\n    } yield (invocable, invocable.processFor(args) _)\n  }\n}\n"
  },
  {
    "path": "bfg-benchmark/src/main/scala/model/Java.scala",
    "content": "package model\n\ncase class Java(javaCmd: String, version: String)\n"
  },
  {
    "path": "bfg-benchmark/src/test/scala/JavaVersionSpec.scala",
    "content": "import org.scalatest.OptionValues\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\nobject JavaVersionSpec extends AnyFlatSpec with OptionValues with Matchers {\n  \"version\" should \"parse an example line\" in {\n    JavaVersion.versionFrom(\"\"\"java version \"1.7.0_51\"\"\"\").value shouldBe \"1.7.0_51\"\n  }\n\n  it should \"parse openjdk weirdness\" in {\n    JavaVersion.versionFrom(\"\"\"openjdk version \"1.8.0_40-internal\"\"\"\").value shouldBe \"1.8.0_40-internal\"\n  }\n}\n"
  },
  {
    "path": "bfg-library/build.sbt",
    "content": "import Dependencies.*\n\nlibraryDependencies ++= guava ++ Seq(\n  parCollections,\n  scalaCollectionPlus,\n  textmatching,\n  scalaGit,\n  jgit,\n  slf4jSimple,\n  lineSplitting,\n  scalaGitTest % Test,\n  \"org.apache.commons\" % \"commons-text\" % \"1.13.0\" % Test\n)\n\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/collection/concurrent/ConcurrentMultiMap.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.collection.concurrent\n\nimport com.madgag.scala.collection.decorators._\n\nclass ConcurrentMultiMap[A, B] {\n\n  val m: collection.concurrent.Map[A, ConcurrentSet[B]] = collection.concurrent.TrieMap.empty\n\n  def addBinding(key: A, value: B): this.type = {\n    val store = m.getOrElse(key, {\n      val freshStore = new ConcurrentSet[B]\n      m.putIfAbsent(key, freshStore).getOrElse(freshStore)\n    })\n    store += value\n    this\n  }\n\n  def toMap: Map[A, Set[B]] = m.toMap.mapV(_.toSet)\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/collection/concurrent/ConcurrentSet.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.collection.concurrent\n\nimport scala.collection.mutable.{AbstractSet, SetOps}\nimport scala.collection.{IterableFactory, IterableFactoryDefaults, mutable}\n\nclass ConcurrentSet[A]()\n  extends AbstractSet[A]\n    with SetOps[A, ConcurrentSet, ConcurrentSet[A]]\n    with IterableFactoryDefaults[A, ConcurrentSet]\n{\n\n  val m: collection.concurrent.Map[A, Boolean] = collection.concurrent.TrieMap.empty\n\n  override def iterableFactory: IterableFactory[ConcurrentSet] = ConcurrentSet\n\n  override def clear(): Unit = m.clear()\n\n  override def addOne(elem: A): ConcurrentSet.this.type = {\n    m.put(elem, true)\n    this\n  }\n\n  override def subtractOne(elem: A): ConcurrentSet.this.type = {\n    m.remove(elem)\n    this\n  }\n\n  override def contains(elem: A): Boolean = m.contains(elem)\n\n  override def iterator: Iterator[A] = m.keysIterator\n\n}\n\nobject ConcurrentSet extends IterableFactory[ConcurrentSet] {\n\n  @transient\n  private final val EmptySet = new ConcurrentSet()\n\n  def empty[A]: ConcurrentSet[A] = EmptySet.asInstanceOf[ConcurrentSet[A]]\n\n  def from[A](source: collection.IterableOnce[A]): ConcurrentSet[A] =\n    source match {\n      case hs: ConcurrentSet[A] => hs\n      case _ if source.knownSize == 0 => empty[A]\n      case _ => (newBuilder[A] ++= source).result()\n    }\n\n  /** Create a new Builder which can be reused after calling `result()` without an\n   * intermediate call to `clear()` in order to build multiple related results.\n   */\n  def newBuilder[A]: mutable.Builder[A, ConcurrentSet[A]] = ???\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/LFS.scala",
    "content": "/*\n * Copyright (c) 2015 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git\n\nimport com.google.common.base.Splitter\nimport com.madgag.git.bfg.model.FileName\nimport org.apache.commons.codec.binary.Hex._\nimport org.eclipse.jgit.lib.ObjectLoader\n\nimport java.nio.charset.Charset\nimport java.nio.charset.StandardCharsets.UTF_8\nimport java.nio.file.{Files, Path}\nimport java.security.{DigestOutputStream, MessageDigest}\nimport scala.jdk.CollectionConverters._\nimport scala.util.Using\n\nobject LFS {\n\n  val ObjectsPath: Seq[String] = Seq(\"lfs\" , \"objects\")\n\n  val PointerCharset: Charset = UTF_8\n\n  case class Pointer(shaHex: String, blobSize: Long) {\n\n    lazy val text: String = s\"\"\"|version https://git-lfs.github.com/spec/v1\n                                |oid sha256:$shaHex\n                                |size $blobSize\n                                |\"\"\".stripMargin\n\n    lazy val bytes: Array[Byte] = text.getBytes(PointerCharset)\n\n    lazy val path: Seq[String] = Seq(shaHex.substring(0, 2), shaHex.substring(2, 4), shaHex)\n  }\n\n  object Pointer {\n\n    val splitter = Splitter.on('\\n').omitEmptyStrings().trimResults().withKeyValueSeparator(' ')\n\n    def parse(bytes: Array[Byte]) = {\n      val text = new String(bytes, PointerCharset)\n      val valuesByKey= splitter.split(text).asScala\n      val size = valuesByKey(\"size\").toLong\n      val shaHex = valuesByKey(\"oid\").stripPrefix(\"sha256:\")\n      Pointer(shaHex, size)\n    }\n  }\n\n  val GitAttributesFileName = FileName(\".gitattributes\")\n\n  def pointerFor(loader: ObjectLoader, tmpFile: Path) = {\n    val digest = MessageDigest.getInstance(\"SHA-256\")\n\n    Using(Files.newOutputStream(tmpFile)) { outStream =>\n      loader.copyTo(new DigestOutputStream(outStream, digest))\n    }\n\n    Pointer(encodeHexString(digest.digest()), loader.getSize)\n  }\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/GitUtil.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg\n\nimport com.google.common.primitives.Ints\nimport com.madgag.git.bfg.cleaner._\nimport com.madgag.git.{SizedObject, _}\nimport org.eclipse.jgit.internal.storage.file.ObjectDirectory\nimport org.eclipse.jgit.lib.Constants.OBJ_BLOB\nimport org.eclipse.jgit.lib.ObjectReader._\nimport org.eclipse.jgit.lib._\nimport org.eclipse.jgit.revwalk.RevWalk\nimport org.eclipse.jgit.storage.file.WindowCacheConfig\n\nimport scala.jdk.CollectionConverters._\nimport scala.jdk.StreamConverters._\nimport scala.language.implicitConversions\n\ntrait CleaningMapper[V] extends Cleaner[V] {\n  def isDirty(v: V) = apply(v) != v\n\n  def substitution(oldId: V): Option[(V, V)] = {\n    val newId = apply(oldId)\n    if (newId == oldId) None else Some((oldId, newId))\n  }\n\n  def replacement(oldId: V): Option[V] = {\n    val newId = apply(oldId)\n    if (newId == oldId) None else Some(newId)\n  }\n}\n\nobject GitUtil {\n  \n  val ProbablyNoNonFileObjectsOverSizeThreshold: Long = 1024 * 1024\n  \n  def tweakStaticJGitConfig(massiveNonFileObjects: Option[Long]): Unit = {\n    val wcConfig: WindowCacheConfig = new WindowCacheConfig()\n    wcConfig.setStreamFileThreshold(Ints.saturatedCast(massiveNonFileObjects.getOrElse(ProbablyNoNonFileObjectsOverSizeThreshold)))\n    wcConfig.install()\n  }\n\n  def hasBeenProcessedByBFGBefore(repo: Repository): Boolean = {\n    // This method just checks the tips of all refs - a good-enough indicator for our purposes...\n    implicit val revWalk = new RevWalk(repo)\n    implicit val objectReader = revWalk.getObjectReader\n\n    repo.getRefDatabase.getRefs().asScala.map(_.getObjectId).filter(_.open.getType == Constants.OBJ_COMMIT)\n      .map(_.asRevCommit).exists(_.getFooterLines(FormerCommitFooter.Key).asScala.nonEmpty)\n  }\n\n  implicit def cleaner2CleaningMapper[V](f: Cleaner[V]): CleaningMapper[V] = new CleaningMapper[V] {\n    def apply(v: V) = f(v)\n  }\n\n  def biggestBlobs(implicit objectDB: ObjectDirectory, progressMonitor: ProgressMonitor = NullProgressMonitor.INSTANCE): LazyList[SizedObject] = {\n    Timing.measureTask(\"Scanning packfile for large blobs\", ProgressMonitor.UNKNOWN) {\n      val reader = objectDB.newReader\n      objectDB.packedObjects.map {\n            objectId =>\n              progressMonitor update 1\n              SizedObject(objectId, reader.getObjectSize(objectId, OBJ_ANY))\n          }.toSeq.sorted.reverse.to(LazyList).filter { oid =>\n        oid.size > ProbablyNoNonFileObjectsOverSizeThreshold || reader.open(oid.objectId).getType == OBJ_BLOB\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/BlobCharsetDetector.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.google.common.io.ByteStreams\nimport com.google.common.io.ByteStreams.toByteArray\nimport com.madgag.git.bfg.model.TreeBlobEntry\nimport org.eclipse.jgit.diff.RawText\nimport org.eclipse.jgit.lib.ObjectLoader\n\nimport java.nio.ByteBuffer\nimport java.nio.charset.Charset\nimport java.nio.charset.CodingErrorAction._\nimport scala.util.{Try, Using}\n\n\ntrait BlobCharsetDetector {\n  // should return None if this is a binary file that can not be converted to text\n  def charsetFor(entry: TreeBlobEntry, objectLoader: ObjectLoader): Option[Charset]\n}\n\n\nobject QuickBlobCharsetDetector extends BlobCharsetDetector {\n\n  val CharSets: Seq[Charset] =\n    Seq(Charset.forName(\"UTF-8\"), Charset.defaultCharset(), Charset.forName(\"ISO-8859-1\")).distinct\n\n  def charsetFor(entry: TreeBlobEntry, objectLoader: ObjectLoader): Option[Charset] = {\n    Using(ByteStreams.limit(objectLoader.openStream(), 8000))(toByteArray).toOption.filterNot(RawText.isBinary).flatMap {\n      sampleBytes =>\n        val b = ByteBuffer.wrap(sampleBytes)\n        CharSets.find(cs => Try(decode(b, cs)).isSuccess)\n    }\n  }\n\n  private def decode(b: ByteBuffer, charset: Charset): Unit = {\n    charset.newDecoder.onMalformedInput(REPORT).onUnmappableCharacter(REPORT).decode(b)\n  }\n}\n\n\n\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/BlobTextModifier.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.madgag.git.ThreadLocalObjectDatabaseResources\nimport com.madgag.git.bfg.model.TreeBlobEntry\nimport com.madgag.linesplitting.LineBreakPreservingIterator\nimport org.eclipse.jgit.lib.Constants.OBJ_BLOB\nimport org.eclipse.jgit.lib.ObjectLoader\n\nimport java.io.{ByteArrayOutputStream, InputStreamReader}\nimport java.nio.charset.Charset\n\n\nobject BlobTextModifier {\n\n  val DefaultSizeThreshold: Long = 1024 * 1024\n\n}\n\ntrait BlobTextModifier extends TreeBlobModifier {\n\n  val threadLocalObjectDBResources: ThreadLocalObjectDatabaseResources\n\n  def lineCleanerFor(entry: TreeBlobEntry): Option[String => String]\n\n  val charsetDetector: BlobCharsetDetector = QuickBlobCharsetDetector\n\n  val sizeThreshold = BlobTextModifier.DefaultSizeThreshold\n\n  override def fix(entry: TreeBlobEntry) = {\n\n    def filterTextIn(e: TreeBlobEntry, lineCleaner: String => String): TreeBlobEntry = {\n      def isDirty(line: String) = lineCleaner(line) != line\n\n      val loader = threadLocalObjectDBResources.reader().open(e.objectId)\n      val opt = for {\n        charset <- charsetDetector.charsetFor(e, loader)\n        if loader.getSize < sizeThreshold && linesFor(loader, charset).exists(isDirty)\n      } yield {\n        val b = new ByteArrayOutputStream(loader.getSize.toInt)\n        linesFor(loader, charset).map(lineCleaner).foreach(line => b.write(line.getBytes(charset)))\n        val oid = threadLocalObjectDBResources.inserter().insert(OBJ_BLOB, b.toByteArray)\n        e.copy(objectId = oid)\n      }\n\n      opt.getOrElse(e)\n    }\n\n    lineCleanerFor(entry) match {\n      case Some(lineCleaner) => filterTextIn(entry, lineCleaner).withoutName\n      case None => entry.withoutName\n    }\n  }\n\n  private def linesFor(loader: ObjectLoader, charset: Charset): Iterator[String] = {\n    new LineBreakPreservingIterator(new InputStreamReader(loader.openStream(), charset))\n  }\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/LfsBlobConverter.scala",
    "content": "/*\n * Copyright (c) 2015 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.google.common.io.ByteSource\nimport com.google.common.io.Files.createParentDirs\nimport com.madgag.git.LFS._\nimport com.madgag.git._\nimport com.madgag.git.bfg.model._\nimport com.madgag.git.bfg.{MemoFunc, MemoUtil}\nimport com.madgag.textmatching.{Glob, TextMatcher}\nimport org.eclipse.jgit.internal.storage.file.FileRepository\nimport org.eclipse.jgit.lib.{ObjectId, ObjectReader}\n\nimport java.nio.charset.{Charset, StandardCharsets}\nimport java.nio.file.{Files, Path}\nimport scala.jdk.StreamConverters._\nimport scala.util.{Try, Using}\n\nclass LfsBlobConverter(\n  lfsGlobExpression: String,\n  repo: FileRepository\n) extends TreeBlobModifier {\n\n  val lfsObjectsDir: Path = repo.getDirectory.toPath.resolve(LFS.ObjectsPath)\n\n  val threadLocalObjectDBResources = repo.getObjectDatabase.threadLocalResources\n\n  val lfsGlob = TextMatcher(Glob, lfsGlobExpression)\n\n  val lfsSuitableFiles: (FileName => Boolean) = f => lfsGlob(f.string)\n\n  val gitAttributesLine = s\"$lfsGlobExpression filter=lfs diff=lfs merge=lfs -text\"\n\n  implicit val UTF_8: Charset = StandardCharsets.UTF_8\n\n  val lfsPointerMemo = MemoUtil.concurrentCleanerMemo[ObjectId]()\n  \n  override def apply(dirtyBlobs: TreeBlobs) = {\n    val cleanedBlobs = super.apply(dirtyBlobs)\n    if (cleanedBlobs == dirtyBlobs) cleanedBlobs else ensureGitAttributesSetFor(cleanedBlobs)\n  }\n\n  def ensureGitAttributesSetFor(cleanedBlobs: TreeBlobs): TreeBlobs = {\n    implicit lazy val inserter = threadLocalObjectDBResources.inserter()\n\n    val newGitAttributesId = cleanedBlobs.entryMap.get(GitAttributesFileName).fold {\n      storeBlob(gitAttributesLine)\n    } {\n      case (_, oldGitAttributesId) =>\n        val objectLoader = threadLocalObjectDBResources.reader().open(oldGitAttributesId)\n        Using(ByteSource.wrap(objectLoader.getCachedBytes).asCharSource(UTF_8).lines()) { oldAttributesStream =>\n          val oldAttributes = oldAttributesStream.toScala(Seq)\n          if (oldAttributes.contains(gitAttributesLine)) oldGitAttributesId else {\n            storeBlob((oldAttributes :+ gitAttributesLine).mkString(\"\\n\"))\n          }\n        }.get\n    }\n    cleanedBlobs.copy(entryMap = cleanedBlobs.entryMap + (GitAttributesFileName -> (RegularFile, newGitAttributesId)))\n  }\n\n  override def fix(entry: TreeBlobEntry) = {\n    val cleanId = if (lfsSuitableFiles(entry.filename)) lfsPointerBlobIdForRealBlob(entry.objectId) else entry.objectId\n    (entry.mode, cleanId)\n  }\n\n  val lfsPointerBlobIdForRealBlob: MemoFunc[ObjectId, ObjectId] = lfsPointerMemo { blobId: ObjectId =>\n    implicit val reader = threadLocalObjectDBResources.reader()\n    implicit lazy val inserter = threadLocalObjectDBResources.inserter()\n\n    (for {\n      blobSize <- blobId.sizeTry if blobSize > 512\n      pointer <- tryStoringLfsFileFor(blobId)\n    } yield storeBlob(pointer.bytes)).getOrElse(blobId)\n  }\n\n  def tryStoringLfsFileFor(blobId: ObjectId)(implicit r: ObjectReader): Try[Pointer] = {\n    val loader = blobId.open\n    \n    val tmpFile: Path = Files.createTempFile(s\"bfg.git-lfs.conv-${blobId.name}\",\"dat\")\n    \n    val pointer = pointerFor(loader, tmpFile)\n\n    val lfsPath = lfsObjectsDir.resolve(pointer.path)\n\n    createParentDirs(lfsPath.toFile)\n\n    val ensureLfsFile = Try(if (!Files.exists(lfsPath)) Files.move(tmpFile, lfsPath)).recover {\n      case _ if Files.exists(lfsPath) && Files.size(lfsPath) == loader.getSize =>\n    }\n\n    Try(Files.deleteIfExists(tmpFile))\n\n    ensureLfsFile.map(_ => pointer)\n  }\n\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/ObjectIdCleaner.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.madgag.collection.concurrent.ConcurrentMultiMap\nimport com.madgag.git._\nimport com.madgag.git.bfg.GitUtil._\nimport com.madgag.git.bfg.cleaner.protection.{ProtectedObjectCensus, ProtectedObjectDirtReport}\nimport com.madgag.git.bfg.model.{Tree, TreeSubtrees, _}\nimport com.madgag.git.bfg.{CleaningMapper, Memo, MemoFunc, MemoUtil}\nimport org.eclipse.jgit.lib.Constants._\nimport org.eclipse.jgit.lib._\nimport org.eclipse.jgit.revwalk.{RevCommit, RevTag, RevWalk}\n\nobject ObjectIdCleaner {\n\n  case class Config(protectedObjectCensus: ProtectedObjectCensus,\n                    objectIdSubstitutor: ObjectIdSubstitutor = ObjectIdSubstitutor.OldIdsPublic,\n                    commitNodeCleaners: Seq[CommitNodeCleaner] = Seq.empty,\n                    treeEntryListCleaners: Seq[Cleaner[Seq[Tree.Entry]]] = Seq.empty,\n                    treeBlobsCleaners: Seq[Cleaner[TreeBlobs]] = Seq.empty,\n                    treeSubtreesCleaners: Seq[Cleaner[TreeSubtrees]] = Seq.empty,\n                    // messageCleaners? - covers both Tag and Commits\n                    objectChecker: Option[ObjectChecker] = None) {\n\n    lazy val commitNodeCleaner = CommitNodeCleaner.chain(commitNodeCleaners)\n\n    lazy val treeEntryListCleaner = Function.chain(treeEntryListCleaners)\n\n    lazy val treeBlobsCleaner = Function.chain(treeBlobsCleaners)\n\n    lazy val treeSubtreesCleaner:Cleaner[TreeSubtrees] = Function.chain(treeSubtreesCleaners)\n  }\n\n}\n\n/*\n * Knows how to clean an object, and what objects are protected...\n */\nclass ObjectIdCleaner(config: ObjectIdCleaner.Config, objectDB: ObjectDatabase, implicit val revWalk: RevWalk) extends CleaningMapper[ObjectId] {\n\n  import config._\n\n  val threadLocalResources = objectDB.threadLocalResources\n\n  val changesByFilename = new ConcurrentMultiMap[FileName, (ObjectId, ObjectId)]\n  val deletionsByFilename = new ConcurrentMultiMap[FileName, ObjectId]\n\n  // want to enforce that once any value is returned, it is 'good' and therefore an identity-mapped key as well\n  val memo: Memo[ObjectId, ObjectId] = MemoUtil.concurrentCleanerMemo(protectedObjectCensus.fixedObjectIds)\n\n  val commitMemo: Memo[ObjectId, ObjectId] = MemoUtil.concurrentCleanerMemo()\n  val tagMemo: Memo[ObjectId, ObjectId] = MemoUtil.concurrentCleanerMemo()\n\n  val treeMemo: Memo[ObjectId, ObjectId] = MemoUtil.concurrentCleanerMemo(protectedObjectCensus.treeIds.toSet[ObjectId])\n\n  def apply(objectId: ObjectId): ObjectId = memoClean(objectId)\n\n  val memoClean = memo {\n    uncachedClean\n  }\n\n  def cleanedObjectMap(): Map[ObjectId, ObjectId] =\n    Seq(memoClean, cleanCommit, cleanTag, cleanTree).map(_.asMap()).reduce(_ ++ _)\n\n  def uncachedClean: (ObjectId) => ObjectId = {\n    objectId =>\n      threadLocalResources.reader().open(objectId).getType match {\n        case OBJ_COMMIT => cleanCommit(objectId)\n        case OBJ_TREE => cleanTree(objectId)\n        case OBJ_TAG => cleanTag(objectId)\n        case _ => objectId // we don't currently clean isolated blobs... only clean within a tree context\n      }\n  }\n\n  def getCommit(commitId: AnyObjectId): RevCommit = revWalk synchronized (commitId asRevCommit)\n\n  def getTag(tagId: AnyObjectId): RevTag = revWalk synchronized (tagId asRevTag)\n\n  val cleanCommit: MemoFunc[ObjectId, ObjectId] = commitMemo { commitId =>\n    val originalRevCommit = getCommit(commitId)\n    val originalCommit = Commit(originalRevCommit)\n\n    val cleanedArcs = originalCommit.arcs cleanWith this\n    val kit = new CommitNodeCleaner.Kit(threadLocalResources, originalRevCommit, originalCommit, cleanedArcs, apply)\n    val updatedCommitNode = commitNodeCleaner.fixer(kit)(originalCommit.node)\n    val updatedCommit = Commit(updatedCommitNode, cleanedArcs)\n\n    if (updatedCommit != originalCommit) {\n      val commitBytes = updatedCommit.toBytes\n      objectChecker.foreach(_.checkCommit(commitBytes))\n      threadLocalResources.inserter().insert(OBJ_COMMIT, commitBytes)\n    } else {\n      originalRevCommit\n    }\n  }\n\n  val cleanBlob: Cleaner[ObjectId] = identity // Currently a NO-OP, we only clean at treeblob level\n\n  val cleanTree: MemoFunc[ObjectId, ObjectId] = treeMemo { originalObjectId =>\n    val entries = Tree.entriesFor(originalObjectId)(threadLocalResources.reader())\n    val cleanedTreeEntries = treeEntryListCleaner(entries)\n\n    val tree = Tree(cleanedTreeEntries)\n\n    val originalBlobs = tree.blobs\n    val fixedTreeBlobs = treeBlobsCleaner(originalBlobs)\n    val cleanedSubtrees = TreeSubtrees(treeSubtreesCleaner(tree.subtrees).entryMap.map {\n      case (name, treeId) => (name, cleanTree(treeId))\n    }).withoutEmptyTrees\n\n    val treeBlobsChanged = fixedTreeBlobs != originalBlobs\n    if (entries == cleanedTreeEntries && !treeBlobsChanged && cleanedSubtrees == tree.subtrees) originalObjectId else {\n      if (treeBlobsChanged) recordChange(originalBlobs, fixedTreeBlobs)\n\n      val updatedTree = tree copyWith(cleanedSubtrees, fixedTreeBlobs)\n\n      val treeFormatter = updatedTree.formatter\n      objectChecker.foreach(_.checkTree(treeFormatter.toByteArray))\n      treeFormatter.insertTo(threadLocalResources.inserter())\n    }\n  }\n\n  def recordChange(originalBlobs: TreeBlobs, fixedTreeBlobs: TreeBlobs): Unit = {\n    val changedFiles: Set[TreeBlobEntry] = originalBlobs.entries.toSet -- fixedTreeBlobs.entries.toSet\n    for (TreeBlobEntry(filename, _, oldId) <- changedFiles) {\n      fixedTreeBlobs.objectId(filename) match {\n        case Some(newId) => changesByFilename.addBinding(filename, (oldId, newId))\n        case None => deletionsByFilename.addBinding(filename, oldId)\n      }\n    }\n  }\n\n  case class TreeBlobChange(oldId: ObjectId, newIdOpt: Option[ObjectId], filename: FileName)\n\n  val cleanTag: MemoFunc[ObjectId, ObjectId] = tagMemo { id =>\n    val originalTag = getTag(id)\n\n    replacement(originalTag.getObject).map {\n      cleanedObj =>\n        val tb = new TagBuilder\n        tb.setTag(originalTag.getTagName)\n        tb.setObjectId(cleanedObj, originalTag.getObject.getType)\n        tb.setTagger(originalTag.getTaggerIdent)\n        tb.setMessage(objectIdSubstitutor.replaceOldIds(originalTag.getFullMessage, threadLocalResources.reader(), apply))\n        val cleanedTag: ObjectId = threadLocalResources.inserter().insert(tb)\n        objectChecker.foreach(_.checkTag(tb.build()))\n        cleanedTag\n    }.getOrElse(originalTag)\n  }\n\n  lazy val protectedDirt: Seq[ProtectedObjectDirtReport] = {\n    protectedObjectCensus.protectorRevsByObject.map {\n      case (protectedRevObj, refNames) =>\n        val originalContentObject = treeOrBlobPointedToBy(protectedRevObj).merge\n        val replacementTreeOrBlob = uncachedClean.replacement(originalContentObject)\n        ProtectedObjectDirtReport(protectedRevObj, originalContentObject, replacementTreeOrBlob)\n    }.toList\n  }\n\n  def stats() = Map(\"apply\"->memoClean.stats(), \"tree\" -> cleanTree.stats(), \"commit\" -> cleanCommit.stats(), \"tag\" -> cleanTag.stats())\n\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/ObjectIdSubstitutor.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.madgag.git._\nimport com.madgag.git.bfg.GitUtil._\nimport com.madgag.git.bfg.cleaner.ObjectIdSubstitutor._\nimport org.eclipse.jgit.lib.{AbbreviatedObjectId, ObjectId, ObjectReader}\n\nclass CommitMessageObjectIdsUpdater(objectIdSubstitutor: ObjectIdSubstitutor) extends CommitNodeCleaner {\n\n  override def fixer(kit: CommitNodeCleaner.Kit) = commitNode => commitNode.copy(message = objectIdSubstitutor.replaceOldIds(commitNode.message, kit.threadLocalResources.reader(), kit.mapper))\n\n}\n\nobject ObjectIdSubstitutor {\n\n  object OldIdsPrivate extends ObjectIdSubstitutor {\n    def format(oldIdText: String, newIdText: String) = newIdText\n  }\n\n  object OldIdsPublic extends ObjectIdSubstitutor {\n    def format(oldIdText: String, newIdText: String) = s\"$newIdText [formerly $oldIdText]\"\n  }\n\n  val hexRegex = \"\"\"\\b\\p{XDigit}{10,40}\\b\"\"\".r // choose minimum size based on size of project??\n\n}\n\ntrait ObjectIdSubstitutor {\n\n  def format(oldIdText: String, newIdText: String): String\n\n  // slow!\n  def replaceOldIds(message: String, reader: ObjectReader, mapper: Cleaner[ObjectId]): String = {\n    val substitutionOpts = for {\n      m: String <- hexRegex.findAllIn(message).toSet\n      objectId <- reader.resolveExistingUniqueId(AbbreviatedObjectId.fromString(m)).toOption\n    } yield mapper.replacement(objectId).map(newId => m -> format(m, reader.abbreviate(newId, m.length).name))\n\n    val substitutions = substitutionOpts.flatten.toMap\n    if (substitutions.isEmpty) message else hexRegex.replaceSomeIn(message, m => substitutions.get(m.matched))\n  }\n}"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/RepoRewriter.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.madgag.git._\nimport com.madgag.git.bfg.Timing\nimport org.eclipse.jgit.lib.{ObjectId, ProgressMonitor, RefDatabase}\nimport org.eclipse.jgit.revwalk.RevSort._\nimport org.eclipse.jgit.revwalk.{RevCommit, RevWalk}\nimport org.eclipse.jgit.transport.ReceiveCommand\n\nimport scala.jdk.CollectionConverters._\nimport scala.collection.parallel.CollectionConverters._\nimport scala.concurrent.ExecutionContext.Implicits.global\nimport scala.concurrent.Future\n\n/*\nEncountering a blob ->\nBIG-BLOB-DELETION : Either 'good' or 'delete'   - or possibly replace, with a different filename (means tree-level)\nPASSWORD-REMOVAL : Either 'good' or 'replace'\n\nEncountering a tree ->\nBIG-BLOB-DELETION : Either 'good' or 'replace'   - possibly adding with a different placeholder blob entry\nPASSWORD-REMOVAL : Either 'good' or 'replace' - replacing one blob entry with another\n\nSo if we encounter a tree, we are unlikely to want to remove that tree entirely...\nSHOULD WE JUST DISALLOW THAT?\nObviously, a Commit HAS to have a tree, so it's dangerous to allow a None response to tree transformation\n\nAn objectId must be either GOOD or BAD, and we must never translate *either* kind of id into a BAD\n\nUser-customisation interface: TreeBlobs => TreeBlobs\n\nUser gets no say in adding, renaming, removing directories\n\nTWO MAIN USE CASES FOR HISTORY-CHANGING ARE:\n1: GETTING RID OF BIG BLOBS\n2: REMOVING PASSWORDS IN HISTORICAL FILES\n\npossible other use-case: fixing committer names - and possibly removing passwords from commits? (could possibly just be done with rebase)\n\nWhy else would you want to rewrite HISTORY? Many other changes (ie putting a directory one down) need only be applied\nin a new commit, we don't care about history.\n\nWhen updating a Tree, the User has no right to muck with sub-trees. They can only alter the blob contents.\n */\n\nobject RepoRewriter {\n\n  def rewrite(repo: org.eclipse.jgit.lib.Repository, objectIdCleanerConfig: ObjectIdCleaner.Config): Map[ObjectId, ObjectId] = {\n    implicit val refDatabase: RefDatabase = repo.getRefDatabase\n\n    assert(refDatabase.hasRefs, \"Can't find any refs in repo at \" + repo.getDirectory.getAbsolutePath)\n\n    val reporter: Reporter = new CLIReporter(repo)\n    implicit val progressMonitor: ProgressMonitor = reporter.progressMonitor\n\n    val allRefs = refDatabase.getRefs().asScala\n\n    def createRevWalk: RevWalk = {\n\n      val revWalk = new RevWalk(repo)\n\n      revWalk.sort(TOPO) // crucial to ensure we visit parents BEFORE children, otherwise blow stack\n      revWalk.sort(REVERSE, true) // we want to start with the earliest commits and work our way up...\n\n      val startCommits = allRefs.map(_.targetObjectId.asRevObject(revWalk)).collect { case c: RevCommit => c }\n\n      revWalk.markStart(startCommits.asJavaCollection)\n      revWalk\n    }\n\n    implicit val revWalk = createRevWalk\n    implicit val reader = revWalk.getObjectReader\n\n    reporter.reportRefsForScan(allRefs)\n\n    reporter.reportObjectProtection(objectIdCleanerConfig)(repo.getObjectDatabase, revWalk)\n\n    val objectIdCleaner = new ObjectIdCleaner(objectIdCleanerConfig, repo.getObjectDatabase, revWalk)\n\n    val commits = revWalk.asScala.toSeq\n\n    def clean(commits: Seq[RevCommit]): Unit = {\n      reporter.reportCleaningStart(commits)\n\n      Timing.measureTask(\"Cleaning commits\", commits.size) {\n        Future {\n          commits.par.foreach {\n            commit => objectIdCleaner(commit.getTree)\n          }\n        }\n\n        commits.foreach {\n          commit =>\n            objectIdCleaner(commit)\n            progressMonitor update 1\n        }\n      }\n    }\n\n    def updateRefsWithCleanedIds(): Unit = {\n      val refUpdateCommands = for (ref <- repo.nonSymbolicRefs;\n                                   (oldId, newId) <- objectIdCleaner.substitution(ref.getObjectId)\n      ) yield new ReceiveCommand(oldId, newId, ref.getName)\n\n      if (refUpdateCommands.isEmpty) {\n        println(\"\\nBFG aborting: No refs to update - no dirty commits found??\\n\")\n      } else {\n        reporter.reportRefUpdateStart(refUpdateCommands)\n\n        Timing.measureTask(\"...Ref update\", refUpdateCommands.size) {\n          // Hack a fix for issue #23 : Short-cut the calculation that determines an update is NON-FF\n          val quickMergeCalcRevWalk = new RevWalk(revWalk.getObjectReader) {\n            override def isMergedInto(base: RevCommit, tip: RevCommit) =\n              if (tip == objectIdCleaner(base)) false else super.isMergedInto(base, tip)\n          }\n\n          refDatabase.newBatchUpdate.setAllowNonFastForwards(true).addCommand(refUpdateCommands.asJavaCollection)\n            .execute(quickMergeCalcRevWalk, progressMonitor)\n        }\n\n        reporter.reportResults(commits, objectIdCleaner)\n      }\n    }\n\n\n    clean(commits)\n\n    updateRefsWithCleanedIds()\n\n    objectIdCleaner.stats()\n\n    objectIdCleaner.cleanedObjectMap()\n  }\n\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/Reporter.scala",
    "content": "package com.madgag.git.bfg.cleaner\n\nimport com.google.common.io.Files.asCharSink\nimport com.madgag.collection.concurrent.ConcurrentMultiMap\nimport com.madgag.git._\nimport com.madgag.git.bfg.cleaner.Reporter.dump\nimport com.madgag.git.bfg.cleaner.protection.{ProtectedObjectCensus, ProtectedObjectDirtReport}\nimport com.madgag.git.bfg.model.FileName\nimport com.madgag.text.Text._\nimport com.madgag.text.{ByteSize, Tables, Text}\nimport org.eclipse.jgit.diff.DiffEntry.ChangeType._\nimport org.eclipse.jgit.diff._\nimport org.eclipse.jgit.lib.FileMode._\nimport org.eclipse.jgit.lib._\nimport org.eclipse.jgit.revwalk.{RevCommit, RevWalk}\nimport org.eclipse.jgit.transport.ReceiveCommand\n\nimport java.nio.charset.StandardCharsets.UTF_8\nimport java.nio.file.Files.createDirectories\nimport java.nio.file.Path\nimport java.time.ZonedDateTime\nimport java.time.format.DateTimeFormatter\nimport scala.collection.immutable.SortedMap\nimport scala.jdk.CollectionConverters._\n\n\nobject Reporter {\n  def dump(path: Path, iter: Iterable[String]): Unit = {\n    val sink = asCharSink(path.toFile, UTF_8)\n\n    sink.writeLines(iter.asJava, \"\\n\")\n  }\n}\n\ntrait Reporter {\n\n  val progressMonitor: ProgressMonitor\n\n  def reportRefsForScan(allRefs: Iterable[Ref])(implicit objReader: ObjectReader): Unit\n\n  def reportRefUpdateStart(refUpdateCommands: Iterable[ReceiveCommand]): Unit\n\n  def reportObjectProtection(objectIdCleanerConfig: ObjectIdCleaner.Config)(implicit objectDB: ObjectDatabase, revWalk: RevWalk): Unit\n\n  def reportCleaningStart(commits: Seq[RevCommit]): Unit\n\n  def reportResults(commits: Seq[RevCommit], objectIdCleaner: ObjectIdCleaner): Unit\n}\n\nclass CLIReporter(repo: Repository) extends Reporter {\n\n  lazy val reportsDir: Path = {\n    val now = ZonedDateTime.now()\n\n    val topDirPath = repo.topDirectory.toPath.toAbsolutePath\n\n    val reportsDir = topDirPath.resolveSibling(s\"${topDirPath.getFileName}.bfg-report\")\n\n    val dateFormatter = DateTimeFormatter.ofPattern(\"uuuu-MM-dd\")\n    val timeFormatter = DateTimeFormatter.ofPattern(\"HH-mm-ss\")\n\n    val dir = reportsDir.resolve(now.format(dateFormatter)).resolve(now.format(timeFormatter))\n\n    createDirectories(dir)\n    dir\n  }\n\n  lazy val progressMonitor = new TextProgressMonitor\n\n  def reportRefUpdateStart(refUpdateCommands: Iterable[ReceiveCommand]): Unit = {\n    println(title(\"Updating \" + plural(refUpdateCommands, \"Ref\")))\n\n    val summaryTableCells = refUpdateCommands.map(update => (update.getRefName, update.getOldId.shortName, update.getNewId.shortName))\n\n    Tables.formatTable((\"Ref\", \"Before\", \"After\"), summaryTableCells.toSeq).map(\"\\t\" + _).foreach(println)\n\n    println()\n  }\n\n  def reportRefsForScan(allRefs: Iterable[Ref])(implicit objReader: ObjectReader): Unit = {\n    val refsByObjType = allRefs.groupBy {\n      ref => objReader.open(ref.getObjectId).getType\n    } withDefault Seq.empty\n\n    refsByObjType.foreach {\n      case (typ, refs) => println(\"Found \" + refs.size + \" \" + Constants.typeString(typ) + \"-pointing refs : \" + abbreviate(refs.map(_.getName).toSeq, \"...\", 4).mkString(\", \"))\n    }\n  }\n\n\n  // abort due to Dirty Tips on Private run - user needs to manually clean\n  // warn due to Dirty Tips on Public run - it's not so serious if users publicise dirty tips.\n  // if no protection\n  def reportObjectProtection(objectIdCleanerConfig: ObjectIdCleaner.Config)(implicit objectDB: ObjectDatabase, revWalk: RevWalk): Unit = {\n    println(title(\"Protected commits\"))\n\n    if (objectIdCleanerConfig.protectedObjectCensus.isEmpty) {\n      println(\"You're not protecting any commits, which means the BFG will modify the contents of even *current* commits.\\n\\n\" +\n        \"This isn't recommended - ideally, if your current commits are dirty, you should fix up your working copy and \" +\n        \"commit that, check that your build still works, and only then run the BFG to clean up your history.\")\n    } else {\n      println(\"These are your protected commits, and so their contents will NOT be altered:\\n\")\n\n      val unprotectedConfig = objectIdCleanerConfig.copy(protectedObjectCensus = ProtectedObjectCensus.None)\n\n      reportProtectedCommitsAndTheirDirt(objectIdCleanerConfig)\n    }\n  }\n\n  case class DiffSideDetails(id: ObjectId, path: String, mode: FileMode, size: Option[Long])\n\n  def reportProtectedCommitsAndTheirDirt(objectIdCleanerConfig: ObjectIdCleaner.Config)(implicit objectDB: ObjectDatabase, revWalk: RevWalk): Unit = {\n    implicit val reader = revWalk.getObjectReader\n\n    def diffDetails(d: DiffEntry) = {\n      val side = DiffEntry.Side.OLD\n      val id: ObjectId = d.getId(side).toObjectId\n      DiffSideDetails(id, d.getPath(side), d.getMode(side), id.sizeOpt)\n    }\n\n    def fileInfo(d: DiffSideDetails) = {\n      val extraInfo = (d.mode match {\n        case GITLINK => Some(\"submodule\")\n        case _ => d.size.map(ByteSize.format(_))\n      }).map(e => s\"($e)\")\n\n      (d.path +: extraInfo.toSeq).mkString(\" \")\n    }\n\n    val protectedDirtDir = reportsDir.resolve(\"protected-dirt\")\n    createDirectories(protectedDirtDir)\n\n    val reports = ProtectedObjectDirtReport.reportsFor(objectIdCleanerConfig, objectDB)\n\n    reports.foreach {\n      report =>\n        val protectorRevs = objectIdCleanerConfig.protectedObjectCensus.protectorRevsByObject(report.revObject)\n        val objectTitle = s\" * ${report.revObject.typeString} ${report.revObject.shortName} (protected by '${protectorRevs.mkString(\"', '\")}')\"\n\n        report.dirt match {\n          case None => println(objectTitle)\n          case Some(diffEntries) =>\n            if (diffEntries.isEmpty) {\n              println(objectTitle + \" - dirty\")\n            } else {\n              println(objectTitle + \" - contains \" + plural(diffEntries, \"dirty file\") + \" : \")\n              abbreviate(diffEntries.view.map(diffDetails).map(fileInfo), \"...\").foreach {\n                dirtyFile => println(\"\\t- \" + dirtyFile)\n              }\n\n              val protectorRefsFileNameSafe: String = protectorRevs.mkString(\"_\").replace(\n                protectedDirtDir.getFileSystem.getSeparator,\n                \"-\"\n              )\n              val diffFile = protectedDirtDir.resolve(s\"${report.revObject.shortName}-$protectorRefsFileNameSafe.csv\")\n\n              dump(diffFile, diffEntries.map {\n                diffEntry =>\n                  val de = diffDetails(diffEntry)\n\n                  val modifiedLines = if (diffEntry.getChangeType == MODIFY) diffEntry.editList.map(changedLinesFor) else None\n\n                  val elems = Seq(de.id.name, diffEntry.getChangeType.name, de.mode.name, de.path, de.size.getOrElse(\"\"), modifiedLines.getOrElse(\"\"))\n\n                  elems.mkString(\",\")\n              })\n              }\n            }\n        }\n\n    val dirtyReports = reports.filter(_.objectProtectsDirt)\n    if (dirtyReports.nonEmpty) {\n\n      println(s\"\"\"\n      |WARNING: The dirty content above may be removed from other commits, but as\n      |the *protected* commits still use it, it will STILL exist in your repository.\n      |\n      |Details of protected dirty content have been recorded here :\n      |\n      |${protectedDirtDir.toAbsolutePath.toString + protectedDirtDir.getFileSystem.getSeparator}\n      |\n      |If you *really* want this content gone, make a manual commit that removes it,\n      |and then run the BFG on a fresh copy of your repo.\n       \"\"\".stripMargin)\n      // TODO would like to abort here if we are cleaning 'private' data.\n    }\n  }\n\n  def changedLinesFor(edits: EditList): String = {\n    edits.asScala.map {\n      edit => Seq(edit.getBeginA + 1, edit.getEndA).distinct.mkString(\"-\")\n    }.mkString(\";\")\n  }\n\n  def reportCleaningStart(commits: Seq[RevCommit]): Unit = {\n    println(title(\"Cleaning\"))\n    println(\"Found \" + commits.size + \" commits\")\n  }\n\n  def reportResults(commits: Seq[RevCommit], objectIdCleaner: ObjectIdCleaner): Unit = {\n    def reportTreeDirtHistory(): Unit = {\n\n      val dirtHistoryElements = math.max(20, math.min(60, commits.size))\n      def cut[A](xs: Seq[A], n: Int) = {\n        val avgSize = xs.size.toFloat / n\n        def startOf(unit: Int): Int = math.round(unit * avgSize)\n        (0 until n).view.map(u => xs.slice(startOf(u), startOf(u + 1)))\n      }\n      val treeDirtHistory = cut(commits, dirtHistoryElements).map {\n        case commits if commits.isEmpty => ' '\n        case commits if (commits.exists(c => objectIdCleaner.isDirty(c.getTree))) => 'D'\n        case commits if (commits.exists(objectIdCleaner.isDirty)) => 'm'\n        case _ => '.'\n      }.mkString\n      def leftRight(markers: Seq[String]) = markers.mkString(\" \" * (treeDirtHistory.length - markers.map(_.size).sum))\n      println(title(\"Commit Tree-Dirt History\"))\n      println(\"\\t\" + leftRight(Seq(\"Earliest\", \"Latest\")))\n      println(\"\\t\" + leftRight(Seq(\"|\", \"|\")))\n      println(\"\\t\" + treeDirtHistory)\n      println(\"\\n\\tD = dirty commits (file tree fixed)\")\n      println(\"\\tm = modified commits (commit message or parents changed)\")\n      println(\"\\t. = clean commits (no changes to file tree)\\n\")\n\n      val firstModifiedCommit = commits.find(objectIdCleaner.isDirty).map(_ -> \"First modified commit\")\n      val lastDirtyCommit = commits.reverse.find(c => objectIdCleaner.isDirty(c.getTree)).map(_ -> \"Last dirty commit\")\n      val items = for {\n        (commit, desc) <- firstModifiedCommit ++ lastDirtyCommit\n        (before, after) <- objectIdCleaner.substitution(commit)\n      } yield (desc, before.shortName, after.shortName)\n      Tables.formatTable((\"\", \"Before\", \"After\"), items.toSeq).map(\"\\t\" + _).foreach(println)\n    }\n\n    reportTreeDirtHistory()\n\n    lazy val mapFile: Path = reportsDir.resolve(\"object-id-map.old-new.txt\")\n    lazy val cacheStatsFile: Path = reportsDir.resolve(\"cache-stats.txt\")\n\n    val changedIds = objectIdCleaner.cleanedObjectMap()\n\n    def reportFiles[FI](\n        fileData: ConcurrentMultiMap[FileName, FI],\n        actionType: String,\n        tableTitles: Product\n      )(f: ((FileName,Set[FI])) => Product)(fi: FI => Seq[String]): Unit = {\n      implicit val fileNameOrdering = Ordering[String].on[FileName](_.string)\n\n      val dataByFilename = SortedMap[FileName, Set[FI]](fileData.toMap.toSeq: _*)\n      if (dataByFilename.nonEmpty) {\n        println(title(s\"$actionType files\"))\n        Tables.formatTable(tableTitles, dataByFilename.map(f).toSeq).map(\"\\t\" + _).foreach(println)\n\n        val actionFile = reportsDir.resolve(s\"${actionType.toLowerCase}-files.txt\")\n\n        dump(actionFile, dataByFilename.flatMap {\n          case (filename, changes) => changes.map(fi.andThen(fid => (fid :+ filename).mkString(\" \")))\n        })\n      }\n    }\n\n    reportFiles(objectIdCleaner.changesByFilename, \"Changed\", (\"Filename\", \"Before & After\")) {\n      case (filename, changes) => (filename, Text.abbreviate(changes.map {case (oldId, newId) => oldId.shortName+\" ⇒ \"+newId.shortName}, \"...\").mkString(\", \"))\n    } { case (oldId, newId) => Seq(oldId.name, newId.name) }\n\n    implicit val reader = objectIdCleaner.threadLocalResources.reader()\n\n    reportFiles(objectIdCleaner.deletionsByFilename, \"Deleted\", (\"Filename\", \"Git id\")) {\n      case (filename, oldIds) => (filename, Text.abbreviate(oldIds.map(oldId => oldId.shortName + oldId.sizeOpt.map(size => s\" (${ByteSize.format(size)})\").mkString), \"...\").mkString(\", \"))\n    } { oldId => Seq(oldId.name, oldId.sizeOpt.mkString) }\n\n    println(s\"\\n\\nIn total, ${changedIds.size} object ids were changed. Full details are logged here:\\n\\n\\t$reportsDir\")\n\n    dump(mapFile,SortedMap[AnyObjectId, ObjectId](changedIds.toSeq: _*).view.map { case (o,n) => s\"${o.name} ${n.name}\"})\n\n    dump(cacheStatsFile,objectIdCleaner.stats().map(_.toString()))\n\n    println(\"\\nBFG run is complete! When ready, run: git reflog expire --expire=now --all && git gc --prune=now --aggressive\")\n\n  }\n\n  def title(text: String) = s\"\\n$text\\n\" + (\"-\" * text.size) + \"\\n\"\n}"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/TreeBlobModifier.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.madgag.git.bfg.MemoUtil\nimport com.madgag.git.bfg.model.{TreeBlobEntry, _}\nimport org.eclipse.jgit.lib.ObjectId\n\ntrait TreeBlobModifier extends Cleaner[TreeBlobs] {\n\n  val memoisedCleaner: Cleaner[TreeBlobEntry] = MemoUtil.concurrentCleanerMemo[TreeBlobEntry](Set.empty) {\n    entry =>\n      val (mode, objectId) = fix(entry)\n      TreeBlobEntry(entry.filename, mode, objectId)\n  }\n\n  def fix(entry: TreeBlobEntry): (BlobFileMode, ObjectId) // implementing code can not safely know valid filename\n\n  override def apply(treeBlobs: TreeBlobs) = treeBlobs.entries.map(memoisedCleaner)\n\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/commits.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.madgag.git.ThreadLocalObjectDatabaseResources\nimport com.madgag.git.bfg.model._\nimport org.eclipse.jgit.lib._\nimport org.eclipse.jgit.revwalk.RevCommit\n\nobject CommitNodeCleaner {\n\n  class Kit(val threadLocalResources: ThreadLocalObjectDatabaseResources,\n            val originalRevCommit: RevCommit,\n            val originalCommit: Commit,\n            val updatedArcs: CommitArcs,\n            val mapper: Cleaner[ObjectId]) {\n\n    val arcsChanged = originalCommit.arcs != updatedArcs\n\n    def commitIsChanged(withThisNode: CommitNode) = arcsChanged || originalCommit.node != withThisNode\n  }\n\n  def chain(cleaners: Seq[CommitNodeCleaner]) = new CommitNodeCleaner {\n    def fixer(kit: CommitNodeCleaner.Kit) = Function.chain(cleaners.map(_.fixer(kit)))\n  }\n}\n\ntrait CommitNodeCleaner {\n  def fixer(kit: CommitNodeCleaner.Kit): Cleaner[CommitNode]\n}\n\nobject FormerCommitFooter extends CommitNodeCleaner {\n  val Key = \"Former-commit-id\"\n\n  override def fixer(kit: CommitNodeCleaner.Kit) = modifyIf(kit.commitIsChanged) {\n    _ add Footer(Key, kit.originalRevCommit.name)\n  }\n\n  def modifyIf[A](predicate: A => Boolean)(modifier: A => A): (A => A) = v => if (predicate(v)) modifier(v) else v\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/kit/BlobInserter.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner.kit\n\nimport java.io.InputStream\n\nimport org.eclipse.jgit.lib.Constants._\nimport org.eclipse.jgit.lib.{ObjectId, ObjectInserter}\n\nclass BlobInserter(objectInserter: ObjectInserter) {\n  def insert(data: Array[Byte]): ObjectId = objectInserter.insert(OBJ_BLOB, data)\n\n  def insert(length: Long, in: InputStream): ObjectId = objectInserter.insert(OBJ_BLOB, length, in)\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/package.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg\n\npackage object cleaner {\n  type Cleaner[V] = V => V\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/protection/ProtectedObjectCensus.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner.protection\n\nimport com.madgag.git._\nimport com.madgag.scala.collection.decorators._\nimport org.eclipse.jgit.lib.{ObjectId, Repository}\nimport org.eclipse.jgit.revwalk._\n\n/**\n * PROTECTING TREES :\n * Want to leave the tree unchanged for all commits at the tips of refs the user thinks are important.\n * What if you think a Tag is important? Or a tree?\n *\n * If a tag points to a:\n * - commit - that commit may change, but it's tree must stay the same\n * - tree - who the fuck tags tree anyway? if I've been asked to protect it, that suggests that it's supposed to be inviolate\n * - 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\n *\n * We can take a shortcut here by just pushing all hallowed trees straight into the memo collection\n * This does mean that we will never notice, or be able to report, if somebody sets a rule that 'cleans' (alters) a hallowed tree\n * It might also have somewhat unexpected consequences if someone hallows a very 'simple' directory that occurs often\n *\n *\n * PROTECTING BLOBS :\n * If a user wants to protect the tip of a ref, all blobs will be retained. There is no space-saving or secrets-kept\n * by deleting, tampering with those blobs elsewhere. And if you have some big-old blob like a jar that you have\n * used consistently throughout the history of your project, it benefits no-one to remove it- in fact it's actively\n * harmful.\n *\n * We explicitly protect blobs (rather than just allowing them to fall under the protection given to Trees) precisely\n * because these blobs may historically have existed in other directories (trees) that did not appear in the\n * protected tips, and so would not be protected by Tree protection.\n *\n *\n * PROTECTING TAGS & COMMITS :\n * This just means protecting the Trees & Blobs under those Tags and Commits, as specified above. Changing other\n * state - such as the message, or author, or referenced commit Ids (and consequently the object Id of the target\n * object itself) is very much up for grabs. I gotta change your history, or I've no business being here.\n */\nobject ProtectedObjectCensus {\n\n  val None = ProtectedObjectCensus()\n\n  def apply(revisions: Set[String])(implicit repo: Repository): ProtectedObjectCensus = {\n\n    implicit val (revWalk, reader) = repo.singleThreadedReaderTuple\n\n    val objectProtection = revisions.groupBy { revision =>\n      Option(repo.resolve(revision)).getOrElse { throw new IllegalArgumentException(\n          s\"Couldn't find '$revision' in ${repo.topDirectory.getAbsolutePath} - are you sure that exists?\"\n      )}.asRevObject\n    }\n\n    // blobs come from direct blob references and tag references\n    // trees come from direct tree references, commit & tag references\n\n    val treeAndBlobProtection = objectProtection.keys.groupUp(treeOrBlobPointedToBy)(_.toSet) // use Either?\n\n    val directBlobProtection = treeAndBlobProtection collect {\n      case (Left(blob), p) => blob.getId -> p\n    }\n    val treeProtection = treeAndBlobProtection collect {\n      case (Right(tree), p) => tree -> p\n    }\n    val indirectBlobProtection = treeProtection.keys.flatMap(tree => allBlobsUnder(tree).map(_ -> tree)).groupUp(_._1)(_.map(_._2).toSet)\n\n    ProtectedObjectCensus(objectProtection, treeProtection, directBlobProtection, indirectBlobProtection)\n  }\n}\n\ncase class ProtectedObjectCensus(protectorRevsByObject: Map[RevObject, Set[String]] = Map.empty,\n                            treeProtection: Map[RevTree, Set[RevObject]] = Map.empty,\n                            directBlobProtection: Map[ObjectId, Set[RevObject]] = Map.empty,\n                            indirectBlobProtection: Map[ObjectId, Set[RevTree]] = Map.empty) {\n\n  val isEmpty = protectorRevsByObject.isEmpty\n\n  lazy val blobIds: Set[ObjectId] = directBlobProtection.keySet ++ indirectBlobProtection.keySet\n\n  lazy val treeIds = treeProtection.keySet\n\n  // blobs only for completeness here\n  lazy val fixedObjectIds: Set[ObjectId] = treeIds ++ blobIds\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/protection/ProtectedObjectDirtReport.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner.protection\n\nimport com.madgag.git._\nimport com.madgag.git.bfg.GitUtil._\nimport com.madgag.git.bfg.cleaner.ObjectIdCleaner\nimport org.eclipse.jgit.diff.DiffEntry\nimport org.eclipse.jgit.diff.DiffEntry.ChangeType._\nimport org.eclipse.jgit.lib.{ObjectDatabase, ObjectId}\nimport org.eclipse.jgit.revwalk.{RevObject, RevWalk}\nimport org.eclipse.jgit.treewalk.TreeWalk\nimport org.eclipse.jgit.treewalk.filter.TreeFilter\n\nimport scala.jdk.CollectionConverters._\n\nobject ProtectedObjectDirtReport {\n  def reportsFor(objectIdCleanerConfig: ObjectIdCleaner.Config, objectDB: ObjectDatabase)(implicit revWalk: RevWalk) = {\n    val uncaringCleaner: ObjectIdCleaner = new ObjectIdCleaner(\n      objectIdCleanerConfig.copy(protectedObjectCensus = ProtectedObjectCensus.None),\n      objectDB,\n      revWalk\n    )\n\n    for (protectedRevObj <- objectIdCleanerConfig.protectedObjectCensus.protectorRevsByObject.keys) yield {\n      val originalContentTreeOrBlob = treeOrBlobPointedToBy(protectedRevObj)\n      val replacementTreeOrBlob = originalContentTreeOrBlob.fold(uncaringCleaner.cleanBlob.replacement, uncaringCleaner.cleanTree.replacement)\n      ProtectedObjectDirtReport(protectedRevObj, originalContentTreeOrBlob.merge, replacementTreeOrBlob)\n    }\n  }\n}\n\n/**\n * The function of the ProtectedObjectDirtReport is tell the user that this is the stuff they've decided\n * to protect in their latest commits - it's the stuff The BFG /would/ remove if you hadn't told it to\n * hold back,\n *\n * @param revObject - the protected object (eg protected because it is the HEAD commit, or even by additional refs)\n * @param originalTreeOrBlob - the unmodified content-object referred to by the protected object (may be same object)\n * @param replacementTreeOrBlob - an option, populated if cleaning creates a replacement for the content-object\n */\ncase class ProtectedObjectDirtReport(revObject: RevObject, originalTreeOrBlob: RevObject, replacementTreeOrBlob: Option[ObjectId]) {\n  val objectProtectsDirt: Boolean = replacementTreeOrBlob.isDefined\n\n  def dirt(implicit revWalk: RevWalk): Option[Seq[DiffEntry]] = replacementTreeOrBlob.map { newId =>\n    val tw = new TreeWalk(revWalk.getObjectReader)\n    tw.setRecursive(true)\n    tw.reset\n\n    tw.addTree(originalTreeOrBlob.asRevTree)\n    tw.addTree(newId.asRevTree)\n    tw.setFilter(TreeFilter.ANY_DIFF)\n    DiffEntry.scan(tw).asScala.filterNot(_.getChangeType == ADD).toSeq\n  }\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/cleaner/treeblobs.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.madgag.git.bfg.cleaner.kit.BlobInserter\nimport com.madgag.git.bfg.model.FileName.ImplicitConversions._\nimport com.madgag.git.bfg.model.{TreeBlobEntry, _}\nimport com.madgag.textmatching.TextMatcher\nimport org.eclipse.jgit.lib.ObjectId\n\nclass FileDeleter(fileNameMatcher: TextMatcher) extends Cleaner[TreeBlobs] {\n  override def apply(tbs: TreeBlobs) = tbs.entries.filterNot(e => fileNameMatcher(e.filename))\n}\n\nclass BlobRemover(blobIds: Set[ObjectId]) extends Cleaner[TreeBlobs] {\n  override def apply(treeBlobs: TreeBlobs) = treeBlobs.entries.filter(e => !blobIds.contains(e.objectId))\n}\n\nclass BlobReplacer(badBlobs: Set[ObjectId], blobInserter: => BlobInserter) extends Cleaner[TreeBlobs] {\n  override def apply(treeBlobs: TreeBlobs) = treeBlobs.entries.map {\n    case e if badBlobs.contains(e.objectId) =>\n      TreeBlobEntry(FileName(e.filename + \".REMOVED.git-id\"), RegularFile, blobInserter.insert(e.objectId.name.getBytes))\n    case e => e\n  }\n}\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/memo.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg\n\nimport scala.jdk.CollectionConverters._\nimport com.google.common.cache.{CacheBuilder, CacheLoader, CacheStats, LoadingCache}\nimport com.madgag.git.bfg.cleaner._\n\ntrait Memo[K, V] {\n  def apply(z: K => V): MemoFunc[K, V]\n}\n\ntrait MemoFunc[K,V] extends (K => V) {\n  def asMap(): Map[K,V]\n\n  def stats(): CacheStats\n}\n\nobject MemoUtil {\n\n  def memo[K, V](f: (K => V) => MemoFunc[K, V]): Memo[K, V] = new Memo[K, V] {\n    def apply(z: K => V) = f(z)\n  }\n\n  /**\n   *\n   * A caching wrapper for a function (V => V), backed by a no-eviction LoadingCache from Google Collections.\n   */\n  def concurrentCleanerMemo[V](fixedEntries: Set[V] = Set.empty[V]): Memo[V, V] = {\n    memo[V, V] {\n      (f: Cleaner[V]) =>\n        lazy val permanentCache = loaderCacheFor(f)(fix)\n\n        def fix(v: V): Unit = {\n          // enforce that once any value is returned, it is 'good' and therefore an identity-mapped key as well\n          permanentCache.put(v, v)\n        }\n\n        fixedEntries foreach fix\n\n        new MemoFunc[V, V] {\n          def apply(k: V) = permanentCache.get(k)\n\n          def asMap() = permanentCache.asMap().asScala.view.filter {\n            case (oldId, newId) => newId != oldId\n          }.toMap\n\n          override def stats(): CacheStats = permanentCache.stats()\n        }\n    }\n  }\n\n  def loaderCacheFor[K, V](calc: K => V)(postCalc: V => Unit): LoadingCache[K, V] =\n    CacheBuilder.newBuilder.asInstanceOf[CacheBuilder[K, V]].recordStats().build(new CacheLoader[K, V] {\n      def load(key: K): V = {\n        val v = calc(key)\n        postCalc(v)\n        v\n      }\n    })\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/model/Commit.scala",
    "content": "package com.madgag.git.bfg.model\n\nimport com.madgag.git._\nimport com.madgag.git.bfg.cleaner._\nimport org.eclipse.jgit.lib.Constants.OBJ_COMMIT\nimport org.eclipse.jgit.lib._\nimport org.eclipse.jgit.revwalk.RevCommit\n\nimport java.nio.charset.StandardCharsets.UTF_8\nimport java.nio.charset.{Charset, IllegalCharsetNameException, UnsupportedCharsetException}\nimport scala.jdk.CollectionConverters._\n\n/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\n\nobject Commit {\n  def apply(revCommit: RevCommit): Commit = Commit(CommitNode(revCommit), revCommit.arcs)\n}\n\ncase class Commit(node: CommitNode, arcs: CommitArcs) {\n  def toBytes: Array[Byte] = {\n    val c = new CommitBuilder\n    c.setParentIds(arcs.parents.asJava)\n    c.setTreeId(arcs.tree)\n\n    c.setAuthor(node.author)\n    c.setCommitter(node.committer)\n    c.setEncoding(node.encoding)\n    c.setMessage(node.message)\n\n    c.toByteArray\n  }\n\n  lazy val id = new ObjectInserter.Formatter().idFor(OBJ_COMMIT, toBytes)\n\n  override lazy val toString = s\"commit[${id.shortName}${node.subject.map(s=> s\" '${s.take(50)}'\").getOrElse(\"\")}]\"\n}\n\ncase class CommitArcs(parents: Seq[ObjectId], tree: ObjectId) {\n  def cleanWith(cleaner: ObjectIdCleaner) = CommitArcs(parents map cleaner.cleanCommit, cleaner.cleanTree(tree))\n}\n\nobject CommitNode {\n  def apply(c: RevCommit): CommitNode = CommitNode(c.getAuthorIdent, c.getCommitterIdent, c.getFullMessage,\n      try c.getEncoding catch {case e @ (_ : IllegalCharsetNameException | _ : UnsupportedCharsetException) => UTF_8})\n}\n\ncase class CommitNode(author: PersonIdent, committer: PersonIdent, message: String, encoding: Charset = UTF_8) {\n  lazy val subject = message.linesIterator.to(LazyList).headOption\n  lazy val lastParagraphBreak = message.lastIndexOf(\"\\n\\n\")\n  lazy val messageWithoutFooters = if (footers.isEmpty) message else (message take lastParagraphBreak)\n  lazy val footers: List[Footer] = message.drop(lastParagraphBreak).linesIterator.collect {\n    case Footer.FooterPattern(key, value) => Footer(key, value)\n  }.toList\n\n  def add(footer: Footer) = copy(message = message + \"\\n\" + (if (footers.isEmpty) \"\\n\" else \"\") + footer.toString)\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/model/Footer.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.model\n\nobject Footer {\n  // ^[A-Za-z0-9-]+:\n  val FooterPattern = \"\"\"([\\p{Alnum}-]+): *(.*)\"\"\".r\n\n  def apply(footerLine: String): Option[Footer] = footerLine match {\n    case FooterPattern(key, value) => Some(Footer(key, value))\n    case _ => None\n  }\n}\n\ncase class Footer(key: String, value: String) {\n  override lazy val toString = key + \": \" + value\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/model/package.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg\n\nimport org.eclipse.jgit.revwalk.RevCommit\n\nimport java.nio.file.Path\n\n\npackage object model {\n  implicit class RichRevCommit(revCommit: RevCommit) {\n    lazy val arcs: CommitArcs = CommitArcs(revCommit.getParents.toIndexedSeq, revCommit.getTree)\n  }\n\n  implicit class RichPath(path: Path) {\n    def resolve(pathSegments: Seq[String]): Path = pathSegments.foldLeft(path)(_ resolve _)\n  }\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/git/bfg/timing.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg\n\nimport java.lang.System._\nimport java.util.concurrent.TimeUnit.NANOSECONDS\n\nimport org.eclipse.jgit.lib.ProgressMonitor\n\nobject Timing {\n  //  def measure[T](block: => T) = {\n  //    val start = nanoTime\n  //    val result = block\n  //    val duration = nanoTime - start\n  //    println(\"duration=\"+duration)\n  //    result\n  //  }\n\n  def measureTask[T](taskName: String, workSize: Int)(block: => T)(implicit progressMonitor: ProgressMonitor) = {\n    progressMonitor.beginTask(taskName, workSize)\n    val start = nanoTime\n    val result = block\n    val duration = nanoTime - start\n    progressMonitor.endTask()\n    println(taskName + \" completed in %,d ms.\".format(NANOSECONDS.toMillis(duration)))\n    result\n  }\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/inclusion/inclusion.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.inclusion\n\nimport scala.Function.const\n\ncase class IncExcExpression[-A](filters: Seq[Filter[A]]) {\n  lazy val searchPath = (filters.headOption.map(_.impliedPredecessor).getOrElse(Include.everything) +: filters).reverse\n\n  def includes(a: A): Boolean = searchPath.find(_.predicate(a)).get.included\n}\n\nsealed trait Filter[-A] {\n  val included: Boolean\n\n  val predicate: A => Boolean\n\n  val impliedPredecessor: Filter[A]\n\n  def isDefinedAt(a: A) = predicate(a)\n}\n\n\nobject Include {\n  def everything = Include(const(true))\n}\n\nobject Exclude {\n  def everything = Exclude(const(true))\n}\n\ncase class Include[A](predicate: A => Boolean) extends Filter[A] {\n  lazy val impliedPredecessor = Exclude.everything\n  val included = true\n}\n\ncase class Exclude[A](predicate: A => Boolean) extends Filter[A] {\n  lazy val impliedPredecessor = Include.everything\n  val included = false\n}"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/text/ByteSize.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.text\n\nobject ByteSize {\n\n  import math._\n\n  val magnitudeChars = Seq('B', 'K', 'M', 'G', 'T', 'P')\n  val unit = 1024\n\n  def parse(v: String): Long = magnitudeChars.indexOf(v.takeRight(1)(0).toUpper) match {\n    case -1 => throw new IllegalArgumentException(s\"Size unit is missing (ie ${magnitudeChars.mkString(\", \")})\")\n    case index => v.dropRight(1).toLong << (index * 10)\n  }\n\n  def format(bytes: Long): String = {\n    if (bytes < unit) s\"$bytes B \" else {\n      val exp = (log(bytes.toDouble) / log(unit)).toInt\n      val pre = magnitudeChars(exp)\n      \"%.1f %sB\".format(bytes / pow(unit, exp), pre)\n    }\n  }\n\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/text/Tables.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.text\n\nobject Tables {\n  def formatTable(header: Product, data: Seq[Product], maxDataRows: Int = 16): Seq[String] = {\n    val numColumns = data.head.productArity\n    val sizes: Seq[Int] = (0 until numColumns).map(i => (data :+ header).map(_.productElement(i).toString.length).max)\n    def padLine(l: Product): IndexedSeq[String] = {\n      (0 until numColumns).map(c => l.productElement(c).toString.padTo(sizes(c), ' '))\n    }\n\n    val headerLine = padLine(header).mkString(\"   \")\n    Text.abbreviate(headerLine +: \"-\" * headerLine.size +: data.map {\n      l =>\n        padLine(l).mkString(\" | \")\n    }, \"...\", maxDataRows+2).toSeq\n  }\n}\n"
  },
  {
    "path": "bfg-library/src/main/scala/com/madgag/text/text.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.text\n\nobject Text {\n\n  def abbreviate[A](elems: Iterable[A], truncationToken: A, maxElements: Int = 3) = {\n    val firstElems = elems.take(maxElements + 1)\n    if (firstElems.size > maxElements) {\n      firstElems.take(maxElements-1).toSeq :+ truncationToken\n    } else {\n      elems\n    }\n  }\n\n  def plural[A](list: Iterable[A], noun: String) = s\"${list.size} $noun${if (list.size == 1) \"\" else \"s\"}\"\n}\n"
  },
  {
    "path": "bfg-library/src/test/scala/com/madgag/git/LFSSpec.scala",
    "content": "/*\n * Copyright (c) 2015 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git\n\nimport com.madgag.git.LFS.Pointer\nimport com.madgag.git.test._\nimport org.eclipse.jgit.lib.Constants._\nimport org.eclipse.jgit.lib.ObjectInserter\nimport org.scalatest.OptionValues\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\nimport java.nio.file.Files\nimport java.nio.file.Files.createTempFile\n\nclass LFSSpec extends AnyFlatSpec with Matchers with OptionValues {\n  \"Our implementation of Git LFS Pointers\" should \"create pointers that have the same Git id as the ones produced by `git lfs pointer`\" in {\n    val pointer = LFS.Pointer(\"b2893eddd9b394bfb7efadafda2ae0be02c573fdd83a70f26c781a943f3b7016\", 21616)\n\n    val pointerObjectId = new ObjectInserter.Formatter().idFor(OBJ_BLOB, pointer.bytes)\n\n    pointerObjectId shouldBe \"1d90744cffd9e9f324870ed60b6d1258e56a39e1\".asObjectId\n  }\n\n  it should \"have the correctly sharded path\" in {\n    val pointer = LFS.Pointer(\"b2893eddd9b394bfb7efadafda2ae0be02c573fdd83a70f26c781a943f3b7016\", 21616)\n\n    pointer.path shouldBe Seq(\"b2\", \"89\", \"b2893eddd9b394bfb7efadafda2ae0be02c573fdd83a70f26c781a943f3b7016\")\n  }\n\n  it should \"calculate pointers correctly directly from the Git database, creating a temporary file\" in {\n    implicit val repo = unpackRepo(\"/sample-repos/example.git.zip\")\n    implicit val (revWalk, reader) = repo.singleThreadedReaderTuple\n\n    val tmpFile = createTempFile(s\"bfg.test.git-lfs\",\".conv\")\n\n    val pointer = LFS.pointerFor(abbrId(\"06d7\").open, tmpFile)\n\n    pointer shouldBe Pointer(\"5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef\", 1024)\n\n    Files.size(tmpFile) shouldBe 1024\n  }\n}"
  },
  {
    "path": "bfg-library/src/test/scala/com/madgag/git/bfg/GitUtilSpec.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg\n\nimport com.madgag.git._\nimport com.madgag.git.test._\nimport org.eclipse.jgit.internal.storage.file.FileRepository\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\nclass GitUtilSpec extends AnyFlatSpec with Matchers {\n  implicit val repo: FileRepository = unpackRepo(\"/sample-repos/example.git.zip\")\n\n  \"reachable blobs\" should \"match expectations\" in {\n    implicit val (revWalk, reader) = repo.singleThreadedReaderTuple\n\n    allBlobsReachableFrom(abbrId(\"475d\") asRevCommit) shouldBe Set(\"d8d1\", \"34bd\", \"e69d\", \"c784\", \"d004\").map(abbrId)\n  }\n}"
  },
  {
    "path": "bfg-library/src/test/scala/com/madgag/git/bfg/MessageFooterSpec.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg\n\nimport com.madgag.git.bfg.model.{CommitNode, Footer}\nimport org.eclipse.jgit.lib.PersonIdent\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\nclass MessageFooterSpec extends AnyFlatSpec with Matchers {\n\n  val person = new PersonIdent(\"Dave Eg\", \"dave@e.com\")\n\n  def commit(m: String) = CommitNode(person, person, m)\n\n  \"Message footers\" should \"append footer without new paragraph if footers already present\" in {\n\n    val updatedCommit = commit(\"Sub\\n\\nmessage\\n\\nSigned-off-by: Joe Eg <joe@e.com>\") add Footer(\"Foo\", \"Bar\")\n\n    updatedCommit.message shouldBe \"Sub\\n\\nmessage\\n\\nSigned-off-by: Joe Eg <joe@e.com>\\nFoo: Bar\"\n  }\n\n  it should \"create paragraph break if no footers already present\" in {\n\n    val updatedCommit = commit(\"Sub\\n\\nmessage\") add Footer(\"Foo\", \"Bar\")\n\n    updatedCommit.message shouldBe \"Sub\\n\\nmessage\\n\\nFoo: Bar\"\n  }\n\n  // def footersViaJGit(commit: RevCommit) = commit.getFooterLines.map(f => Footer(f.getKey, f.getValue)).toList\n}"
  },
  {
    "path": "bfg-library/src/test/scala/com/madgag/git/bfg/TreeEntrySpec.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg\n\nimport com.madgag.git.bfg.model.{FileName, Tree}\nimport org.eclipse.jgit.lib.FileMode\nimport org.eclipse.jgit.lib.FileMode._\nimport org.eclipse.jgit.lib.ObjectId.zeroId\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\nclass TreeEntrySpec extends AnyFlatSpec with Matchers {\n\n  def a(mode: FileMode, name: String) = Tree.Entry(FileName(name), mode, zeroId)\n\n  \"Tree entry ordering\" should \"match ordering used by Git\" in {\n    a(TREE, \"agit-test-utils\") should be < a(TREE, \"agit\")\n  }\n}"
  },
  {
    "path": "bfg-library/src/test/scala/com/madgag/git/bfg/cleaner/LfsBlobConverterSpec.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.madgag.diff.{After, Before, MapDiff}\nimport com.madgag.git.LFS.Pointer\nimport com.madgag.git._\nimport com.madgag.git.bfg.model.{BlobFileMode, FileName, Tree, TreeBlobs, _}\nimport com.madgag.git.test._\nimport com.madgag.scala.collection.decorators._\nimport org.eclipse.jgit.internal.storage.file.FileRepository\nimport org.eclipse.jgit.lib.ObjectId\nimport org.scalatest.concurrent.Eventually\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\nimport org.scalatest.{Inspectors, OptionValues}\n\nimport java.nio.file.Files.readAllBytes\nimport java.nio.file.{Files, Path}\n\nclass LfsBlobConverterSpec extends AnyFlatSpec with Matchers with OptionValues with Inspectors with Eventually {\n\n  \"LfsBlobConverter\" should \"successfully shift the blob to the LFS store\" in {\n    implicit val repo = unpackRepo(\"/sample-repos/example.git.zip\")\n    implicit val (revWalk, reader) = repo.singleThreadedReaderTuple\n\n    val oldTreeBlobs = Tree(repo.resolve(\"early-release^{tree}\")).blobs\n\n    val newTreeBlobs = clean(oldTreeBlobs, \"*ero*\")\n\n    val diff = oldTreeBlobs.diff(newTreeBlobs)\n\n    diff.changed shouldBe Set(FileName(\"one-kb-zeros\"))\n    diff.unchanged should contain allOf(FileName(\"hero\"), FileName(\"zero\"))\n\n    verifyPointersForChangedFiles(diff)\n  }\n\n  it should \"not do damage if run twice - ie don't create a pointer for a pointer!\" in {\n    implicit val repo = unpackRepo(\"/sample-repos/example.git.zip\")\n    implicit val (revWalk, reader) = repo.singleThreadedReaderTuple\n\n    val oldTreeBlobs = Tree(repo.resolve(\"early-release^{tree}\")).blobs\n\n    val treeBlobsAfterRun1 = clean(oldTreeBlobs, \"*ero*\")\n\n    val firstDiff = oldTreeBlobs.diff(treeBlobsAfterRun1)\n\n    firstDiff.changed shouldBe Set(FileName(\"one-kb-zeros\"))\n\n    val treeBlobsAfterRun2 = clean(treeBlobsAfterRun1, \"*ero*\")\n\n    treeBlobsAfterRun1.diff(treeBlobsAfterRun2).changed shouldBe empty\n\n    verifyPointersForChangedFiles(firstDiff) // Are the LFS files still intact?\n  }\n\n\n  def clean(oldTreeBlobs: TreeBlobs, glob: String)(implicit repo: FileRepository): TreeBlobs = {\n    val converter = new LfsBlobConverter(glob, repo)\n    converter(oldTreeBlobs)\n  }\n\n  def verifyPointerInsertedFor(fileName: FileName, diff: MapDiff[FileName, (BlobFileMode, ObjectId)])(implicit repo: FileRepository) = {\n    implicit val (revWalk, reader) = repo.singleThreadedReaderTuple\n\n    diff.changed should contain(fileName)\n\n    val fileBeforeAndAfter = diff.changedMap(fileName)\n\n    fileBeforeAndAfter(After)._1 shouldBe fileBeforeAndAfter(Before)._1\n\n    val fileIds = fileBeforeAndAfter.mapV(_._2)\n\n    val (originalFileId, pointerObjectId) = (fileIds(Before), fileIds(After))\n\n    verifyPointerFileFor(originalFileId, pointerObjectId)\n  }\n\n  def verifyPointerFileFor(originalFileId: ObjectId, pointerObjectId: ObjectId)(implicit repo: FileRepository) = {\n    implicit val (revWalk, reader) = repo.singleThreadedReaderTuple\n\n    val pointer = Pointer.parse(pointerObjectId.open.getCachedBytes)\n\n    val lfsStoredFile: Path = repo.getDirectory.toPath.resolve(Seq(\"lfs\", \"objects\") ++ pointer.path)\n\n    Files.exists(lfsStoredFile) shouldBe true\n\n    Files.size(lfsStoredFile) shouldBe pointer.blobSize\n\n    eventually { readAllBytes(lfsStoredFile).blobId } shouldBe originalFileId\n  }\n\n  def verifyPointersForChangedFiles(diff: MapDiff[FileName, (BlobFileMode, ObjectId)])(implicit repo: FileRepository) = {\n    diff.only(Before) shouldBe empty\n    diff.only(After).keys shouldBe Set(FileName(\".gitattributes\"))\n\n    forAll(diff.changed) { fileName =>\n      verifyPointerInsertedFor(fileName, diff)\n    }\n  }\n}\n"
  },
  {
    "path": "bfg-library/src/test/scala/com/madgag/git/bfg/cleaner/ObjectIdCleanerSpec.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.madgag.git._\nimport com.madgag.git.bfg.cleaner.protection.ProtectedObjectCensus\nimport com.madgag.textmatching.Literal\nimport org.eclipse.jgit.lib.ObjectId\nimport org.eclipse.jgit.revwalk.RevCommit\nimport org.scalatest.Inspectors\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.Matcher\nimport org.scalatest.matchers.should.Matchers\n\nimport scala.jdk.CollectionConverters._\n\nclass ObjectIdCleanerSpec extends AnyFlatSpec with Matchers {\n  \n  \"cleaning\" should \"not have a StackOverflowError cleaning a repo with deep history\" ignore new unpackedRepo(\"/sample-repos/deep-history.zip\") {\n    val dirtyCommitWithDeepHistory = \"d88ac4f99511667fc0617ea026f3a0ce8a25fd07\".asObjectId\n\n    val config = ObjectIdCleaner.Config(\n      ProtectedObjectCensus.None,\n      treeBlobsCleaners = Seq(new FileDeleter(Literal(\"foo\")))\n    )\n\n    ensureCleanerWith(config).removesDirtOfCommitsThat(haveFile(\"foo\")).whenCleaning(dirtyCommitWithDeepHistory)\n  }\n\n}\n\nclass unpackedRepo(filePath: String) extends bfg.test.unpackedRepo(filePath) {\n\n  class EnsureCleanerWith(config: ObjectIdCleaner.Config) {\n\n    class RemoveDirtOfCommitsThat(commitM: Matcher[RevCommit]) extends Inspectors with Matchers {\n      def histOf(c: ObjectId) = repo.git.log.add(c).call.asScala.toSeq.reverse\n\n      def whenCleaning(oldCommit: ObjectId): Unit = {\n        val cleaner = new ObjectIdCleaner(config, repo.getObjectDatabase, revWalk)\n        forAtLeast(1, histOf(oldCommit)) { commit =>\n          commit should commitM\n        }\n\n        val cleanCommit = cleaner.cleanCommit(oldCommit)\n\n        forAll(histOf(cleanCommit)) { commit =>\n          commit shouldNot commitM\n        }\n      }\n    }\n\n    def removesDirtOfCommitsThat[T](commitM: Matcher[RevCommit]) = new RemoveDirtOfCommitsThat(commitM)\n  }\n\n  def ensureCleanerWith(config: ObjectIdCleaner.Config) = new EnsureCleanerWith(config)\n}\n\n"
  },
  {
    "path": "bfg-library/src/test/scala/com/madgag/git/bfg/cleaner/ObjectIdSubstitutorSpec.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.madgag.git._\nimport com.madgag.git.bfg.cleaner.ObjectIdSubstitutor.hexRegex\nimport com.madgag.git.test._\nimport org.eclipse.jgit.lib.ObjectId\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\nclass ObjectIdSubstitutorSpec extends AnyFlatSpec with Matchers {\n\n  \"Object Id Substitutor regex\" should \"match hex strings\" in {\n    \"01234567890\" should include regex hexRegex\n\n    \"decade2001\" should include regex hexRegex\n\n    \"This is decade2001\" should include regex hexRegex\n\n    \"This is decade2001 I say\" should include regex hexRegex\n\n    \"This is Gdecade2001 I say\" shouldNot include regex hexRegex\n\n    \"This is decade2001X I say\" shouldNot include regex hexRegex\n  }\n\n  \"Object Id\" should \"be substituted in commit message\" in {\n    implicit val repo = unpackRepo(\"/sample-repos/example.git.zip\")\n    implicit val reader = repo.newObjectReader\n\n    val cleanedMessage = ObjectIdSubstitutor.OldIdsPublic.replaceOldIds(\"See 3699910d2baab1 for backstory\", reader, (_: ObjectId) => abbrId(\"06d7405020018d\"))\n\n    cleanedMessage shouldBe \"See 06d7405020018d [formerly 3699910d2baab1] for backstory\"\n  }\n\n}"
  },
  {
    "path": "bfg-library/src/test/scala/com/madgag/git/bfg/cleaner/RepoRewriteSpec.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.madgag.git._\nimport com.madgag.git.bfg.GitUtil._\nimport com.madgag.git.bfg.cleaner.ObjectIdSubstitutor._\nimport com.madgag.git.bfg.cleaner.protection.ProtectedObjectCensus\nimport com.madgag.git.bfg.model.{FileName, RegularFile, TreeBlobEntry}\nimport com.madgag.git.test._\nimport com.madgag.textmatching._\nimport org.apache.commons.io.FilenameUtils\nimport org.eclipse.jgit.lib.ObjectId\nimport org.eclipse.jgit.revwalk.RevWalk\nimport org.eclipse.jgit.util.RawParseUtils\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\nimport java.io.StringReader\nimport java.net.URLEncoder\nimport java.util.Properties\nimport java.util.regex.Pattern._\nimport scala.PartialFunction.condOpt\nimport scala.jdk.CollectionConverters._\n\nclass RepoRewriteSpec extends AnyFlatSpec with Matchers {\n\n  \"Git repo\" should \"not explode\" in {\n    implicit val repo = unpackRepo(\"/sample-repos/example.git.zip\")\n    implicit val reader = repo.newObjectReader\n\n    hasBeenProcessedByBFGBefore(repo) shouldBe false\n\n    val blobsToRemove = Set(abbrId(\"06d740\"))\n    RepoRewriter.rewrite(repo, ObjectIdCleaner.Config(ProtectedObjectCensus(Set(\"HEAD\")), OldIdsPublic, Seq(FormerCommitFooter), treeBlobsCleaners = Seq(new BlobRemover(blobsToRemove))))\n\n    val allCommits = repo.git.log.all.call.asScala.toSeq\n\n    val unwantedBlobsByCommit = allCommits.flatMap(commit => {\n      val unwantedBlobs = allBlobsReachableFrom(commit).intersect(blobsToRemove).map(_.shortName)\n      if (!unwantedBlobs.isEmpty) Some(commit.shortName -> unwantedBlobs) else None\n    }).toMap\n\n    unwantedBlobsByCommit shouldBe empty\n\n    allCommits.head.getFullMessage should include(FormerCommitFooter.Key)\n\n    hasBeenProcessedByBFGBefore(repo) shouldBe true\n  }\n\n  \"Repo rewriter\" should \"clean commit messages even on clean branches, because commit messages may reference commits from dirty ones\" in {\n    implicit val repo = unpackRepo(\"/sample-repos/taleOfTwoBranches.git.zip\")\n    implicit val revWalk = new RevWalk(repo)\n\n    def commitMessageForRev(rev: String) = repo.resolve(rev).asRevCommit.getFullMessage\n\n    commitMessageForRev(\"pure\") should include(\"6e76960ede2addbbe7e\")\n\n    RepoRewriter.rewrite(repo, ObjectIdCleaner.Config(ProtectedObjectCensus.None, OldIdsPrivate, Seq(new CommitMessageObjectIdsUpdater(OldIdsPrivate)), treeBlobsCleaners = Seq(new FileDeleter(Literal(\"sin\")))))\n\n    commitMessageForRev(\"pure\") should not include \"6e76960ede2addbbe7e\"\n  }\n\n  it should \"remove passwords\" in {\n    implicit val repo = unpackRepo(\"/sample-repos/example.git.zip\")\n    implicit val (revWalk, reader) = repo.singleThreadedReaderTuple\n\n    def propertiesIn(contents: String) = {\n      val p = new Properties()\n      p.load(new StringReader(contents))\n      p\n    }\n\n    def passwordFileContentsIn(id: ObjectId) = {\n      val cleanedPasswordFile = repo.resolve(id.name + \":folder/secret-passwords.txt\")\n      RawParseUtils.decode(reader.open(cleanedPasswordFile).getCachedBytes)\n    }\n\n    object FileExt {\n      def unapply(fileName: String) = Option(FilenameUtils.getExtension(fileName))\n    }\n\n    val blobTextModifier = new BlobTextModifier {\n      override def lineCleanerFor(entry: TreeBlobEntry) = condOpt(entry.filename.string) {\n        case FileExt(\"txt\") | FileExt(\"scala\") => \"\"\"(\\.password=).*\"\"\".r --> (_.group(1) + \"*** PASSWORD ***\")\n      }\n\n      val threadLocalObjectDBResources = repo.getObjectDatabase.threadLocalResources\n    }\n    val cleanedObjectMap = RepoRewriter.rewrite(repo, ObjectIdCleaner.Config(ProtectedObjectCensus(Set(\"HEAD\")), treeBlobsCleaners = Seq(blobTextModifier)))\n\n    val oldCommitContainingPasswords = abbrId(\"37bcc89\")\n\n    val cleanedCommitWithPasswordsRemoved = cleanedObjectMap(oldCommitContainingPasswords).asRevCommit\n\n    val originalContents = passwordFileContentsIn(oldCommitContainingPasswords)\n    val cleanedContents = passwordFileContentsIn(cleanedCommitWithPasswordsRemoved)\n\n    cleanedContents should (include(\"science\") and include(\"database.password=\"))\n    originalContents should include(\"correcthorse\")\n    cleanedContents should not include \"correcthorse\"\n\n    propertiesIn(cleanedContents).asScala.toMap should have size propertiesIn(originalContents).size\n  }\n\n\n\n\n  def textReplacementOf(parentPath: String, fileNamePrefix: String, fileNamePostfix: String, before: String, after: String) = {\n    implicit val repo = unpackRepo(\"/sample-repos/encodings.git.zip\")\n    val beforeAndAfter = Seq(before, after).map(URLEncoder.encode(_, \"UTF-8\")).mkString(\"-\")\n    val filename = s\"$fileNamePrefix-ORIGINAL.$fileNamePostfix\"\n    val beforeFile = s\"$parentPath/$filename\"\n    val afterFile = s\"$parentPath/$fileNamePrefix-MODIFIED-$beforeAndAfter.$fileNamePostfix\"\n\n    val blobTextModifier = new BlobTextModifier {\n      def lineCleanerFor(entry: TreeBlobEntry) = Some(quote(before).r --> (_ => after))\n\n      val threadLocalObjectDBResources = repo.getObjectDatabase.threadLocalResources\n    }\n\n    RepoRewriter.rewrite(repo, ObjectIdCleaner.Config(ProtectedObjectCensus.None, treeBlobsCleaners = Seq(blobTextModifier)))\n\n    val cleanedFile = repo.resolve(s\"master:$beforeFile\")\n    val expectedFile = repo.resolve(s\"master:$afterFile\")\n\n    expectedFile should not be null\n\n    implicit val threadLocalObjectReader = repo.getObjectDatabase.threadLocalResources.reader()\n    val cleaned = cleanedFile.open.getBytes\n    val expected = expectedFile.open.getBytes\n    val cleanedStr = new String(cleaned)\n    val expectedStr = new String(expected)\n\n    cleanedStr shouldBe expectedStr\n    cleanedFile shouldBe expectedFile\n  }\n\n  \"Text modifier\" should \"handle the short UTF-8\" in textReplacementOf(\"UTF-8\", \"bushhidthefacts\", \"txt\", \"facts\", \"toffee\")\n\n  it should \"handle the long UTF-8\" in textReplacementOf(\"UTF-8\", \"big\", \"scala\", \"good\", \"blessed\")\n\n  it should \"handle ASCII in SHIFT JIS\" in textReplacementOf(\"SHIFT-JIS\", \"japanese\", \"txt\", \"EUC\", \"BOOM\")\n\n  it should \"handle ASCII in ISO-8859-1\" in textReplacementOf(\"ISO-8859-1\", \"laparabla\", \"txt\", \"palpitando\", \"buscando\")\n\n  it should \"handle converting Windows newlines to Unix\" in textReplacementOf(\"newlines\", \"windows\", \"txt\", \"\\r\\n\", \"\\n\")\n\n  it should \"handle a file that uses LF for newlines\" in\n    textReplacementOf(\"newlines\", \"using-LF\", \"txt\", \"file\", \"blob\")\n\n  it should \"handle a file that uses CRLF for newlines\" in\n    textReplacementOf(\"newlines\", \"using-CRLF\", \"txt\", \"file\", \"blob\")\n\n}\n"
  },
  {
    "path": "bfg-library/src/test/scala/com/madgag/git/bfg/cleaner/TreeBlobModifierSpec.scala",
    "content": "/*\n * Copyright (c) 2012 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.cleaner\n\nimport com.google.common.util.concurrent.AtomicLongMap\nimport com.madgag.git.bfg.cleaner.ObjectIdSubstitutor._\nimport com.madgag.git.bfg.cleaner.protection.ProtectedObjectCensus\nimport com.madgag.git.bfg.model.TreeBlobEntry\nimport com.madgag.git.test._\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\nimport scala.jdk.CollectionConverters._\n\nclass TreeBlobModifierSpec extends AnyFlatSpec with Matchers {\n\n  \"TreeBlobModifier\" should \"only clean a given tree entry once\" in {\n    class CountingTreeBlobModifier extends TreeBlobModifier {\n      val counts = AtomicLongMap.create[TreeBlobEntry]\n\n      def fix(entry: TreeBlobEntry) = {\n        counts.incrementAndGet(entry)\n        (entry.mode, entry.objectId)\n      }\n    }\n\n    implicit val repo = unpackRepo(\"/sample-repos/taleOfTwoBranches.git.zip\")\n\n    val countingTreeBlobModifier = new CountingTreeBlobModifier()\n\n    RepoRewriter.rewrite(repo, ObjectIdCleaner.Config(ProtectedObjectCensus(Set(\"HEAD\")), OldIdsPublic, treeBlobsCleaners = Seq(countingTreeBlobModifier)))\n\n    val endCounts = countingTreeBlobModifier.counts.asMap().asScala.toMap\n\n    endCounts.size should be >= 4\n    all (endCounts.values) shouldBe 1\n  }\n}\n"
  },
  {
    "path": "bfg-library/src/test/scala/com/madgag/git/bfg/model/CommitSpec.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.git.bfg.model\n\nimport com.madgag.git.bfg.test.unpackedRepo\nimport org.scalatest.Inspectors\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\nclass CommitSpec extends AnyFlatSpec with Matchers with Inspectors {\n  \"Commit model\" should \"calculate the same Git commit id for any given commit\" in new unpackedRepo(\"/sample-repos/example.git.zip\") {\n    forAll (commitHist()) { revCommit =>\n      Commit(revCommit).id shouldBe revCommit.toObjectId\n    }\n  }\n\n}\n"
  },
  {
    "path": "bfg-library/src/test/scala/com/madgag/text/ByteSizeSpecs.scala",
    "content": "/*\n * Copyright (c) 2012, 2013 Roberto Tyley\n *\n * This file is part of 'BFG Repo-Cleaner' - a tool for removing large\n * or troublesome blobs from Git repositories.\n *\n * BFG Repo-Cleaner is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BFG Repo-Cleaner is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http://www.gnu.org/licenses/ .\n */\n\npackage com.madgag.text\n\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\n\nclass ByteSizeSpecs extends AnyFlatSpec with Matchers {\n  \"Size parser\" should \"understand 1B\" in {\n    ByteSize.parse(\"0B\") shouldBe 0\n    ByteSize.parse(\"1B\") shouldBe 1\n    ByteSize.parse(\"2B\") shouldBe 2\n    ByteSize.parse(\"10B\") shouldBe 10\n  }\n  it should \"understand 3G\" in {\n    ByteSize.parse(\"3G\") shouldBe 3L * 1024 * 1024 * 1024\n  }\n  it should \"understand 1G\" in {\n    ByteSize.parse(\"1G\") shouldBe 1024 * 1024 * 1024\n  }\n  it should \"understand 1M\" in {\n    ByteSize.parse(\"1M\") shouldBe 1024 * 1024\n  }\n  it should \"understand 3500M\" in {\n    ByteSize.parse(\"3500M\") shouldBe 3500L * 1024 * 1024\n  }\n  it should \"understand 1K\" in {\n    ByteSize.parse(\"1K\") shouldBe 1024\n  }\n  it should \"understand 5K\" in {\n    ByteSize.parse(\"5K\") shouldBe 5 * 1024\n  }\n  it should \"reject strings without a unit\" in {\n    an[IllegalArgumentException] should be thrownBy ByteSize.parse(\"1232\")\n  }\n\n  \"Size formatter\" should \"correctly format\" in {\n    ByteSize.format(1024) shouldBe \"1.0 KB\"\n  }\n}\n"
  },
  {
    "path": "bfg-test/build.sbt",
    "content": "import Dependencies._\n\nlibraryDependencies ++= Seq(scalatest, jgit, scalaGit, scalaGitTest)\n\n"
  },
  {
    "path": "bfg-test/src/main/scala/com/madgag/git/bfg/test/unpackedRepo.scala",
    "content": "package com.madgag.git.bfg.test\n\nimport com.madgag.git._\nimport com.madgag.git.test._\nimport org.eclipse.jgit.internal.storage.file.{FileRepository, GC, ObjectDirectory}\nimport org.eclipse.jgit.lib.Constants.OBJ_BLOB\nimport org.eclipse.jgit.lib.{ObjectId, ObjectReader, Repository}\nimport org.eclipse.jgit.revwalk.{RevCommit, RevTree, RevWalk}\nimport org.eclipse.jgit.treewalk.TreeWalk\nimport org.scalatest.Inspectors\nimport org.scalatest.flatspec.AnyFlatSpec\nimport org.scalatest.matchers.should.Matchers\nimport org.scalatest.matchers.{MatchResult, Matcher}\n\nimport scala.jdk.CollectionConverters._\n\nclass unpackedRepo(filePath: String) extends AnyFlatSpec with Matchers {\n\n  implicit val repo: FileRepository = unpackRepo(filePath)\n  implicit val objectDirectory: ObjectDirectory = repo.getObjectDatabase\n  implicit lazy val (revWalk: RevWalk, reader: ObjectReader) = repo.singleThreadedReaderTuple\n\n\n  def blobOfSize(sizeInBytes: Int): Matcher[ObjectId] = Matcher { (objectId: ObjectId) =>\n    val objectLoader = objectId.open\n    val hasThatSize = objectLoader.getType == OBJ_BLOB && objectLoader.getSize == sizeInBytes\n    def thing(boo: String) = s\"${objectId.shortName} $boo size of $sizeInBytes\"\n    MatchResult(hasThatSize, thing(\"did not have\"), thing(\"had\"))\n  }\n\n  def packedBlobsOfSize(sizeInBytes: Long): Set[ObjectId] = {\n    implicit val reader: ObjectReader = repo.newObjectReader()\n    repo.getObjectDatabase.packedObjects.filter { objectId =>\n      val objectLoader = objectId.open\n      objectLoader.getType == OBJ_BLOB && objectLoader.getSize == sizeInBytes\n    }.toSet\n  }\n\n  def haveFile(name: String): Matcher[ObjectId] = haveTreeEntry(name, !_.isSubtree)\n\n  def haveFolder(name: String): Matcher[ObjectId] = haveTreeEntry(name, _.isSubtree)\n\n  def haveTreeEntry(name: String, p: TreeWalk => Boolean)= new Matcher[ObjectId] {\n    def apply(treeish: ObjectId) = {\n      treeOrBlobPointedToBy(treeish.asRevObject) match {\n        case Right(tree) =>\n          def thing(boo: String) = s\"tree ${treeish.shortName} $boo a '$name' entry\"\n          MatchResult(\n            treeEntryNames(tree, p).contains(name),\n            thing(\"did not contain\"),\n            thing(\"contained\")\n          )\n        case Left(blob) =>\n          MatchResult(\n            false,\n            s\"blob ${treeish.shortName} was not a tree containing '$name'\",\n            s\"\"\"When does this happen??!\"\"\"\"\n          )\n      }\n    }\n  }\n\n  def treeEntryNames(t: RevTree, p: TreeWalk => Boolean): Seq[String] =\n    t.walk(postOrderTraversal = true).withFilter(p).map(_.getNameString).toList\n\n  def commitHist(specificRefs: String*)(implicit repo: Repository): Seq[RevCommit] = {\n    val logCommand = repo.git.log\n    if (specificRefs.isEmpty) logCommand.all else specificRefs.foldLeft(logCommand)((lc, ref) => lc.add(repo.resolve(ref)))\n  }.call.asScala.toSeq.reverse\n\n  def haveCommitWhereObjectIds(boom: Matcher[Iterable[ObjectId]])(implicit reader: ObjectReader): Matcher[RevCommit] = boom compose {\n    (c: RevCommit) => c.getTree.walk().map(_.getObjectId(0)).toSeq\n  }\n\n  def haveRef(refName: String, objectIdMatcher: Matcher[ObjectId]): Matcher[Repository] = objectIdMatcher compose {\n    (r: Repository) => r resolve refName // aka s\"Ref [$refName]\"\n  }\n\n  def commitHistory(histMatcher: Matcher[Seq[RevCommit]]) = histMatcher compose {\n    r: Repository => commitHist()(r)\n  }\n\n  def commitHistoryFor(refs: String*)(histMatcher: Matcher[Seq[RevCommit]]) = histMatcher compose {\n    r: Repository => commitHist(refs:_*)(r)\n  }\n\n  def ensureRemovalOfBadEggs[S,T](expr : => Iterable[S], exprResultMatcher: Matcher[Iterable[S]])(block: => T) = {\n    gc()\n    expr should exprResultMatcher\n\n    block\n\n    gc()\n    expr shouldBe empty\n  }\n\n  def gc() = {\n    val gc = new GC(repo)\n    gc.setPackExpireAgeMillis(0)\n    gc.gc()\n  }\n\n\n  class CheckRemovalFromCommits(commits: => Seq[RevCommit]) extends Inspectors {\n    def ofCommitsThat[T](commitM: Matcher[RevCommit])(block: => T): Unit = {\n      forAtLeast(1, commits) { commit =>\n        commit should commitM\n      }\n\n      block\n\n      forAll(commits) { commit =>\n        commit shouldNot commitM\n      }\n    }\n  }\n\n\n  def ensureRemovalFrom(commits: => Seq[RevCommit]): CheckRemovalFromCommits = new CheckRemovalFromCommits(commits)\n\n  def ensureInvariantValue[T, S](f: => S)(block: => T) = {\n    val originalValue = f\n    block\n    f should equal(originalValue)\n  }\n\n  def ensureInvariantCondition[T, S](cond: Matcher[Repository])(block: => T) = {\n    repo should cond\n    block\n    repo should cond\n  }\n\n}\n"
  },
  {
    "path": "build.sbt",
    "content": "import ReleaseTransformations.*\nimport Dependencies.*\n\nThisBuild / organization := \"com.madgag\"\n\nThisBuild / scalaVersion := \"2.13.16\"\n\nThisBuild / scalacOptions ++= Seq(\"-deprecation\", \"-feature\", \"-language:postfixOps\", \"-release:11\")\n\nThisBuild / licenses := Seq(License.GPL3_or_later)\n\nThisBuild / resolvers ++= jgitVersionOverride.map(_ => Resolver.mavenLocal).toSeq\n\nThisBuild / libraryDependencies += scalatest % Test\n\nThisBuild / Test/ testOptions += Tests.Argument(\n  TestFrameworks.ScalaTest,\n  \"-u\", s\"test-results/scala-${scalaVersion.value}\"\n)\n\nlazy val root = Project(id = \"bfg-parent\", base = file(\".\")).aggregate (bfg, `bfg-test`, `bfg-library`).settings(\n  publish / skip := true,\n  releaseCrossBuild := true, // true if you cross-build the project for multiple Scala versions\n  releaseProcess := Seq[ReleaseStep](\n    checkSnapshotDependencies,\n    inquireVersions,\n    runClean,\n    runTest,\n    setReleaseVersion,\n    commitReleaseVersion,\n    tagRelease,\n    setNextVersion,\n    commitNextVersion\n  )\n)\n\nlazy val `bfg-test` = project\n\nlazy val `bfg-library` = project.dependsOn(`bfg-test` % Test)\n\nlazy val bfg = project.enablePlugins(BuildInfoPlugin).dependsOn(`bfg-library`, `bfg-test` % Test)\n\nlazy val `bfg-benchmark` = project\n"
  },
  {
    "path": "project/build.properties",
    "content": "sbt.version=1.10.7\n"
  },
  {
    "path": "project/dependencies.scala",
    "content": "import sbt._\n\nobject Dependencies {\n\n  val scalaGitVersion = \"5.0.3\"\n\n  val jgitVersionOverride = Option(System.getProperty(\"jgit.version\"))\n\n  val jgitVersion = jgitVersionOverride.getOrElse(\"6.10.0.202406032230-r\")\n\n  val jgit = \"org.eclipse.jgit\" % \"org.eclipse.jgit\" % jgitVersion\n\n  // this matches slf4j-api in jgit's dependencies\n  val slf4jSimple = \"org.slf4j\" % \"slf4j-simple\" % \"1.7.36\"\n\n  val scalaCollectionPlus =  \"com.madgag\" %% \"scala-collection-plus\" % \"0.11\"\n\n  val parCollections = \"org.scala-lang.modules\" %% \"scala-parallel-collections\" % \"1.2.0\"\n\n  val scalaGit = \"com.madgag.scala-git\" %% \"scala-git\" % scalaGitVersion exclude(\"org.eclipse.jgit\", \"org.eclipse.jgit\")\n\n  val scalaGitTest = \"com.madgag.scala-git\" %% \"scala-git-test\" % scalaGitVersion\n\n  val scalatest = \"org.scalatest\" %% \"scalatest\" % \"3.2.19\"\n\n  val madgagCompress = \"com.madgag\" % \"util-compress\" % \"1.35\"\n\n  val textmatching = \"com.madgag\" %% \"scala-textmatching\" % \"2.8\"\n\n  val scopt = \"com.github.scopt\" %% \"scopt\" % \"3.7.1\"\n\n  val guava = Seq(\"com.google.guava\" % \"guava\" % \"33.4.0-jre\", \"com.google.code.findbugs\" % \"jsr305\" % \"3.0.2\")\n\n  val useNewerJava =  \"com.madgag\" % \"use-newer-java\" % \"1.0.2\"\n\n  val lineSplitting = \"com.madgag\" %% \"line-break-preserving-line-splitting\" % \"0.1.6\"\n\n}\n"
  },
  {
    "path": "project/plugins.sbt",
    "content": "addSbtPlugin(\"com.github.sbt\" % \"sbt-release\" % \"1.4.0\")\n\naddSbtPlugin(\"org.xerial.sbt\" % \"sbt-sonatype\" % \"3.12.2\")\n\naddSbtPlugin(\"ch.epfl.scala\" % \"sbt-version-policy\" % \"3.2.1\")\n\naddSbtPlugin(\"com.eed3si9n\" % \"sbt-assembly\" % \"2.3.0\")\n\naddSbtPlugin(\"com.eed3si9n\" % \"sbt-buildinfo\" % \"0.13.1\")\n\naddDependencyTreePlugin"
  },
  {
    "path": "version.sbt",
    "content": "ThisBuild / version := \"1.15.1-SNAPSHOT\"\n"
  }
]