├── .github ├── CONTRIBUTING.md ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .idea └── vcs.xml ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md └── deep-clean.kts /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a code of conduct, please follow it in all your interactions with the project. 7 | 8 | ## Pull Request Process 9 | 10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a 11 | build. 12 | 2. Update the README.md with details of changes to the interface, this includes new environment 13 | variables, exposed ports, useful file locations and container parameters. 14 | 3. Increase the version numbers in any examples files and the README.md to the new version that this 15 | Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). 16 | 4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you 17 | do not have permission to do that, you may request the second reviewer to merge it for you. 18 | 19 | (adapted from [this template](https://gist.github.com/PurpleBooth/b24679402957c63ec426)) 20 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [ rock3r ] 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior: 12 | 1. Go to '...' 13 | 2. Click on '....' 14 | 3. Scroll down to '....' 15 | 4. See error 16 | 17 | **Expected behavior** 18 | A clear and concise description of what you expected to happen. 19 | 20 | **Screenshots** 21 | If applicable, add screenshots to help explain your problem. 22 | 23 | **System information** 24 | - OS version: [e.g., macOS 10.13.5] 25 | - Kotlin version: [e.g., 1.2.50 (run `kotlinc -version`)] 26 | - Maven version: [e.g., 3.5.3 (run `mvn -version`)] 27 | - KScript version: [e.g., (run `kscript`)] 28 | - Script version: [e.g., 1.0.1 (run `deep-clean.kts --version`)] 29 | 30 | **Additional context** 31 | Add any other context about the problem here. 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | _What is the aim of this PR?_ 2 | 3 | ## Implemented solution 4 | 5 | _How does this PR achieve said goal? Explain at a high level the implementation._ 6 | 7 | ## REQUIRED: pre-PR checklist 8 | 9 | * [ ] The project compiles/runs 10 | * [ ] The implemented solution works as intended 11 | * [ ] Dry-run (`-d`) doesn't actually perform any action besides logging 12 | * [ ] The `README.md` file has been updated 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Seb's .gitignore template 2 | # You can find the most up-to-date version at https://go.sebastiano.dev/gitignore 3 | # Partly based on templates by https://plugins.jetbrains.com/plugin/7495--ignore 4 | 5 | ### Windows template 6 | # Windows thumbnail cache files 7 | Thumbs.db 8 | Thumbs.db:encryptable 9 | ehthumbs.db 10 | ehthumbs_vista.db 11 | 12 | # Dump file 13 | *.stackdump 14 | 15 | # Folder config file 16 | [Dd]esktop.ini 17 | 18 | # Recycle Bin used on file shares 19 | $RECYCLE.BIN/ 20 | 21 | # Windows Installer files 22 | *.cab 23 | *.msi 24 | *.msix 25 | *.msm 26 | *.msp 27 | 28 | # Windows shortcuts 29 | *.lnk 30 | 31 | ### macOS template 32 | # General 33 | .DS_Store 34 | .AppleDouble 35 | .LSOverride 36 | 37 | # Icon must end with two \r 38 | Icon 39 | 40 | # Thumbnails 41 | ._* 42 | 43 | # Files that might appear in the root of a volume 44 | .DocumentRevisions-V100 45 | .fseventsd 46 | .Spotlight-V100 47 | .TemporaryItems 48 | .Trashes 49 | .VolumeIcon.icns 50 | .com.apple.timemachine.donotpresent 51 | 52 | # Directories potentially created on remote AFP share 53 | .AppleDB 54 | .AppleDesktop 55 | Network Trash Folder 56 | Temporary Items 57 | .apdisk 58 | 59 | ### Linux template 60 | *~ 61 | 62 | # temporary files which can be created if a process still has a handle open of a deleted file 63 | .fuse_hidden* 64 | 65 | # KDE directory preferences 66 | .directory 67 | 68 | # Linux trash folder which might appear on any partition or disk 69 | .Trash-* 70 | 71 | # .nfs files are created when an open file is removed but is still being accessed 72 | .nfs* 73 | 74 | ### JetBrains template 75 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 76 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 77 | 78 | *.iml 79 | *.ipr 80 | *.iws 81 | /.idea/* 82 | 83 | # Exclude non-user-specific stuff 84 | !.idea/.name 85 | !.idea/codeInsightSettings.xml 86 | !.idea/codeStyles/ 87 | !.idea/copyright/ 88 | !.idea/dataSources.xml 89 | !.idea/detekt.xml 90 | !.idea/encodings.xml 91 | !.idea/externalDependencies.xml 92 | !.idea/file.template.settings.xml 93 | !.idea/fileTemplates/ 94 | !.idea/icon.svg 95 | !.idea/inspectionProfiles/ 96 | !.idea/runConfigurations/ 97 | !.idea/scopes/ 98 | !.idea/vcs.xml 99 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [@seebrock3r](https://twitter.com/@seebrock3r). The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # deep-clean 2 | A Kotlin script that nukes all build caches from Gradle/Android projects. 3 | Useful when Gradle or the IDE let you down 💔 4 | 5 | ![deep-clean in action](https://user-images.githubusercontent.com/153802/41173653-ab0ae36c-6b4f-11e8-8f98-8dba4340add7.png) 6 | 7 | 🎩 h/t to [@Takhion](https://github.com/Takhion) for the original idea, and to 8 | [@holgerbrandl](https://github.com/holgerbrandl) for KScript. 9 | 10 | The script has been tested on macOS 🍎, but it is completely untested on 11 | Linux 🐧 and Windows 🖥️. KScript may not work at all on Windows! 12 | 13 | ⚠️There may be [major issues](https://github.com/rock3r/deep-clean/issues/4) on Windows/Linux when using `-n`, 14 | please let me know if you encounter any such issue! 15 | 16 | **USE AT YOUR OWN RISK IN ANY CASE!** 17 | 18 | ## Running the script 19 | 20 | `deep-clean` requires three components to be on your `PATH`: 21 | * [`kotlinc`](https://kotlinlang.org/docs/tutorials/command-line.html) 22 | * [`kscript`](https://github.com/holgerbrandl/kscript) 23 | * [`mvn`](https://maven.apache.org/) 24 | 25 | If you **have all three commands** on your `PATH`, then you can simply download 26 | and execute the script: 27 | 28 | ```bash 29 | $ cd /your/project/root.folder 30 | $ [kscript] deep-clean.kts [options] 31 | ``` 32 | 33 | >Note: on macOS and Linux the script does not need `kscript` to be invoked, because 34 | >it has a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)). On Windows, you 35 | >will need to explicitly specify you want to use `kscript` to run it. 36 | 37 | Where the options are: 38 | 39 | ``` 40 | -b --backup Renames files and folders instead of deleting them. Implies 41 | --verbose. 42 | -d --dry-run Don't delete anything. Useful for testing. Implies --verbose. 43 | -i --ide-files This also deletes IDEA/Android Studio project files (*.iml). 44 | If used in conjunction with --nuke it will also delete the 45 | .idea folder in the current directory. 46 | -p --ide-preferences ⚠️ THIS IS DANGEROUS SHIT ⚠️ Will wipe your IDE settings! 47 | This deletes the GLOBAL IDEA/Android Studio preferences. 48 | This option requires the --nuke option to be active too, since 49 | it touches global system state. 50 | --not-recursive Don't recursively search sub-folders of this folder for matches. 51 | The default behaviour is to look for matches in sub-directories, 52 | since things like 'build' folders and '.iml' files are not all 53 | found at the top level of a project directory structure. This 54 | flag is useful if you know you have matches you want to keep, 55 | e.g., if your code contains a package with a name like 'build'. 56 | This option severely limits the effectiveness of the deep clean. 57 | -n --nuke ⚠️ THIS IS DANGEROUS SHIT ⚠️ Super-deep clean 58 | This includes clearing out global folders, including: 59 | * the global Gradle cache 60 | * the global Maven artefacts 61 | * the wrapper-downloaded Gradle distros 62 | * the Gradle daemon data (logs, locks, etc.) 63 | * the Android build cache 64 | Nukes the entire thing from orbit — it's the only way to be sure. 65 | -v --verbose Print detailed information about all commands. 66 | ``` 67 | 68 | For this script to work, you need to have `kotlin`, `kscript` and `maven` on your `PATH`. 69 | If you **DON'T have all three commands** on your `PATH`, then read on to the next 70 | section to install them. 71 | 72 | ## Installing the script dependencies 73 | 74 | To make the script run, we'll first need to install all the required dependencies. 75 | All dependencies are available on [SDKMan!](https://sdkman.io/) (Windows, Linux, macOS). 76 | **Note that KScript support for Windows is not officially available yet**. 77 | 78 | ```bash 79 | $ sdk install kotlin 80 | $ sdk install maven 81 | $ sdk install kscript 82 | ``` 83 | 84 | ## Licence 85 | 86 | ``` 87 | Copyright 2022 Sebastiano Poggi 88 | 89 | Licensed under the Apache License, Version 2.0 (the "License"); 90 | you may not use this file except in compliance with the License. 91 | You may obtain a copy of the License at 92 | 93 | http://www.apache.org/licenses/LICENSE-2.0 94 | 95 | Unless required by applicable law or agreed to in writing, software 96 | distributed under the License is distributed on an "AS IS" BASIS, 97 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 98 | See the License for the specific language governing permissions and 99 | limitations under the License. 100 | ``` 101 | 102 | For more information please refer to the [`LICENSE`](LICENSE) file. 103 | -------------------------------------------------------------------------------- /deep-clean.kts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env kscript 2 | 3 | @file:DependsOn("com.offbytwo:docopt:0.6.0.20150202") 4 | 5 | import org.docopt.Docopt 6 | import java.io.File 7 | import java.nio.file.Files 8 | import java.nio.file.Paths 9 | import java.util.concurrent.TimeUnit 10 | import kotlin.system.exitProcess 11 | 12 | typealias CommandLineArguments = Map 13 | 14 | val usage = """ 15 | This script nukes all build caches from Gradle/Android projects. 16 | Run this in a Gradle/Android project folder. 17 | 18 | Usage: deep-clean [options] 19 | 20 | Options: 21 | -b --backup Renames files and folders instead of deleting them. Implies 22 | --verbose. 23 | -d --dry-run Don't delete anything. Useful for testing. Implies --verbose. 24 | -i --ide-files This also deletes IDEA/Android Studio project files (*.iml). 25 | If used in conjunction with --nuke it will also delete the 26 | .idea folder in the current directory. 27 | -p --ide-preferences ⚠️ THIS IS DANGEROUS SHIT ⚠️ Will wipe your IDE settings! 28 | This deletes the GLOBAL IDEA/Android Studio preferences. 29 | This option requires the --nuke option to be active too, since 30 | it touches global system state. 31 | --not-recursive Don't recursively search sub-folders of this folder for matches. 32 | The default behaviour is to look for matches in sub-directories, 33 | since things like 'build' folders and '.iml' files are not all 34 | found at the top level of a project directory structure. This 35 | flag is useful if you know you have matches you want to keep, 36 | e.g., if your code contains a package with a name like 'build'. 37 | This option severely limits the effectiveness of the deep clean. 38 | -n --nuke ⚠️ THIS IS DANGEROUS SHIT ⚠️ Super-deep clean 39 | This includes clearing out global folders, including: 40 | * the global Gradle cache 41 | * the global Maven artefacts 42 | * the wrapper-downloaded Gradle distros 43 | * the Gradle daemon data (logs, locks, etc.) 44 | * the Android build cache 45 | Nukes the entire thing from orbit — it's the only way to be sure. 46 | -v --verbose Print detailed information about all commands. 47 | """ 48 | 49 | val userHome = File(System.getProperty("user.home")) 50 | val gradleHome = locateGradleHome() 51 | val mavenLocalRepository = locateMavenLocalRepository() 52 | 53 | val workingDir = File(Paths.get("").toAbsolutePath().toString()) 54 | 55 | assert(userHome.exists()) { "Unable to determine the user home folder, aborting..." } 56 | 57 | val parsedArgs: CommandLineArguments = Docopt(usage) 58 | .withVersion("deep-clean 1.5.0") 59 | .parse(args.toList()) 60 | 61 | val nukeItFromOrbit = parsedArgs.isFlagSet("--nuke", "-n") 62 | val ideFiles = parsedArgs.isFlagSet("--ide-files", "-i") 63 | val shouldAlsoClearIdePreferences = parsedArgs.isFlagSet("--ide-preferences", "-p") 64 | val idePreferences = shouldAlsoClearIdePreferences && nukeItFromOrbit 65 | val recursively = parsedArgs.isFlagSet("--not-recursive").not() 66 | val dryRun = parsedArgs.isFlagSet("--dry-run", "-d") 67 | val backup = parsedArgs.isFlagSet("--backup", "-b") 68 | val verbose = backup || dryRun || parsedArgs.isFlagSet("--verbose", "-v") 69 | 70 | if (shouldAlsoClearIdePreferences != idePreferences) { 71 | println("\n⚠️ To clear the IDE preferences you must also enable nuke mode.") 72 | } 73 | 74 | if (dryRun) println("\nℹ️ This is a dry-run. No files will be moved/deleted.\n") 75 | 76 | val wetRun = dryRun.not() 77 | val gradlew = "./gradlew" + if (isOsWindows()) ".bat" else "" 78 | 79 | if (!File(gradlew.removePrefix("./")).exists()) { 80 | printInBold("❌ Could not find Gradle wrapper in the work directory: $gradlew") 81 | exitProcess(-1) 82 | } 83 | 84 | Runtime.getRuntime().apply { 85 | printInBold("⏳ Executing Gradle clean...") 86 | doWithGradleWrapper { 87 | execOnWetRun("$gradlew clean -q") 88 | ?.printOutput(onlyErrors = !verbose) 89 | } 90 | println() 91 | 92 | printInBold("🔫 Killing Gradle daemon...") 93 | doWithGradleWrapper { 94 | execOnWetRun("$gradlew --stop") 95 | ?.printOutput() 96 | } 97 | println() 98 | 99 | printInBold("🔫 Killing ADB server...") 100 | killAdb() 101 | println() 102 | 103 | printInBold("🔥 Removing every 'build' folder...") 104 | workingDir.removeSubfoldersMatching { it.name.equals("build", ignoreCase = true) } 105 | println() 106 | 107 | printInBold("🔥 Removing every '.gradle' folder...") 108 | workingDir.removeSubfoldersMatching { it.name.equals(".gradle", ignoreCase = true) } 109 | println() 110 | 111 | if (ideFiles) deleteIdeaProjectFiles() 112 | 113 | if (idePreferences) { 114 | printIdePreferencesWarning(timeoutSeconds = 3) 115 | 116 | clearIdePreferences() 117 | } 118 | 119 | if (nukeItFromOrbit) { 120 | printNukeModeWarning(timeoutSeconds = 3) 121 | 122 | if (ideFiles) nukeIdeaProjectSettingsFolder() 123 | 124 | nukeGlobalCaches() 125 | } 126 | 127 | printInBold("🔫 Killing Kotlin compile daemon...") 128 | println(" ℹ️ Note: this kills any CLI Java instance running (including this script)") 129 | execOnWetRun("killall java") 130 | println() 131 | } 132 | 133 | //////////////////////////////////////////////////////////////////////////////////////////////// 134 | //////////////////////////////////////////////////////////////////////////////////////////////// 135 | //////////////////////////////////////////////////////////////////////////////////////////////// 136 | 137 | fun locateGradleHome(): File? { 138 | val envGradleHome = System.getenv("GRADLE_HOME") 139 | ?.let { File(it) } 140 | val userGradleHome = File(userHome, ".gradle") 141 | 142 | return when { 143 | envGradleHome?.exists() == true -> envGradleHome 144 | userGradleHome.exists() -> userGradleHome 145 | else -> null 146 | } 147 | } 148 | 149 | fun locateMavenLocalRepository(): File? { 150 | return File(userHome, ".m2").takeIf { it.exists() } 151 | } 152 | 153 | fun CommandLineArguments.isFlagSet(vararg flagAliases: String): Boolean = 154 | flagAliases.map { this[it] as Boolean? } 155 | .first { it != null }!! 156 | 157 | fun Runtime.execOnWetRun(command: String) = if (wetRun) exec(command) else null 158 | 159 | fun Process.printOutput(onlyErrors: Boolean = true) { 160 | if (onlyErrors.not()) { 161 | inputStream.bufferedReader().lines().forEach { println(" $it") } 162 | } 163 | errorStream.bufferedReader().lines().forEach { println(" $it") } 164 | } 165 | 166 | fun Process.printIfNoError(message: String) { 167 | if (errorStream.bufferedReader().lineSequence().none()) { 168 | println(" $message") 169 | } 170 | } 171 | 172 | fun Runtime.doWithGradleWrapper(action: () -> Unit) { 173 | if (!Files.exists(Paths.get("gradlew")) && !isExecutableOnPath("adb")) { 174 | println("⚠️ Gradle wrapper not found. Nothing to do here.") 175 | return 176 | } 177 | 178 | action() 179 | } 180 | 181 | fun Runtime.killAdb() { 182 | if (!isExecutableOnPath("adb")) { 183 | println("⚠️ ADB not found. Nothing to do here.") 184 | return 185 | } 186 | 187 | execOnWetRun("adb kill-server") 188 | ?.printIfNoError("Adb server killed.") 189 | execOnWetRun("killall adb") 190 | } 191 | 192 | fun Runtime.isExecutableOnPath(executableName: String) = 193 | System.getenv("PATH").split(File.pathSeparator) 194 | .map(Paths::get) 195 | .any { pathEntry -> Files.exists(pathEntry.resolve(executableName)) } 196 | 197 | fun deleteIdeaProjectFiles() { 198 | printInBold("🔥 Removing IntelliJ IDEA/Android Studio '.iml' project files...") 199 | workingDir.removeFilesWithExtension("iml") 200 | println() 201 | } 202 | 203 | fun File.removeFilesWithExtension(extension: String) { 204 | val matchingFiles = this 205 | .listContents(recursively = recursively) { 206 | !it.isDirectory && it.extension.equals(extension, ignoreCase = true) 207 | } 208 | 209 | when { 210 | backup -> matchingFiles.backupAndDeleteByRenaming() 211 | else -> matchingFiles.deleteRecursively() 212 | } 213 | } 214 | 215 | fun printIdePreferencesWarning(timeoutSeconds: Long) { 216 | printInBold("⚠️ ⚠️ ⚠️ ⚠️ WARNING: deleting IDE settings ⚠️ ⚠️ ⚠️ ⚠️ ") 217 | println() 218 | println(" ( . )") 219 | println(" ) ( )") 220 | println(" . ' . ' . ' .") 221 | println(" ( , ) (. ) ( ', )") 222 | println(" .' ) ( . ) , ( , ) ( .") 223 | println(" ). , ( . ( ) ( , ') .' ( , )") 224 | println(" (_,) . ), ) _) _,') (, ) '. ) ,. (' )") 225 | println(" jgs^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^") 226 | println() 227 | println("⚠️ This will reset all your IDE preferences! ⚠️") 228 | println() 229 | printInBold(" ⏲️ You have $timeoutSeconds seconds to cancel! ⏲️") 230 | println(" Press Ctrl-C to stop now.") 231 | println() 232 | println() 233 | 234 | Thread.sleep(TimeUnit.SECONDS.toMillis(timeoutSeconds)) 235 | } 236 | 237 | fun clearIdePreferences() { 238 | printInBold("🔥 Clearing ${Ide.IntelliJIdea} preferences...") 239 | clearIdePreferences(Ide.IntelliJIdea) 240 | println() 241 | 242 | printInBold("🔥 Clearing ${Ide.AndroidStudio} preferences...") 243 | clearIdePreferences(Ide.AndroidStudio) 244 | println() 245 | } 246 | 247 | fun clearIdePreferences(ide: Ide) { 248 | val preferencesDirectories = locatePreferencesFolderFor(ide) 249 | 250 | when { 251 | backup -> preferencesDirectories 252 | .onEach { 253 | println(" ℹ️ Clearing preferences for $ide ${extractVersion(it, ide)}...") 254 | } 255 | .backupAndDeleteByRenaming() 256 | else -> preferencesDirectories 257 | .onEach { 258 | println(" ℹ️ Clearing preferences for $ide ${extractVersion(it, ide)}...") 259 | } 260 | .deleteRecursively() 261 | } 262 | } 263 | 264 | fun locatePreferencesFolderFor(ide: Ide): Sequence = 265 | when { 266 | isOsWindows() || isOsLinux() -> { 267 | userHome.listContents(recursively = false) { 268 | it.isDirectory && it.name.startsWith(".${ide.folderPrefix}") 269 | } 270 | } 271 | isOsMacOs() -> { 272 | File(userHome, "Library/Preferences") 273 | .listContents(recursively = false) { 274 | it.isDirectory && it.name.startsWith(ide.folderPrefix, ignoreCase = true) 275 | } 276 | } 277 | else -> { 278 | println(" ⚠️ Unsupported OS, skipping.") 279 | emptySequence() 280 | } 281 | } 282 | .filter { it.exists() } 283 | 284 | fun nukeIdeaProjectSettingsFolder() { 285 | printInBold("🔥 Removing IntelliJ IDEA/Android Studio '.idea' folders...") 286 | 287 | workingDir.removeSubfoldersMatching { 288 | it.isDirectory && it.name.equals(".idea", ignoreCase = true) 289 | } 290 | println() 291 | } 292 | 293 | fun printNukeModeWarning(timeoutSeconds: Long) { 294 | printInBold("☢️ ☢️ ☢️ ☢️ WARNING: nuke mode activated ☢️ ☢️ ☢️ ☢️ ") 295 | println() 296 | println(" __,-~~/~ `---.") 297 | println(" _/_,---( , )") 298 | println(" __ / < / ) \\___") 299 | println("- ------===;;;'====------------------===;;;===----- - -") 300 | println(" \\/ ~\"~\"~\"~\"~\"~\\~\"~)~\"/") 301 | println(" (_ ( \\ ( > \\)") 302 | println(" \\_( _ < >_>'") 303 | println(" ~ `-i' ::>|--\"") 304 | println(" I;|.|.|") 305 | println(" <|i::|i|`.") 306 | println(" (` ^'\"`-' \")") 307 | println("------------------------------------------------------------------") 308 | println("") 309 | println("⚠️ This will affect system-wide caches for Gradle and IDEs! ⚠️") 310 | println("⚠️ You will lose local version history and other IDE data! ⚠️") 311 | println() 312 | printInBold(" ⏲️ You have $timeoutSeconds seconds to cancel! ⏲️") 313 | println(" Press Ctrl-C to stop now.") 314 | println() 315 | println() 316 | 317 | Thread.sleep(TimeUnit.SECONDS.toMillis(timeoutSeconds)) 318 | } 319 | 320 | fun Runtime.nukeGlobalCaches() { 321 | printInBold("⏳ Clearing Android Gradle build cache...") 322 | exec("$gradlew cleanBuildCache") 323 | println() 324 | 325 | printInBold("🔥 Clearing ${Ide.IntelliJIdea} caches...") 326 | clearIdeCache(Ide.IntelliJIdea) 327 | println() 328 | 329 | printInBold("🔥 Clearing ${Ide.AndroidStudio} caches...") 330 | clearIdeCache(Ide.AndroidStudio) 331 | println() 332 | 333 | printInBold("🔥 Clearing Maven local repository artefacts...") 334 | if (mavenLocalRepository != null) { 335 | if (verbose) println(" ℹ️ Maven local repository found at: ${mavenLocalRepository.absolutePath}") 336 | mavenLocalRepository.removeSubfoldersMatching { it.name.toLowerCase() == "repository" } 337 | } else { 338 | println(" ⚠️ Unable to locate Maven local repository. Checked ~/.m2") 339 | } 340 | 341 | printInBold("🔥 Clearing Gradle global cache directories: build-scan-data, caches, daemon, wrapper...") 342 | if (gradleHome != null) { 343 | if (verbose) println(" ℹ️ Gradle home found at: ${gradleHome.absolutePath}") 344 | gradleHome.removeSubfoldersMatching { 345 | it.name.toLowerCase() == "build-scan-data" || 346 | it.name.toLowerCase() == "caches" || 347 | it.name.toLowerCase() == "daemon" || 348 | it.name.toLowerCase() == "wrapper" 349 | } 350 | } else { 351 | println(" ⚠️ Unable to locate Gradle home directory. Checked \$GRADLE_HOME and ~/.gradle") 352 | } 353 | println() 354 | } 355 | 356 | fun printInBold(message: String) { 357 | when { 358 | isOsWindows() -> println(message) 359 | else -> println("\u001B[1;37m$message\u001B[0;37m") 360 | } 361 | } 362 | 363 | fun clearIdeCache(ide: Ide) { 364 | val cacheDirectories = locateCacheFolderFor(ide) 365 | 366 | when { 367 | backup -> cacheDirectories 368 | .onEach { 369 | println(" ℹ️ Clearing cache for $ide ${extractVersion(it, ide)}...") 370 | } 371 | .backupAndDeleteByRenaming() 372 | else -> cacheDirectories 373 | .onEach { 374 | println(" ℹ️ Clearing cache for $ide ${extractVersion(it, ide)}...") 375 | } 376 | .deleteRecursively() 377 | } 378 | } 379 | 380 | fun locateCacheFolderFor(ide: Ide): Sequence = 381 | when { 382 | isOsWindows() || isOsLinux() -> { 383 | userHome.listContents(recursively = false) { 384 | it.isDirectory && it.name.startsWith(".${ide.folderPrefix}") 385 | } 386 | } 387 | isOsMacOs() -> { 388 | File(userHome, "Library/Caches") 389 | .listContents(recursively = false) { 390 | it.isDirectory && it.name.startsWith(ide.folderPrefix, ignoreCase = true) 391 | } 392 | } 393 | else -> { 394 | println(" ⚠️ Unsupported OS, skipping.") 395 | emptySequence() 396 | } 397 | } 398 | .filter { it.exists() } 399 | 400 | fun isOsLinux() = System.getProperty("os.name").startsWith("Linux", ignoreCase = true) 401 | fun isOsMacOs() = System.getProperty("os.name").startsWith("Mac", ignoreCase = true) 402 | 403 | fun extractVersion(it: File, ide: Ide): String { 404 | val versionName = it.name.substringAfter(ide.folderPrefix) 405 | return if (versionName.startsWith("Preview")) { 406 | "${versionName.substring("Preview".length)} Preview" 407 | } else { 408 | versionName 409 | } 410 | } 411 | 412 | fun File.removeSubfoldersMatching(matcher: (file: File) -> Boolean) { 413 | val matchingDirectories = this 414 | .listContents(recursively = recursively) { 415 | it.isDirectory && matcher(it) 416 | } 417 | 418 | when { 419 | backup -> matchingDirectories.backupAndDeleteByRenaming() 420 | else -> matchingDirectories.deleteRecursively() 421 | } 422 | } 423 | 424 | fun File.listContents(recursively: Boolean, matcher: (File) -> Boolean): Sequence = 425 | listFiles()!! 426 | .asSequence() 427 | .flatMap { 428 | when { 429 | matcher(it) -> sequenceOf(it) 430 | recursively && it.isDirectory -> { 431 | it.listContents(recursively = true, matcher = matcher) 432 | } 433 | else -> sequenceOf() 434 | } 435 | } 436 | 437 | fun Sequence.backupAndDeleteByRenaming() = 438 | this.onEach { if (verbose) println(" Deleting: ${it.absolutePath}") } 439 | .map { Pair(it, generateBackupNameFor(it)) } 440 | .onEach { (_, backup) -> if (verbose) println(" ⤷ Backing up to: ${backup.name}") } 441 | .forEach { (original, backup) -> if (wetRun) original.renameTo(backup) } 442 | 443 | fun generateBackupNameFor(file: File): File { 444 | var backupFile: File 445 | var index = 0 446 | do { 447 | backupFile = File(file.parentFile, "${file.name}-backup%02d".format(index)) 448 | index++ 449 | } while (backupFile.exists()) 450 | return backupFile 451 | } 452 | 453 | fun Sequence.deleteRecursively() = 454 | this.onEach { if (verbose) println(" Deleting: ${it.absolutePath}") } 455 | .forEach { if (wetRun) it.deleteRecursively() } 456 | 457 | fun isOsWindows() = System.getProperty("os.name").startsWith("Windows", ignoreCase = true) 458 | 459 | sealed class Ide(private val name: String, val folderPrefix: String) { 460 | 461 | object IntelliJIdea : Ide(name = "IntelliJ IDEA", folderPrefix = "IntelliJIdea") 462 | 463 | object AndroidStudio : Ide(name = "Android Studio", folderPrefix = "AndroidStudio") 464 | 465 | override fun toString() = name 466 | } 467 | --------------------------------------------------------------------------------