├── .github ├── dependabot.yml └── workflows │ └── build.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── gr │ │ └── jchrist │ │ └── gitextender │ │ ├── BackgroundableRepoUpdateTask.java │ │ ├── BranchUpdateResult.java │ │ ├── BranchUpdater.java │ │ ├── GitExtenderUpdateAll.java │ │ ├── NotificationUtil.java │ │ ├── RepositoryUpdater.java │ │ ├── configuration │ │ ├── GitExtenderSettings.java │ │ ├── GitExtenderSettingsHandler.java │ │ ├── ProjectSettingsHandler.java │ │ ├── SettingsConfigurableProvider.java │ │ ├── SettingsDialog.java │ │ ├── SettingsView.form │ │ └── SettingsView.java │ │ ├── dialog │ │ ├── SelectModuleDialog.form │ │ └── SelectModuleDialog.java │ │ └── handlers │ │ ├── AfterFailedMergeHandler.java │ │ ├── AfterMergeHandler.java │ │ ├── AfterSuccessfulMergeHandler.java │ │ ├── BeforeMergeHandler.java │ │ ├── CheckoutHandler.java │ │ ├── DeleteHandler.java │ │ ├── FastForwardOnlyMerger.java │ │ ├── MergeState.java │ │ ├── SimpleMerger.java │ │ └── UpdatedFilesNotifier.java └── resources │ └── META-INF │ └── plugin.xml └── test └── java └── gr └── jchrist └── gitextender ├── AbstractIT.java ├── BranchUpdateResultTest.java ├── GitExecutor.java ├── GitTestUtil.java ├── ProjectUpdateITest.java ├── TestingUtil.java ├── configuration ├── GitExtenderSettingsTest.java ├── ProjectSettingsHandlerTest.java ├── SettingsDialogTest.java └── SettingsViewTest.java ├── dialog └── SelectModuleDialogTest.java └── handlers ├── AfterMergeHandlerTest.java └── UpdatedFilesNotifierTest.java /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Dependabot configuration: 2 | # https://docs.github.com/en/free-pro-team@latest/github/administering-a-repository/configuration-options-for-dependency-updates 3 | 4 | version: 2 5 | updates: 6 | - package-ecosystem: "gradle" 7 | directory: "/" 8 | schedule: 9 | interval: "daily" 10 | # Maintain dependencies for GitHub Actions 11 | - package-ecosystem: "github-actions" 12 | directory: "/" 13 | schedule: 14 | interval: "daily" -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: [push] 4 | 5 | jobs: 6 | citest: 7 | runs-on: ubuntu-latest 8 | steps: 9 | # Free GitHub Actions Environment Disk Space 10 | - name: Maximize Build Space 11 | run: | 12 | sudo rm -rf /usr/share/dotnet 13 | sudo rm -rf /usr/local/lib/android 14 | sudo rm -rf /opt/ghc 15 | - name: checkout 16 | uses: actions/checkout@v4 17 | # Validate wrapper 18 | - name: Gradle Wrapper Validation 19 | uses: gradle/wrapper-validation-action@v3 20 | - name: Setup Java 21 | uses: actions/setup-java@v4 22 | with: 23 | distribution: corretto 24 | java-version: 17 25 | - name: build 26 | run: ./gradlew check --stacktrace --info 27 | - uses: codecov/codecov-action@v5 28 | with: 29 | token: ${{ secrets.CODECOV_TOKEN }} 30 | - name: Collect Tests Result 31 | if: ${{ failure() }} 32 | uses: actions/upload-artifact@v4 33 | with: 34 | name: tests-result 35 | path: ${{ github.workspace }}/build/reports/tests 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | .mtj.tmp/ 4 | 5 | *.jar 6 | *.war 7 | *.ear 8 | 9 | hs_err_pid* 10 | 11 | .idea/ 12 | *.iml 13 | *.ipr 14 | *.iws 15 | 16 | /out/ 17 | 18 | .idea_modules/ 19 | 20 | .intellijPlatform/ 21 | 22 | .gradle 23 | /build/ 24 | 25 | # Ignore Gradle GUI config 26 | gradle-app.setting 27 | gradle.properties 28 | !**/gradle-wrapper.jar 29 | .gradletasknamecache 30 | 31 | *~ 32 | .directory 33 | .Trash-* 34 | 35 | Thumbs.db 36 | ehthumbs.db 37 | Desktop.ini 38 | $RECYCLE.BIN/ 39 | *.cab 40 | *.msi 41 | *.msm 42 | *.msp 43 | *.lnk 44 | 45 | .DS_Store 46 | .AppleDouble 47 | .LSOverride 48 | 49 | Icon 50 | 51 | ._* 52 | 53 | .DocumentRevisions-V100 54 | .fseventsd 55 | .Spotlight-V100 56 | .TemporaryItems 57 | .Trashes 58 | .VolumeIcon.icns 59 | 60 | .AppleDB 61 | .AppleDesktop 62 | Network Trash Folder 63 | Temporary Items 64 | .apdisk 65 | 66 | testdir/ 67 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Changelog 2 | --------- 3 | 4 | 5 | ## 0.8.2 (2024-08-26) 6 | * Update intellij platform plugin and dependencies 7 | 8 | ## 0.8.1 (2024-01-30) 9 | * Limit number of threads for updates. Closes [#55](https://github.com/JChrist/gitextender/issues/55) 10 | 11 | ## 0.8.0 (2023-12-14) 12 | * Fix no display name for configurable. Closes [#70](https://github.com/JChrist/gitextender/issues/70) 13 | 14 | ## 0.7.0 (2021-06-04) 15 | * Workaround issue with wrong thread creating the update tree, by disabling showing update tree 16 | 17 | ## 0.6.0 (2020-12-29) 18 | * Fixed plugin menu integration 19 | 20 | ## 0.5.2 (2019-09-26) 21 | * Fixed missing backgroundable task spinning notification and disabled concurrent executions 22 | 23 | ## 0.5.1 (2019-09-25) 24 | * Updated threading model for updating repositories, (hopefully) closing issue #13 25 | * Refactored all tests to not use the hacky way of BaseTest with Inner platform test case, instead extending BasePlatformTestCase or AbstractIT (which in turn extends HeavyPlatformTestCase) 26 | 27 | ## 0.5.0 (2019-06-13) 28 | * Added _prune local branches_ feature, so that a local branch gets deleted if it was tracking a remote one prior to fetching (and pruning) and its remote counter-part was pruned 29 | 30 | ## 0.4.1 (2017-12-06) 31 | - Fix issue #8: create UpdateInfoTree in the event dispatch thread 32 | 33 | ## 0.4.0 (2017-07-01) 34 | - For projects with multiple modules as separate Git roots, a dialog will open up, offering the option to select which module(s) to update. 35 | - Refactored persisted configuration settings. 36 | 37 | ## 0.3.1 (2017-03-23) 38 | - Removed until version in plugin.xml, so that it is compatible with latest releases 39 | 40 | ## 0.3.0 (2017-01-23) 41 | - Moved plugin build to gradle and added !**tests**, as well as Travis CI builds. 42 | - Added settings page, for controlling whether merge-abort-on-error will be attempted 43 | - Added Apache License Version 2.0 reference. 44 | 45 | ## 0.2.0 (2016-04-02) 46 | - Keeping track of updated files, as results to be displayed after updating 47 | 48 | ## 0.1.3 (2016-02-13) 49 | - Changed pull method from rebase to merge, with the --ff-only flag (fast-forward only) 50 | 51 | ## 0.1.2 (2015-07-17) 52 | - Using GitFetcher to fetch and prune remotes and show results before starting the update 53 | 54 | ## 0.1.1 (2015-06-29) 55 | - Changed jdk to 1.7, so that the plugin works with IDEA running with 1.7 jdk 56 | - Added check if any staged or unstaged changes exist in each repository, in order to stash only if needed 57 | 58 | ## 0.1 (2015-06-28) 59 | - Initial version of Git Extender, with support for updating all local branches tracking a remote of all git roots 60 | in the current project, using rebase for all local commits and automatic stashing/popping of uncommitted changes 61 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | https://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 | https://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 | # Git Extender 2 | 3 | [![Actions Status](https://github.com/JChrist/gitextender/workflows/build/badge.svg)](https://github.com/JChrist/gitextender/actions) 4 | [![codecov](https://codecov.io/gh/JChrist/gitextender/branch/main/graph/badge.svg)](https://codecov.io/gh/JChrist/gitextender) 5 | 6 | Git Extender is a plugin for IntelliJ products, 7 | which allows updating all local branches of all modules in the current project. 8 | 9 | It will update all local branches of all git roots 10 | (most usually defined as separate modules) 11 | in the current project. 12 | 13 | Local branches that will be updated are 14 | the branches that exist locally and have been configured 15 | to track a remote branch. 16 | 17 | It tries to fast-forward commits in remote branches to local branches. 18 | If the local branch cannot be merged to the tracked remote using fast-forward only, 19 | and the respective setting has been enabled through `File->Settings->Other Settings->GitExtender Settings` then a simple merge will be attempted. 20 | If there are conflict errors, it will be aborted and an error notification will be shown. 21 | In this case, the update must be performed manually for the reported branch. 22 | 23 | After updating a branch, if there were any file changes, they will be displayed in 24 | IntelliJ Version Control tab. 25 | Currently, the correct list of file changes 26 | (updated, created, removed) will be displayed. 27 | However, when performing a diff for files in a branch other than the currently checked 28 | out, the diff will most probably be incorrect. 29 | 30 | This plugin is available under [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0) 31 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "java" 3 | id "org.jetbrains.intellij.platform" version "2.6.0" 4 | id "jacoco" 5 | } 6 | 7 | repositories { 8 | mavenCentral() 9 | maven { 10 | url = uri("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies") 11 | } 12 | intellijPlatform { 13 | defaultRepositories() 14 | } 15 | } 16 | 17 | group 'gr.jchrist' 18 | version '0.8.2' 19 | 20 | sourceCompatibility = '17' 21 | targetCompatibility = '17' 22 | 23 | dependencies { 24 | intellijPlatform { 25 | intellijIdeaCommunity('2024.2') 26 | //intellijIdeaCommunity('LATEST-EAP-SNAPSHOT') 27 | bundledPlugin 'Git4Idea' 28 | 29 | instrumentationTools() 30 | 31 | testFramework(org.jetbrains.intellij.platform.gradle.TestFrameworkType.Platform.INSTANCE) 32 | } 33 | 34 | testImplementation 'org.mockito:mockito-core:5.18.0' 35 | testImplementation 'junit:junit:4.13.2' 36 | testImplementation 'org.assertj:assertj-core:3.27.3' 37 | testImplementation 'org.opentest4j:opentest4j:1.3.0' 38 | } 39 | 40 | intellijPlatform { 41 | buildSearchableOptions = false 42 | 43 | pluginConfiguration { 44 | id = 'gr.jchrist.gitextender' 45 | name = 'Git Extender' 46 | version = project.version 47 | // patchPluginXml.enabled = false 48 | ideaVersion { 49 | sinceBuild = '241' 50 | untilBuild = provider { null } 51 | } 52 | } 53 | } 54 | 55 | jacocoTestReport { 56 | classDirectories.setFrom(instrumentCode) 57 | reports { 58 | xml.required = true 59 | html.required = false 60 | csv.required = false 61 | } 62 | } 63 | 64 | //specify here that jacoco test report should execute after test 65 | test { 66 | finalizedBy jacocoTestReport 67 | jacoco { 68 | includeNoLocationClasses = true 69 | excludes = ["jdk.internal.*"] 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JChrist/gitextender/460f84dc1bce2c11f1dc8ab1ed98ba1e0dd9ea28/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 165 | if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then 166 | cd "$(dirname "$0")" 167 | fi 168 | 169 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 170 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'gitextender' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/BackgroundableRepoUpdateTask.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender; 2 | 3 | import com.intellij.openapi.diagnostic.Logger; 4 | import git4idea.repo.GitRepository; 5 | import gr.jchrist.gitextender.configuration.GitExtenderSettings; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | import java.util.concurrent.CountDownLatch; 9 | 10 | public class BackgroundableRepoUpdateTask implements Runnable { 11 | private static final Logger logger = Logger.getInstance(BackgroundableRepoUpdateTask.class); 12 | 13 | private final CountDownLatch countDownLatch; 14 | private final GitRepository repo; 15 | private final String repoName; 16 | private final GitExtenderSettings settings; 17 | 18 | public BackgroundableRepoUpdateTask( 19 | @NotNull GitRepository repo, 20 | @NotNull String repoName, 21 | @NotNull GitExtenderSettings settings, 22 | @NotNull CountDownLatch countDownLatch 23 | ) { 24 | this.countDownLatch = countDownLatch; 25 | this.repo = repo; 26 | this.repoName = repoName; 27 | this.settings = settings; 28 | } 29 | 30 | @Override 31 | public void run() { 32 | logger.debug("executing repo update - " + Thread.currentThread().getName()); 33 | RepositoryUpdater repositoryUpdater = new RepositoryUpdater(repo, repoName, settings); 34 | try { 35 | repositoryUpdater.updateRepository(); 36 | } finally { 37 | logger.debug("counting down latch - " + Thread.currentThread().getName()); 38 | countDownLatch.countDown(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/BranchUpdateResult.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender; 2 | 3 | import git4idea.commands.GitCommandResult; 4 | 5 | public class BranchUpdateResult { 6 | protected GitCommandResult checkoutResult; 7 | protected GitCommandResult mergeFastForwardResult; 8 | protected GitCommandResult mergeSimpleResult; 9 | protected GitCommandResult abortResult; 10 | 11 | public BranchUpdateResult() { 12 | } 13 | 14 | public BranchUpdateResult( 15 | GitCommandResult checkoutResult, GitCommandResult mergeFastForwardResult, 16 | GitCommandResult mergeSimpleResult, GitCommandResult abortResult) { 17 | this.checkoutResult = checkoutResult; 18 | this.mergeFastForwardResult = mergeFastForwardResult; 19 | this.mergeSimpleResult = mergeSimpleResult; 20 | this.abortResult = abortResult; 21 | } 22 | 23 | public boolean isSuccess() { 24 | //we're successful if we checked out and 25 | //we merged either by fast-forward, or with simple merge 26 | return isCheckoutSuccess() && isMergeSuccess(); 27 | } 28 | 29 | public boolean isCheckoutSuccess() { 30 | return checkoutResult != null && checkoutResult.success(); 31 | } 32 | 33 | public boolean isCheckoutError() { 34 | return !isCheckoutSuccess(); 35 | } 36 | 37 | public boolean isMergeSuccess() { 38 | return isMergeFastForwardSuccess() || isMergeSimpleSuccess(); 39 | } 40 | 41 | public boolean isMergeError() { 42 | return !isMergeSuccess(); 43 | } 44 | 45 | public boolean isMergeFastForwardSuccess() { 46 | return mergeFastForwardResult != null && mergeFastForwardResult.success(); 47 | } 48 | 49 | public boolean isMergeSimpleSuccess() { 50 | return mergeSimpleResult != null && mergeSimpleResult.success(); 51 | } 52 | 53 | public boolean isAbortSucceeded() { 54 | return abortResult != null && abortResult.success(); 55 | } 56 | 57 | public GitCommandResult getCheckoutResult() { 58 | return checkoutResult; 59 | } 60 | 61 | public GitCommandResult getMergeFastForwardResult() { 62 | return mergeFastForwardResult; 63 | } 64 | 65 | public GitCommandResult getMergeSimpleResult() { 66 | return mergeSimpleResult; 67 | } 68 | 69 | public GitCommandResult getAbortResult() { 70 | return abortResult; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/BranchUpdater.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender; 2 | 3 | import com.intellij.openapi.diagnostic.Logger; 4 | import git4idea.commands.Git; 5 | import git4idea.repo.GitBranchTrackInfo; 6 | import git4idea.repo.GitRepository; 7 | import gr.jchrist.gitextender.configuration.GitExtenderSettings; 8 | import gr.jchrist.gitextender.handlers.AfterMergeHandler; 9 | import gr.jchrist.gitextender.handlers.BeforeMergeHandler; 10 | import gr.jchrist.gitextender.handlers.CheckoutHandler; 11 | import gr.jchrist.gitextender.handlers.FastForwardOnlyMerger; 12 | import gr.jchrist.gitextender.handlers.MergeState; 13 | import gr.jchrist.gitextender.handlers.SimpleMerger; 14 | import org.jetbrains.annotations.NotNull; 15 | 16 | /** 17 | * @author jchrist 18 | * @since 2016/03/27 19 | */ 20 | public class BranchUpdater { 21 | private static final Logger logger = Logger.getInstance(BranchUpdater.class); 22 | 23 | private final Git git; 24 | private final GitRepository repo; 25 | 26 | private final String repoName; 27 | private final String remoteBranchName; 28 | private final String localBranchName; 29 | private final BranchUpdateResult branchUpdateResult; 30 | private final GitExtenderSettings gitExtenderSettings; 31 | private MergeState mergeState; 32 | 33 | public BranchUpdater( 34 | Git git, GitRepository repo, String repoName, 35 | GitBranchTrackInfo info, GitExtenderSettings gitExtenderSettings) { 36 | this.git = git; 37 | this.repo = repo; 38 | this.repoName = repoName; 39 | 40 | this.remoteBranchName = info.getRemoteBranch().getNameForLocalOperations(); 41 | this.localBranchName = info.getLocalBranch().getName(); 42 | this.branchUpdateResult = new BranchUpdateResult(); 43 | this.gitExtenderSettings = gitExtenderSettings; 44 | } 45 | 46 | @NotNull 47 | public BranchUpdateResult update() { 48 | checkout(); 49 | if (!branchUpdateResult.isCheckoutSuccess()) { 50 | return this.branchUpdateResult; 51 | } 52 | 53 | merge(); 54 | return this.branchUpdateResult; 55 | } 56 | 57 | protected void checkout() { 58 | branchUpdateResult.checkoutResult = 59 | new CheckoutHandler(git, repo.getProject(), repo.getRoot()) 60 | .checkout(localBranchName); 61 | } 62 | 63 | protected void merge() { 64 | //let's prepare for the merge: find what files we have now 65 | prepareMerge(); 66 | 67 | mergeFastForwardOnly(); 68 | if (!branchUpdateResult.isMergeSuccess()) { 69 | // this is controlled with a user setting flag, 70 | // because it might be dangerous in case abort fails 71 | if (Boolean.TRUE.equals(gitExtenderSettings.getAttemptMergeAbort())) { 72 | logger.info("fast-forward merge failed, attempting simple merge"); 73 | mergeAbortIfFailed(); 74 | } else { 75 | logger.info("fast-forward merge failed, NOT attempting simple merge"); 76 | } 77 | } 78 | 79 | if (branchUpdateResult.isMergeSuccess()) { 80 | afterMerge(); 81 | } 82 | } 83 | 84 | protected void mergeFastForwardOnly() { 85 | branchUpdateResult.mergeFastForwardResult = 86 | new FastForwardOnlyMerger(git, repo.getProject(), repo.getRoot(), remoteBranchName) 87 | .mergeFastForward(); 88 | } 89 | 90 | protected void mergeAbortIfFailed() { 91 | SimpleMerger simpleMerger = new SimpleMerger(git, repo.getProject(), repo.getRoot(), remoteBranchName); 92 | simpleMerger.mergeAbortIfFailed(); 93 | branchUpdateResult.mergeSimpleResult = simpleMerger.getMergeResult(); 94 | branchUpdateResult.abortResult = simpleMerger.getAbortResult(); 95 | } 96 | 97 | protected void prepareMerge() { 98 | mergeState = new BeforeMergeHandler(repo.getProject(), repo.getRoot(), repo, 99 | repoName, localBranchName, remoteBranchName) 100 | .beforeMerge(); 101 | } 102 | 103 | protected void afterMerge() { 104 | AfterMergeHandler.getInstance(branchUpdateResult, mergeState).afterMerge(); 105 | } 106 | 107 | @NotNull 108 | public String getLocalBranchName() { 109 | return localBranchName; 110 | } 111 | 112 | @NotNull 113 | public String getRemoteBranchName() { 114 | return remoteBranchName; 115 | } 116 | 117 | @NotNull 118 | public BranchUpdateResult getBranchUpdateResult() { 119 | return branchUpdateResult; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/GitExtenderUpdateAll.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender; 2 | 3 | import com.google.common.util.concurrent.ThreadFactoryBuilder; 4 | import com.intellij.dvcs.DvcsUtil; 5 | import com.intellij.dvcs.repo.Repository; 6 | import com.intellij.notification.NotificationType; 7 | import com.intellij.openapi.actionSystem.ActionUpdateThread; 8 | import com.intellij.openapi.actionSystem.AnAction; 9 | import com.intellij.openapi.actionSystem.AnActionEvent; 10 | import com.intellij.openapi.application.AccessToken; 11 | import com.intellij.openapi.diagnostic.Logger; 12 | import com.intellij.openapi.project.Project; 13 | import com.intellij.platform.ide.progress.TasksKt; 14 | import com.intellij.vcsUtil.VcsImplUtil; 15 | import git4idea.GitUtil; 16 | import git4idea.repo.GitRepository; 17 | import git4idea.repo.GitRepositoryManager; 18 | import gr.jchrist.gitextender.configuration.GitExtenderSettings; 19 | import gr.jchrist.gitextender.configuration.GitExtenderSettingsHandler; 20 | import gr.jchrist.gitextender.configuration.ProjectSettingsHandler; 21 | import gr.jchrist.gitextender.dialog.SelectModuleDialog; 22 | import kotlin.coroutines.Continuation; 23 | import kotlin.coroutines.CoroutineContext; 24 | import kotlin.coroutines.EmptyCoroutineContext; 25 | import org.jetbrains.annotations.NotNull; 26 | import org.jetbrains.annotations.Nullable; 27 | 28 | import java.util.List; 29 | import java.util.concurrent.CountDownLatch; 30 | import java.util.concurrent.Executors; 31 | import java.util.concurrent.TimeUnit; 32 | import java.util.concurrent.atomic.AtomicBoolean; 33 | import java.util.stream.Collectors; 34 | 35 | /** 36 | * @author jchrist 37 | * @since 2015/06/27 38 | */ 39 | public class GitExtenderUpdateAll extends AnAction { 40 | private static final Logger logger = Logger.getInstance(GitExtenderUpdateAll.class); 41 | protected CountDownLatch updateCountDown; 42 | protected AtomicBoolean executingFlag = new AtomicBoolean(false); 43 | 44 | @Override 45 | public @NotNull ActionUpdateThread getActionUpdateThread() { 46 | return ActionUpdateThread.BGT; 47 | } 48 | 49 | @Override 50 | public void actionPerformed(@NotNull AnActionEvent event) { 51 | if (!this.executingFlag.compareAndSet(false, true)) { 52 | logger.warn("executing flag was true, another update action should be already running"); 53 | return; 54 | } 55 | try { 56 | Project project = event.getProject(); 57 | if (project == null) { 58 | logger.warn("received event without project"); 59 | throw new CancelUpdateException("Update Failed", "Git Extender failed to retrieve the project"); 60 | } 61 | 62 | GitRepositoryManager manager = getGitRepositoryManager(project); 63 | 64 | if (manager == null) { 65 | throw new CancelUpdateException("Update Failed", "Git Extender could not initialize the project's repository manager"); 66 | } 67 | 68 | List repositoryList = manager.getRepositories(); 69 | if (repositoryList.isEmpty()) { 70 | logger.info("no git repositories in project"); 71 | throw new CancelUpdateException("Update Failed", "Git Extender could not find any repositories in the current project"); 72 | } 73 | 74 | ProjectSettingsHandler projectSettingsHandler = new ProjectSettingsHandler(project); 75 | boolean proceedToUpdate = showSelectModuleDialog(projectSettingsHandler, repositoryList); 76 | if (!proceedToUpdate) { 77 | logger.debug("update cancelled"); 78 | throw new CancelUpdateException("Update Canceled", "update was canceled", NotificationType.INFORMATION); 79 | } 80 | 81 | List reposToUpdate = getSelectedGitRepos(repositoryList, 82 | projectSettingsHandler.loadSelectedModules()); 83 | 84 | if (reposToUpdate.isEmpty()) { 85 | logger.debug("no modules selected in dialog"); 86 | throw new CancelUpdateException("Update Canceled", "Update was canceled due to no repositories selected", NotificationType.INFORMATION); 87 | } 88 | 89 | updateRepositories(project, reposToUpdate); 90 | } catch (CancelUpdateException e) { 91 | logger.debug("cancel update exception received", e); 92 | NotificationUtil.showNotification(e.notificationTitle, e.notificationMessage, e.notificationType); 93 | executingFlag.set(false); 94 | } catch (Exception | Error e) { 95 | logger.warn("error updating project due to exception", e); 96 | NotificationUtil.showErrorNotification("Update Failed", "Git Extender failed to update the project due to exception: " + e); 97 | executingFlag.set(false); 98 | } 99 | } 100 | 101 | @Override 102 | public void update(AnActionEvent anActionEvent) { 103 | // Set the availability based on whether we are already executing or not 104 | anActionEvent.getPresentation().setEnabled(!this.executingFlag.get()); 105 | } 106 | 107 | @Nullable 108 | public static GitRepositoryManager getGitRepositoryManager(@NotNull Project project) { 109 | try { 110 | return GitRepositoryManager.getInstance(project); 111 | } catch (Exception e) { 112 | logger.warn("exception caught while trying to get git repository manager", e); 113 | return null; 114 | } 115 | } 116 | 117 | private boolean showSelectModuleDialog(@NotNull ProjectSettingsHandler projectSettingsHandler, 118 | @NotNull List repositories) { 119 | if (repositories.size() <= 1) { 120 | logger.debug("single git repo in project, no need for displaying module chooser dialog"); 121 | return true; 122 | } 123 | 124 | List repos = repositories.stream() 125 | .map(GitExtenderUpdateAll::getRepoName) 126 | .sorted() 127 | .collect(Collectors.toList()); 128 | SelectModuleDialog selectModuleDialog = new SelectModuleDialog(projectSettingsHandler, repos); 129 | return selectModuleDialog.showAndGet(); 130 | } 131 | 132 | private void updateRepositories(@NotNull Project project, @NotNull List repositories) { 133 | //get an access token for changing the repositories 134 | final AccessToken accessToken = DvcsUtil.workingTreeChangeStarted(project); 135 | 136 | //get the settings to find out the selected options 137 | GitExtenderSettingsHandler settingsHandler = new GitExtenderSettingsHandler(); 138 | final GitExtenderSettings settings = settingsHandler.loadSettings(); 139 | this.updateCountDown = new CountDownLatch(repositories.size()); 140 | final var es = Executors.newFixedThreadPool(Math.min(repositories.size(), 3), 141 | new ThreadFactoryBuilder().setNameFormat("gitextender-repo-updater-%d").build()); 142 | repositories.forEach(repo -> 143 | es.submit(new BackgroundableRepoUpdateTask(repo, VcsImplUtil.getShortVcsRootName(repo.getProject(), repo.getRoot()), 144 | settings, updateCountDown))); 145 | TasksKt.withBackgroundProgress(project, "GitExtender Update All Repos", false, (cs, cont) -> { 146 | try { 147 | logger.debug("waiting for update to finish - " + Thread.currentThread().getName()); 148 | //10 minutes should be extreme enough to account for ALL updates 149 | this.updateCountDown.await(10, TimeUnit.MINUTES); 150 | } catch (Exception e) { 151 | logger.warn("error awaiting update latch!", e); 152 | } 153 | try { 154 | es.shutdownNow(); 155 | } catch (Exception e) { 156 | logger.warn("error shutting down executor", e); 157 | } 158 | logger.debug("update finished - " + Thread.currentThread().getName()); 159 | //the last task finished should clean up, release project changes and show info notification 160 | accessToken.finish(); 161 | 162 | // refresh vfs roots 163 | GitUtil.refreshVfsInRoots(repositories.stream().map(Repository::getRoot).collect(Collectors.toList())); 164 | 165 | NotificationUtil.showInfoNotification("Update Completed", "Git Extender updated all projects"); 166 | executingFlag.set(false); 167 | return cont; 168 | }, new Continuation<>() { 169 | @Override 170 | public @NotNull CoroutineContext getContext() { 171 | return EmptyCoroutineContext.INSTANCE; 172 | } 173 | 174 | @Override 175 | public void resumeWith(@NotNull Object o) {} 176 | }); 177 | } 178 | 179 | protected static List getSelectedGitRepos(List repos, List selectedModules) { 180 | if (repos.size() <= 1) { 181 | return repos; 182 | } 183 | 184 | return repos.stream() 185 | .filter(repo -> selectedModules.contains(getRepoName(repo))) 186 | .collect(Collectors.toList()); 187 | } 188 | 189 | protected static String getRepoName(GitRepository repo) { 190 | return VcsImplUtil.getShortVcsRootName(repo.getProject(), repo.getRoot()); 191 | } 192 | 193 | public static class CancelUpdateException extends Exception { 194 | protected final String notificationTitle; 195 | protected final String notificationMessage; 196 | protected final NotificationType notificationType; 197 | 198 | public CancelUpdateException(String notificationTitle, String notificationMessage) { 199 | this(notificationTitle, notificationMessage, NotificationType.ERROR); 200 | } 201 | 202 | public CancelUpdateException( 203 | String notificationTitle, String notificationMessage, NotificationType notificationType) { 204 | super(notificationMessage); 205 | this.notificationTitle = notificationTitle; 206 | this.notificationMessage = notificationMessage; 207 | this.notificationType = notificationType; 208 | } 209 | 210 | @Override public Throwable fillInStackTrace() { return this; } 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/NotificationUtil.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender; 2 | 3 | import com.intellij.notification.Notification; 4 | import com.intellij.notification.NotificationType; 5 | import com.intellij.notification.Notifications; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | public class NotificationUtil { 9 | private NotificationUtil() { 10 | //no instances should be created 11 | } 12 | 13 | public static final String NOTIFICATION_GROUP_ID = "Git Extender"; 14 | 15 | public static void showErrorNotification(@NotNull String title, @NotNull String content) { 16 | showNotification(title, content, NotificationType.ERROR); 17 | } 18 | 19 | public static void showInfoNotification(@NotNull String title, @NotNull String content) { 20 | showNotification(title, content, NotificationType.INFORMATION); 21 | } 22 | 23 | public static void showNotification(@NotNull String title, @NotNull String content, @NotNull NotificationType type) { 24 | Notifications.Bus.notify(new Notification(NOTIFICATION_GROUP_ID, title, content, type)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/RepositoryUpdater.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender; 2 | 3 | import com.intellij.openapi.application.ApplicationManager; 4 | import com.intellij.openapi.diagnostic.Logger; 5 | import com.intellij.openapi.project.Project; 6 | import git4idea.GitLocalBranch; 7 | import git4idea.GitUtil; 8 | import git4idea.commands.Git; 9 | import git4idea.commands.GitCommandResult; 10 | import git4idea.fetch.GitFetchResult; 11 | import git4idea.fetch.GitFetchSupport; 12 | import git4idea.repo.GitBranchTrackInfo; 13 | import git4idea.repo.GitRepository; 14 | import gr.jchrist.gitextender.configuration.GitExtenderSettings; 15 | import gr.jchrist.gitextender.handlers.CheckoutHandler; 16 | import gr.jchrist.gitextender.handlers.DeleteHandler; 17 | import org.jetbrains.annotations.NotNull; 18 | 19 | import java.util.Collection; 20 | import java.util.Collections; 21 | import java.util.HashSet; 22 | import java.util.Set; 23 | 24 | public class RepositoryUpdater { 25 | private static final Logger logger = Logger.getInstance(RepositoryUpdater.class); 26 | public static final String REBASE_IN_PROGRESS = "Repository $repo cannot be updated, because there is a rebase in progress"; 27 | public static final String NO_REMOTES = "Repository $repo cannot be updated, because there are no remotes"; 28 | public static final String NO_CURRENT_BRANCH = "Git repo: $repo
" + 29 | "Error: Git Extender failed to update git repo, " + 30 | "because it could not identify what the current checked out branch is."; 31 | public static final String NO_STASH = "Git repo: $repo
Error: "; 32 | public static final String FAILED_HAS_CHANGES = "Git repo: $repo
" + 33 | "Error: Git Extender failed to update git repo, " + 34 | "because it could not identify if there were any staged/unstaged changes. " + 35 | "The exception was: "; 36 | public static final String EXCEPTION_DURING_UPDATE = "Git repo: $repo
" + 37 | "Error: Git Extender failed to update git repo, due to an exception during update. " + 38 | "The exception was: "; 39 | private final GitRepository repo; 40 | private final String repoName; 41 | private final GitExtenderSettings settings; 42 | 43 | public RepositoryUpdater( 44 | @NotNull GitRepository repo, 45 | @NotNull String repoName, 46 | @NotNull GitExtenderSettings settings 47 | ) { 48 | this.repo = repo; 49 | this.repoName = repoName; 50 | this.settings = settings; 51 | } 52 | 53 | public static String getMessage(String base, String repoName) { 54 | return base.replace("$repo", repoName); 55 | } 56 | 57 | public static String getMessage(String base, String repoName, String error) { 58 | return base.replace("$repo", repoName) + error; 59 | } 60 | 61 | public void updateRepository() { 62 | //check if repo is valid for updating 63 | if (!canRepoBeUpdated(repo)) { 64 | return; 65 | } 66 | 67 | final Project project = repo.getProject(); 68 | 69 | //find git service 70 | final Git git = ApplicationManager.getApplication().getService(Git.class); 71 | 72 | final String currBranch = repo.getCurrentBranchName(); 73 | if (currBranch == null) { 74 | logger.warn("no current branch in repository: " + repo); 75 | NotificationUtil.showErrorNotification("Git Extender update failed", 76 | getMessage(NO_CURRENT_BRANCH, repoName)); 77 | return; 78 | } 79 | 80 | //check if we require stashing 81 | final boolean repoChanges; 82 | try { 83 | repoChanges = hasChanges(repo); 84 | } catch (Exception e) { 85 | logger.warn("error trying to find if repo has changes: " + repo, e); 86 | NotificationUtil.showErrorNotification("Git Extender update failed", 87 | getMessage(FAILED_HAS_CHANGES, repoName, e.getMessage())); 88 | return; 89 | } 90 | 91 | if (repoChanges) { 92 | //there are changes that we need to stash 93 | GitCommandResult saveResult = git.stashSave(repo, "GitExtender_Stashing"); 94 | if (!saveResult.success()) { 95 | String errOut = saveResult.getErrorOutputAsJoinedString(); 96 | logger.warn("error trying to stash local repo changes: " + errOut); 97 | NotificationUtil.showErrorNotification("Git Extender failed to stash changes", 98 | getMessage(NO_STASH, repoName, errOut)); 99 | return; 100 | } 101 | } 102 | 103 | // keeping a flag whether we tried to abort a merge and failed 104 | // in such a situation, we must stop whatever we were doing ASAP, without making any other change whatsoever. 105 | boolean failureToAbort = false; 106 | try { 107 | /* 108 | //todo locking like this is invalid 109 | logger.info("write-locking vcs for repo: " + repo + " from thread:" + Thread.currentThread().getName()); 110 | boolean locked = repo.getVcs().getCommandLock().writeLock().tryLock(0, TimeUnit.MILLISECONDS); 111 | if (!locked) { 112 | throw new Exception("could not lock repo " + repo + 113 | " for update from thread: " + Thread.currentThread().getName()); 114 | } 115 | */ 116 | //mark here the branch track info prior to fetching/pruning 117 | final Set preInfos = new HashSet<>(repo.getBranchTrackInfos()); 118 | 119 | //fetch and prune remote 120 | //git fetch origin 121 | GitFetchSupport gfs = GitFetchSupport.fetchSupport(project); 122 | GitFetchResult gfr = gfs.fetchAllRemotes(Collections.singletonList(repo)); 123 | gfr.showNotification(); 124 | 125 | //update the repo after fetch, in order to re-sync locals and remotes 126 | repo.update(); 127 | 128 | if (settings.getPruneLocals()) { 129 | pruneLocals(git, preInfos); 130 | } 131 | 132 | for (final GitBranchTrackInfo info : repo.getBranchTrackInfos()) { 133 | final BranchUpdater updater = new BranchUpdater(git, repo, repoName, info, settings); 134 | 135 | BranchUpdateResult result = updater.update(); 136 | 137 | //let's see if we had any errors 138 | if (!result.isSuccess()) { 139 | //where was the error? 140 | //in checkout ? 141 | if (result.isCheckoutError()) { 142 | String error = "Local branch: " + updater.getLocalBranchName() + "
" + 143 | "Git repo:" + repoName + "
" + 144 | "Checkout Error: " + result.checkoutResult.getErrorOutputAsJoinedString(); 145 | NotificationUtil.showErrorNotification("Git Extender failed to checkout branch", error); 146 | } else if (result.isMergeError()) { 147 | String error = "Local branch: " + updater.getLocalBranchName() + "
" + 148 | "Remote branch: " + updater.getRemoteBranchName() + "
" + 149 | "Git repo:" + repoName + "
" + 150 | "Merge error: "; 151 | if (Boolean.FALSE.equals(settings.getAttemptMergeAbort()) || result.isAbortSucceeded()) { 152 | if (result.isAbortSucceeded()) { 153 | error += "Merge was aborted.
"; 154 | } 155 | error += "Please perform the merge (which may need conflict resolution) " + 156 | "manually for this branch, " + 157 | "by checking it out, merging the changes and resolving any conflicts"; 158 | } else { 159 | error += "Merge was NOT aborted! You will need to resolve the merge conflicts!"; 160 | if (repoChanges) { 161 | error += " The changes you had on branch: " + currBranch + " were stashed, " + 162 | "but not un-stashed, due to this merge error. " + 163 | "After resolving the merge conflict, " + 164 | "you can revert to the branch you were on " + 165 | "(e.g. using git checkout " + currBranch + ") " + 166 | "and then pop the stash (e.g. git stash pop)"; 167 | } 168 | failureToAbort = true; 169 | } 170 | NotificationUtil.showErrorNotification( 171 | "Git Extender failed to merge branch" + 172 | (Boolean.FALSE.equals(settings.getAttemptMergeAbort()) ? 173 | " with fast-forward only" : ""), 174 | error); 175 | if (failureToAbort) { 176 | return; 177 | } 178 | } 179 | } else { 180 | //todo perhaps when we have a successful result we need to wait for the update info tree 181 | //generation to happen (invoked to happen through the dispatch thread) before moving on 182 | } 183 | } 184 | 185 | CheckoutHandler checkoutHandler = new CheckoutHandler(git, project, repo.getRoot()); 186 | //now that we're finished, checkout again the branch that the developer had before 187 | checkoutHandler.checkout(currBranch); 188 | 189 | //update the repo after all updates, in order to re-sync locals / remotes and changed files 190 | repo.update(); 191 | } catch (Exception e) { 192 | logger.warn("exception trying to update repo: " + repo + " from thread:" + Thread.currentThread().getName(), e); 193 | NotificationUtil.showErrorNotification("Git Extender update failed", getMessage(EXCEPTION_DURING_UPDATE, repoName, e.getMessage())); 194 | } finally { 195 | //now unstash, if we had stashed any changes 196 | if (repoChanges && !failureToAbort) { 197 | try { 198 | git.stashPop(repo); 199 | } catch (Exception e) { 200 | logger.warn("error trying to pop stash for repo: " + repo, e); 201 | } 202 | } 203 | /* 204 | //todo locking like this is invalid 205 | logger.info("write-unlocking vcs for repo: " + repo); 206 | try { 207 | repo.getVcs().getCommandLock().writeLock().unlock(); 208 | } catch (Exception e) { 209 | logger.warn("exception trying to unlock repo " + repo + " from thread:" + 210 | Thread.currentThread().getName(), e); 211 | }*/ 212 | } 213 | } 214 | 215 | private boolean canRepoBeUpdated(@NotNull GitRepository repo) { 216 | if (repo.isRebaseInProgress()) { 217 | NotificationUtil.showErrorNotification("Repository cannot be updated", getMessage(REBASE_IN_PROGRESS, repoName)); 218 | return false; 219 | } 220 | 221 | if (repo.getRemotes().isEmpty()) { 222 | NotificationUtil.showErrorNotification("Repository cannot be updated", getMessage(NO_REMOTES, repoName)); 223 | return false; 224 | } 225 | 226 | return true; 227 | } 228 | 229 | protected boolean pruneLocals(@NotNull Git git, @NotNull Collection preFetch) { 230 | Collection infos = repo.getBranchTrackInfos(); 231 | if (preFetch.size() == infos.size()) { 232 | return false; 233 | } 234 | 235 | Set afterFetch = new HashSet<>(infos); 236 | Set remainingLocals = new HashSet<>(); 237 | Set markedForDeletion = new HashSet<>(); 238 | 239 | for (GitBranchTrackInfo pre : preFetch) { 240 | boolean mark = true; 241 | for (GitBranchTrackInfo after : afterFetch) { 242 | if (pre.getLocalBranch().getName().equals(after.getLocalBranch().getName())) { 243 | mark = false; 244 | break; 245 | } 246 | } 247 | if (mark) { 248 | markedForDeletion.add(pre); 249 | } else { 250 | remainingLocals.add(pre); 251 | } 252 | } 253 | 254 | if (remainingLocals.isEmpty()) { 255 | //this is strange, if we proceeded to remove all remotely-pruned local branches, nothing would be left 256 | logger.warn("not deleting local branches with pruned remotes, as no branches would be left in: " + repo); 257 | return false; 258 | } 259 | 260 | if (markedForDeletion.isEmpty()) { 261 | return false; 262 | } 263 | 264 | //check if the current branch is also marked for deletion, so as to switch to another (defaulting to master) 265 | GitLocalBranch currentBranch = repo.getCurrentBranch(); 266 | markedForDeletion.stream().filter(ti -> ti.getLocalBranch().equals(currentBranch)) 267 | .findAny().ifPresent(ti -> { 268 | //current branch is marked for deletion, so try to switch to main. 269 | // if that fails, switch to the first possible local 270 | CheckoutHandler checkoutHandler = new CheckoutHandler(git, repo.getProject(), repo.getRoot()); 271 | String branchToSwitchTo = null; 272 | for (GitBranchTrackInfo localBranch : remainingLocals) { 273 | if ("master".equals(localBranch.getLocalBranch().getName()) || 274 | "main".equals(localBranch.getLocalBranch().getName())) { 275 | //this is where we want to go 276 | branchToSwitchTo = localBranch.getLocalBranch().getName(); 277 | break; 278 | } 279 | } 280 | 281 | if (branchToSwitchTo == null) { 282 | //find the first local branch that is not marked for deletion, in order to switch to that 283 | branchToSwitchTo = remainingLocals.iterator().next().getLocalBranch().getName(); 284 | } 285 | 286 | checkoutHandler.checkout(branchToSwitchTo); 287 | }); 288 | 289 | //now delete all marked local branches 290 | DeleteHandler dh = new DeleteHandler(git, repo.getProject(), repo.getRoot()); 291 | for (GitBranchTrackInfo del : markedForDeletion) { 292 | dh.delete(del.getLocalBranch().getName()); 293 | } 294 | 295 | return true; 296 | } 297 | 298 | private boolean hasChanges(GitRepository repo) throws Exception { 299 | return GitUtil.hasLocalChanges(true, repo.getProject(), repo.getRoot()) || 300 | GitUtil.hasLocalChanges(false, repo.getProject(), repo.getRoot()); 301 | } 302 | } 303 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/configuration/GitExtenderSettings.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.configuration; 2 | 3 | public class GitExtenderSettings { 4 | private boolean attemptMergeAbort; 5 | private boolean pruneLocals; 6 | 7 | public GitExtenderSettings() { 8 | this(false, false); 9 | } 10 | 11 | public GitExtenderSettings(boolean attemptMergeAbort, boolean pruneLocals) { 12 | this.attemptMergeAbort = attemptMergeAbort; 13 | this.pruneLocals = pruneLocals; 14 | } 15 | 16 | public boolean getAttemptMergeAbort() { 17 | return attemptMergeAbort; 18 | } 19 | 20 | public void setAttemptMergeAbort(boolean attemptMergeAbort) { 21 | this.attemptMergeAbort = attemptMergeAbort; 22 | } 23 | 24 | public boolean getPruneLocals() { 25 | return pruneLocals; 26 | } 27 | 28 | public void setPruneLocals(boolean pruneLocals) { 29 | this.pruneLocals = pruneLocals; 30 | } 31 | 32 | @Override 33 | public boolean equals(Object o) { 34 | if (this == o) return true; 35 | if (o == null || getClass() != o.getClass()) return false; 36 | 37 | GitExtenderSettings settings = (GitExtenderSettings) o; 38 | 39 | return attemptMergeAbort == settings.attemptMergeAbort && pruneLocals == settings.pruneLocals; 40 | } 41 | 42 | @Override 43 | public int hashCode() { 44 | return (attemptMergeAbort ? 1 : 0) + (pruneLocals ? 10 : 0); 45 | } 46 | 47 | @Override 48 | public String toString() { 49 | return "GitExtenderSettings{" + 50 | "attemptMergeAbort=" + attemptMergeAbort + 51 | "pruneLocals=" + pruneLocals + 52 | '}'; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/configuration/GitExtenderSettingsHandler.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.configuration; 2 | 3 | import com.intellij.ide.util.PropertiesComponent; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | public class GitExtenderSettingsHandler { 7 | static final String PREFIX = "gr.jchrist.gitextender."; 8 | static final String ATTEMPT_MERGE_ABORT_KEY = PREFIX + "attemptMergeAbort"; 9 | static final String PRUNE_LOCALS_KEY = PREFIX + "pruneLocals"; 10 | 11 | public GitExtenderSettingsHandler() { 12 | } 13 | 14 | public GitExtenderSettings loadSettings() { 15 | return new GitExtenderSettings(getAttemptMergeAbort(), getPruneLocals()); 16 | } 17 | 18 | public void saveSettings(GitExtenderSettings settings) { 19 | setAttemptMergeAbort(settings.getAttemptMergeAbort()); 20 | setPruneLocals(settings.getPruneLocals()); 21 | } 22 | 23 | private boolean getAttemptMergeAbort() { 24 | return getApplicationProperties().getBoolean(ATTEMPT_MERGE_ABORT_KEY); 25 | } 26 | 27 | private boolean getPruneLocals() { 28 | return getApplicationProperties().getBoolean(PRUNE_LOCALS_KEY); 29 | } 30 | 31 | private void setAttemptMergeAbort(boolean attemptMergeAbort) { 32 | getApplicationProperties().setValue(ATTEMPT_MERGE_ABORT_KEY, attemptMergeAbort); 33 | } 34 | 35 | private void setPruneLocals(boolean pruneLocals) { 36 | getApplicationProperties().setValue(PRUNE_LOCALS_KEY, pruneLocals); 37 | } 38 | 39 | @NotNull 40 | private PropertiesComponent getApplicationProperties() { 41 | return PropertiesComponent.getInstance(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/configuration/ProjectSettingsHandler.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.configuration; 2 | 3 | import com.intellij.ide.util.PropertiesComponent; 4 | import com.intellij.openapi.project.Project; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class ProjectSettingsHandler { 11 | static final String PREFIX = "gr.jchrist.gitextender."; 12 | static final String SELECTED_MODULES_KEY = PREFIX + "selectedModules"; 13 | 14 | private final Project project; 15 | private final PropertiesComponent properties; 16 | 17 | public ProjectSettingsHandler(@NotNull Project project) { 18 | this.project = project; 19 | this.properties = PropertiesComponent.getInstance(this.project); 20 | } 21 | 22 | @NotNull 23 | public List loadSelectedModules() { 24 | List selectedModules = properties.getList(SELECTED_MODULES_KEY); 25 | if (selectedModules == null) { 26 | return new ArrayList<>(); 27 | } 28 | 29 | return new ArrayList<>(selectedModules); 30 | } 31 | 32 | public void addSelectedModule(@NotNull String module) { 33 | List modules = loadSelectedModules(); 34 | if (!modules.contains(module)) { 35 | modules.add(module); 36 | properties.setList(SELECTED_MODULES_KEY, modules); 37 | } 38 | } 39 | 40 | public void removeSelectedModule(@NotNull String module) { 41 | List modules = loadSelectedModules(); 42 | if (modules.contains(module)) { 43 | modules.remove(module); 44 | if (modules.isEmpty()) { 45 | clearSelectedModules(); 46 | } else { 47 | properties.setList(SELECTED_MODULES_KEY, modules); 48 | } 49 | } 50 | } 51 | 52 | public void setSelectedModules(@NotNull List modules) { 53 | properties.setList(SELECTED_MODULES_KEY, new ArrayList<>(modules)); 54 | } 55 | 56 | public void clearSelectedModules() { 57 | properties.setList(SELECTED_MODULES_KEY, new ArrayList<>()); 58 | properties.unsetValue(SELECTED_MODULES_KEY); 59 | } 60 | 61 | public Project getProject() { 62 | return project; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/configuration/SettingsConfigurableProvider.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.configuration; 2 | 3 | import com.intellij.openapi.options.Configurable; 4 | import com.intellij.openapi.options.ConfigurableProvider; 5 | import org.jetbrains.annotations.Nullable; 6 | 7 | public class SettingsConfigurableProvider extends ConfigurableProvider { 8 | 9 | @Nullable 10 | @Override 11 | public Configurable createConfigurable() { 12 | return new SettingsView(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/configuration/SettingsDialog.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.configuration; 2 | 3 | import com.intellij.openapi.project.Project; 4 | import com.intellij.openapi.ui.DialogWrapper; 5 | import com.intellij.openapi.ui.ValidationInfo; 6 | import org.jetbrains.annotations.Nullable; 7 | 8 | import javax.swing.JComponent; 9 | 10 | public class SettingsDialog extends DialogWrapper { 11 | 12 | private SettingsView settingsView = new SettingsView(); 13 | 14 | public SettingsDialog(@Nullable Project project) { 15 | super(project); 16 | init(); 17 | } 18 | 19 | @Override 20 | protected void init() { 21 | super.init(); 22 | setTitle("Git Extender Settings"); 23 | } 24 | 25 | @Nullable 26 | @Override 27 | protected ValidationInfo doValidate() { 28 | return null; 29 | } 30 | 31 | @Nullable 32 | @Override 33 | protected JComponent createCenterPanel() { 34 | return settingsView.createComponent(); 35 | } 36 | 37 | SettingsView getSettingsView() { 38 | return settingsView; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/configuration/SettingsView.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 |
39 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/configuration/SettingsView.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.configuration; 2 | 3 | import com.intellij.openapi.options.ConfigurationException; 4 | import com.intellij.openapi.options.SearchableConfigurable; 5 | import org.jetbrains.annotations.Nls; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.jetbrains.annotations.Nullable; 8 | 9 | import javax.swing.JCheckBox; 10 | import javax.swing.JComponent; 11 | import javax.swing.JPanel; 12 | 13 | public class SettingsView implements SearchableConfigurable { 14 | public static final String DIALOG_TITLE = "GitExtender Settings"; 15 | private GitExtenderSettingsHandler settingsHandler; 16 | private GitExtenderSettings originalSavedSettings; 17 | 18 | private JPanel mainPanel; 19 | private JCheckBox attemptMergeAbort; 20 | private JCheckBox pruneLocals; 21 | 22 | public SettingsView() { 23 | super(); 24 | 25 | this.settingsHandler = new GitExtenderSettingsHandler(); 26 | this.originalSavedSettings = settingsHandler.loadSettings(); 27 | } 28 | 29 | @NotNull 30 | @Override 31 | public String getId() { 32 | return DIALOG_TITLE; 33 | } 34 | 35 | @Nls 36 | @Override 37 | public String getDisplayName() { 38 | return DIALOG_TITLE; 39 | } 40 | 41 | @Nullable 42 | @Override 43 | public String getHelpTopic() { 44 | return null; 45 | } 46 | 47 | @Nullable 48 | @Override 49 | public JComponent createComponent() { 50 | reset(); 51 | return mainPanel; 52 | } 53 | 54 | @Override 55 | public boolean isModified() { 56 | GitExtenderSettings selected = selected(); 57 | return selected == null || !selected.equals(originalSavedSettings); 58 | } 59 | 60 | @Override 61 | public void apply() throws ConfigurationException { 62 | GitExtenderSettings selected = selected(); 63 | settingsHandler.saveSettings(selected); 64 | originalSavedSettings = settingsHandler.loadSettings(); 65 | } 66 | 67 | @Override 68 | public void reset() { 69 | attemptMergeAbort.setSelected(originalSavedSettings != null && originalSavedSettings.getAttemptMergeAbort()); 70 | pruneLocals.setSelected(originalSavedSettings != null && originalSavedSettings.getPruneLocals()); 71 | } 72 | 73 | @Override 74 | public void disposeUIResources() { 75 | mainPanel = null; 76 | attemptMergeAbort = null; 77 | pruneLocals = null; 78 | } 79 | 80 | protected GitExtenderSettings selected() { 81 | return new GitExtenderSettings(attemptMergeAbort != null && attemptMergeAbort.isSelected(), 82 | pruneLocals != null && pruneLocals.isSelected()); 83 | } 84 | 85 | JPanel getMainPanel() { 86 | return mainPanel; 87 | } 88 | 89 | JCheckBox getAttemptMergeAbort() { 90 | return attemptMergeAbort; 91 | } 92 | 93 | JCheckBox getPruneLocals() { 94 | return pruneLocals; 95 | } 96 | } -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/dialog/SelectModuleDialog.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 |
52 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/dialog/SelectModuleDialog.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.dialog; 2 | 3 | import com.intellij.ide.util.ElementsChooser; 4 | import com.intellij.openapi.ui.DialogWrapper; 5 | import gr.jchrist.gitextender.configuration.ProjectSettingsHandler; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.jetbrains.annotations.Nullable; 8 | 9 | import javax.swing.JButton; 10 | import javax.swing.JComponent; 11 | import javax.swing.JPanel; 12 | import javax.swing.JScrollPane; 13 | import java.util.List; 14 | 15 | public class SelectModuleDialog extends DialogWrapper { 16 | private final ProjectSettingsHandler settingsHandler; 17 | private final List repos; 18 | 19 | private JPanel contentPane; 20 | private JScrollPane scrollPane; 21 | protected JButton selectAllBtn; 22 | protected JButton selectNoneBtn; 23 | protected ElementsChooser repoChooser; 24 | 25 | public SelectModuleDialog(@NotNull ProjectSettingsHandler projectSettingsHandler, @NotNull List repos) { 26 | super(projectSettingsHandler.getProject()); 27 | this.repos = repos; 28 | this.settingsHandler = projectSettingsHandler; 29 | 30 | init(); 31 | setTitle("Select Modules to Update"); 32 | } 33 | 34 | @Override 35 | protected void init() { 36 | super.init(); 37 | 38 | this.selectAllBtn.addActionListener(evt -> { 39 | settingsHandler.setSelectedModules(repos); 40 | repoChooser.setAllElementsMarked(true); 41 | }); 42 | this.selectNoneBtn.addActionListener(evt -> { 43 | settingsHandler.clearSelectedModules(); 44 | repoChooser.setAllElementsMarked(false); 45 | }); 46 | 47 | List savedSelection = settingsHandler.loadSelectedModules(); 48 | //make sure we don't have stale entries 49 | savedSelection.removeIf(str -> { 50 | if (!repos.contains(str)) { 51 | settingsHandler.removeSelectedModule(str); 52 | return true; 53 | } 54 | return false; 55 | }); 56 | 57 | repoChooser.markElements(savedSelection); 58 | setOKActionEnabled(!savedSelection.isEmpty()); 59 | } 60 | 61 | @Nullable 62 | @Override 63 | protected JComponent createCenterPanel() { 64 | return contentPane; 65 | } 66 | 67 | protected void createUIComponents() { 68 | repoChooser = new ElementsChooser<>(repos, false); 69 | repoChooser.addElementsMarkListener((ElementsChooser.ElementsMarkListener) (element, isMarked) -> { 70 | if (isMarked) { 71 | settingsHandler.addSelectedModule(element); 72 | } else { 73 | settingsHandler.removeSelectedModule(element); 74 | } 75 | 76 | setOKActionEnabled(!settingsHandler.loadSelectedModules().isEmpty()); 77 | }); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/handlers/AfterFailedMergeHandler.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | public class AfterFailedMergeHandler extends AfterMergeHandler { 6 | public AfterFailedMergeHandler(@NotNull MergeState mergeState) { 7 | super(mergeState); 8 | } 9 | 10 | @Override 11 | public void afterMerge() { 12 | mergeState.getLocalHistoryAction().finish(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/handlers/AfterMergeHandler.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import gr.jchrist.gitextender.BranchUpdateResult; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | public abstract class AfterMergeHandler { 7 | protected final MergeState mergeState; 8 | 9 | public AfterMergeHandler(@NotNull MergeState mergeState) { 10 | this.mergeState = mergeState; 11 | } 12 | 13 | @NotNull 14 | public static AfterMergeHandler getInstance( 15 | @NotNull BranchUpdateResult branchUpdateResult, 16 | @NotNull MergeState mergeState) { 17 | return (branchUpdateResult.isMergeSuccess() ? 18 | new AfterSuccessfulMergeHandler(mergeState) : 19 | new AfterFailedMergeHandler(mergeState)); 20 | } 21 | 22 | public abstract void afterMerge(); 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/handlers/AfterSuccessfulMergeHandler.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import com.intellij.history.Label; 4 | import com.intellij.history.LocalHistory; 5 | import com.intellij.openapi.application.ApplicationManager; 6 | import com.intellij.openapi.application.ModalityState; 7 | import com.intellij.openapi.diagnostic.Logger; 8 | import com.intellij.openapi.vcs.changes.VcsAnnotationRefresher; 9 | import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx; 10 | import com.intellij.openapi.vcs.update.ActionInfo; 11 | import com.intellij.openapi.vcs.update.RestoreUpdateTree; 12 | import com.intellij.openapi.vcs.update.UpdateFilesHelper; 13 | import com.intellij.openapi.vcs.update.UpdateInfoTree; 14 | import com.intellij.ui.content.ContentManager; 15 | import com.intellij.vcs.ViewUpdateInfoNotification; 16 | import git4idea.merge.MergeChangeCollector; 17 | import org.jetbrains.annotations.NotNull; 18 | 19 | public class AfterSuccessfulMergeHandler extends AfterMergeHandler { 20 | private static final Logger logger = Logger.getInstance(AfterSuccessfulMergeHandler.class); 21 | public AfterSuccessfulMergeHandler(@NotNull MergeState mergeState) { 22 | super(mergeState); 23 | } 24 | 25 | @Override 26 | public void afterMerge() { 27 | //we managed to update the branch, so let's try to get which files were updated 28 | gatherChanges(); 29 | refreshFiles(); 30 | mergeState.getLocalHistoryAction().finish(); 31 | 32 | // TODO: disabling to work around issue https://github.com/JChrist/gitextender/issues/21 33 | // showUpdatedFiles(); 34 | } 35 | 36 | protected void gatherChanges() { 37 | MergeChangeCollector collector = new MergeChangeCollector( 38 | mergeState.getProject(), mergeState.getRepo(), mergeState.getStart()); 39 | try { 40 | collector.collect(mergeState.getUpdatedFiles()); 41 | } catch (Exception e) { 42 | logger.warn("error collecting updated files", e); 43 | } 44 | } 45 | 46 | protected void refreshFiles() { 47 | //request that we update repo for all updated files 48 | //RefreshVFsSynchronously.updateAllChanged(mergeState.getUpdatedFiles()); 49 | 50 | //also notify annotations 51 | final VcsAnnotationRefresher refresher = mergeState.getProject().getMessageBus() 52 | .syncPublisher(VcsAnnotationRefresher.LOCAL_CHANGES_CHANGED); 53 | UpdateFilesHelper.iterateFileGroupFilesDeletedOnServerFirst(mergeState.getUpdatedFiles(), 54 | (filePath, groupId) -> refresher.dirty(filePath)); 55 | } 56 | 57 | protected void showUpdatedFiles() { 58 | //if no files were updated, then there's nothing else to do 59 | if (mergeState.getUpdatedFiles().isEmpty()) { 60 | return; 61 | } 62 | 63 | final UpdateInfoTree tree = generateUpdateInfoTree(); 64 | showUpdateTree(tree); 65 | } 66 | 67 | public UpdateInfoTree generateUpdateInfoTree() { 68 | if (!mergeState.getProject().isOpen() || mergeState.getProject().isDisposed()) { 69 | logger.debug("project is not open or disposed! returning null tree!"); 70 | return null; 71 | } 72 | //now create the *after* update label, so that we have the before (from mergeState) and the after update diff 73 | final Label after = LocalHistory.getInstance().putSystemLabel(mergeState.getProject(), 74 | "After updating:" + mergeState.getProject().getName() + " " + 75 | mergeState.getLocalBranchName()); 76 | 77 | ActionInfo actionInfo = ActionInfo.UPDATE; 78 | RestoreUpdateTree restoreUpdateTree = RestoreUpdateTree.getInstance(mergeState.getProject()); 79 | restoreUpdateTree.registerUpdateInformation(mergeState.getUpdatedFiles(), actionInfo); 80 | final String text = "GitExtender updated Repo:" + mergeState.getRepoName() + " " + 81 | mergeState.getLocalBranchName() + "->" + mergeState.getRemoteBranchName(); 82 | //don't use the one from project level vcs manager, since we want to split creation of tree from showing 83 | /*final UpdateInfoTree updateInfoTree = ProjectLevelVcsManagerEx.getInstanceEx(project). 84 | showUpdateProjectInfo(updatedFiles, text, actionInfo, false);*/ 85 | 86 | ProjectLevelVcsManagerEx plm = ProjectLevelVcsManagerEx.getInstanceEx(mergeState.getProject()); 87 | ContentManager cm = plm != null ? plm.getContentManager() : null; 88 | if (cm == null) { 89 | logger.debug("content manager is null! returning null tree"); 90 | return null; 91 | } 92 | 93 | final UpdateInfoTree updateInfoTree = new UpdateInfoTree(cm, 94 | mergeState.getProject(), 95 | mergeState.getUpdatedFiles(), text, actionInfo); 96 | 97 | updateInfoTree.setBefore(mergeState.getBefore()); 98 | updateInfoTree.setAfter(after); 99 | 100 | updateInfoTree.setCanGroupByChangeList(false); 101 | 102 | return updateInfoTree; 103 | } 104 | 105 | protected void showUpdateTree(final UpdateInfoTree tree) { 106 | if (!mergeState.getProject().isOpen() || mergeState.getProject().isDisposed() || tree == null) return; 107 | ApplicationManager.getApplication().invokeLater(() -> ViewUpdateInfoNotification.focusUpdateInfoTree(mergeState.getProject(), tree), ModalityState.defaultModalityState()); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/handlers/BeforeMergeHandler.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import com.intellij.history.Label; 4 | import com.intellij.history.LocalHistory; 5 | import com.intellij.history.LocalHistoryAction; 6 | import com.intellij.openapi.project.Project; 7 | import com.intellij.openapi.vcs.update.UpdatedFiles; 8 | import com.intellij.openapi.vfs.VirtualFile; 9 | import git4idea.GitRevisionNumber; 10 | import git4idea.repo.GitRepository; 11 | import org.jetbrains.annotations.NotNull; 12 | 13 | public class BeforeMergeHandler { 14 | private final Project project; 15 | private final VirtualFile root; 16 | private final GitRepository repo; 17 | private final String repoName; 18 | private final String localBranchName; 19 | private final String remoteBranchName; 20 | 21 | public BeforeMergeHandler( 22 | @NotNull Project project, 23 | @NotNull VirtualFile root, 24 | @NotNull GitRepository repo, 25 | @NotNull String repoName, 26 | @NotNull String localBranchName, 27 | @NotNull String remoteBranchName) { 28 | this.project = project; 29 | this.root = root; 30 | this.repo = repo; 31 | this.repoName = repoName; 32 | this.localBranchName = localBranchName; 33 | this.remoteBranchName = remoteBranchName; 34 | } 35 | 36 | @NotNull 37 | public MergeState beforeMerge() { 38 | //record the starting revision number 39 | GitRevisionNumber start; 40 | try { 41 | start = GitRevisionNumber.resolve(project, root, "HEAD"); 42 | } catch (Exception e) { 43 | //we failed to get a revision number, that shouldn't stop us from updating the branch 44 | start = null; 45 | } 46 | 47 | final String beforeLabel = getBeforeLocalHistoryLabel(); 48 | Label before = LocalHistory.getInstance().putSystemLabel(project, beforeLabel); 49 | LocalHistoryAction myLocalHistoryAction = LocalHistory.getInstance().startAction(beforeLabel); 50 | 51 | //keep track of all updated files 52 | UpdatedFiles updatedFiles = UpdatedFiles.create(); 53 | return new MergeState(project, root, repo, repoName, localBranchName, remoteBranchName, 54 | start, before, myLocalHistoryAction, updatedFiles); 55 | } 56 | 57 | protected String getBeforeLocalHistoryLabel() { 58 | return "Before updating:" + repoName + " " + localBranchName; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/handlers/CheckoutHandler.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import com.intellij.openapi.project.Project; 4 | import com.intellij.openapi.vfs.VirtualFile; 5 | import git4idea.commands.Git; 6 | import git4idea.commands.GitCommand; 7 | import git4idea.commands.GitCommandResult; 8 | import git4idea.commands.GitLineHandler; 9 | import org.jetbrains.annotations.NotNull; 10 | 11 | public class CheckoutHandler { 12 | private final Git git; 13 | private final Project project; 14 | private final VirtualFile root; 15 | 16 | public CheckoutHandler( 17 | @NotNull Git git, 18 | @NotNull Project project, 19 | @NotNull VirtualFile root) { 20 | this.git = git; 21 | this.project = project; 22 | this.root = root; 23 | } 24 | 25 | @NotNull 26 | public GitCommandResult checkout(String localBranchName) { 27 | GitCommand checkout = GitCommand.CHECKOUT; 28 | GitLineHandler checkoutHandler = new GitLineHandler(project, root, checkout); 29 | checkoutHandler.addParameters(localBranchName); 30 | return git.runCommand(checkoutHandler); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/handlers/DeleteHandler.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import com.intellij.openapi.project.Project; 4 | import com.intellij.openapi.vfs.VirtualFile; 5 | import git4idea.commands.Git; 6 | import git4idea.commands.GitCommand; 7 | import git4idea.commands.GitCommandResult; 8 | import git4idea.commands.GitLineHandler; 9 | import org.jetbrains.annotations.NotNull; 10 | 11 | public class DeleteHandler { 12 | public static final String DELETE_FLAG = "-D"; 13 | private final Git git; 14 | private final Project project; 15 | private final VirtualFile root; 16 | 17 | public DeleteHandler( 18 | @NotNull Git git, 19 | @NotNull Project project, 20 | @NotNull VirtualFile root) { 21 | this.git = git; 22 | this.project = project; 23 | this.root = root; 24 | } 25 | 26 | @NotNull 27 | public GitCommandResult delete(String localBranchName) { 28 | GitCommand checkout = GitCommand.BRANCH; 29 | GitLineHandler deleteHandler = new GitLineHandler(project, root, checkout); 30 | deleteHandler.addParameters(DELETE_FLAG, localBranchName); 31 | return git.runCommand(deleteHandler); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/handlers/FastForwardOnlyMerger.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import com.intellij.openapi.project.Project; 4 | import com.intellij.openapi.vfs.VirtualFile; 5 | import git4idea.commands.Git; 6 | import git4idea.commands.GitCommand; 7 | import git4idea.commands.GitCommandResult; 8 | import git4idea.commands.GitLineHandler; 9 | import org.jetbrains.annotations.NotNull; 10 | 11 | public class FastForwardOnlyMerger { 12 | private final Git git; 13 | private final Project project; 14 | private final VirtualFile root; 15 | private final String remoteBranchName; 16 | 17 | public FastForwardOnlyMerger( 18 | @NotNull Git git, 19 | @NotNull Project project, 20 | @NotNull VirtualFile root, 21 | @NotNull String remoteBranchName) { 22 | this.git = git; 23 | this.project = project; 24 | this.root = root; 25 | this.remoteBranchName = remoteBranchName; 26 | } 27 | 28 | @NotNull 29 | public GitCommandResult mergeFastForward() { 30 | //merge with -ff only 31 | GitCommand merge = GitCommand.MERGE; 32 | GitLineHandler mergeHandler = new GitLineHandler(project, root, merge); 33 | mergeHandler.addParameters("--ff-only"); 34 | mergeHandler.addParameters(remoteBranchName); 35 | return git.runCommand(mergeHandler); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/handlers/MergeState.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import com.intellij.history.Label; 4 | import com.intellij.history.LocalHistoryAction; 5 | import com.intellij.openapi.project.Project; 6 | import com.intellij.openapi.vcs.update.UpdatedFiles; 7 | import com.intellij.openapi.vfs.VirtualFile; 8 | import git4idea.GitRevisionNumber; 9 | import git4idea.repo.GitRepository; 10 | import org.jetbrains.annotations.NotNull; 11 | import org.jetbrains.annotations.Nullable; 12 | 13 | public class MergeState { 14 | private final Project project; 15 | private final VirtualFile root; 16 | private final GitRepository repo; 17 | private final String repoName; 18 | private final String localBranchName; 19 | private final String remoteBranchName; 20 | private final GitRevisionNumber start; 21 | private final Label before; 22 | private final LocalHistoryAction localHistoryAction; 23 | private final UpdatedFiles updatedFiles; 24 | 25 | //for tests 26 | MergeState() { 27 | this.project = null; 28 | this.root = null; 29 | this.repo = null; 30 | this.repoName = null; 31 | this.localBranchName = null; 32 | this.remoteBranchName = null; 33 | this.start = null; 34 | this.before = null; 35 | this.localHistoryAction = null; 36 | this.updatedFiles = null; 37 | } 38 | 39 | public MergeState( 40 | @NotNull Project project, @NotNull VirtualFile root, @NotNull GitRepository repo, 41 | @NotNull String repoName, @NotNull String localBranchName, @NotNull String remoteBranchName, 42 | @Nullable GitRevisionNumber start, @NotNull Label before, 43 | @NotNull LocalHistoryAction localHistoryAction, @NotNull UpdatedFiles updatedFiles) { 44 | this.project = project; 45 | this.root = root; 46 | this.repo = repo; 47 | this.repoName = repoName; 48 | this.localBranchName = localBranchName; 49 | this.remoteBranchName = remoteBranchName; 50 | this.start = start; 51 | this.before = before; 52 | this.localHistoryAction = localHistoryAction; 53 | this.updatedFiles = updatedFiles; 54 | } 55 | 56 | public Project getProject() { 57 | return project; 58 | } 59 | 60 | public VirtualFile getRoot() { 61 | return root; 62 | } 63 | 64 | public GitRepository getRepo() { 65 | return repo; 66 | } 67 | 68 | public String getRepoName() { 69 | return repoName; 70 | } 71 | 72 | public String getLocalBranchName() { 73 | return localBranchName; 74 | } 75 | 76 | public String getRemoteBranchName() { 77 | return remoteBranchName; 78 | } 79 | 80 | public GitRevisionNumber getStart() { 81 | return start; 82 | } 83 | 84 | public Label getBefore() { 85 | return before; 86 | } 87 | 88 | public LocalHistoryAction getLocalHistoryAction() { 89 | return localHistoryAction; 90 | } 91 | 92 | public UpdatedFiles getUpdatedFiles() { 93 | return updatedFiles; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/handlers/SimpleMerger.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import com.intellij.openapi.project.Project; 4 | import com.intellij.openapi.vfs.VirtualFile; 5 | import git4idea.commands.Git; 6 | import git4idea.commands.GitCommand; 7 | import git4idea.commands.GitCommandResult; 8 | import git4idea.commands.GitLineHandler; 9 | import org.jetbrains.annotations.NotNull; 10 | import org.jetbrains.annotations.Nullable; 11 | 12 | public class SimpleMerger { 13 | private final Git git; 14 | private final Project project; 15 | private final VirtualFile root; 16 | private final String remoteBranchName; 17 | 18 | private GitCommandResult mergeResult; 19 | private GitCommandResult abortResult; 20 | 21 | public SimpleMerger( 22 | @NotNull Git git, 23 | @NotNull Project project, 24 | @NotNull VirtualFile root, 25 | @NotNull String remoteBranchName 26 | ) { 27 | this.git = git; 28 | this.project = project; 29 | this.root = root; 30 | this.remoteBranchName = remoteBranchName; 31 | } 32 | 33 | public void mergeAbortIfFailed() { 34 | merge(); 35 | 36 | if (mergeResult.success()) { 37 | return; 38 | } 39 | 40 | abortMerge(); 41 | } 42 | 43 | protected void merge() { 44 | //try simple merging, abort if failed 45 | GitCommand merge = GitCommand.MERGE; 46 | GitLineHandler mergeHandler = new GitLineHandler(project, root, merge); 47 | mergeHandler.addParameters(remoteBranchName); 48 | mergeResult = git.runCommand(mergeHandler); 49 | } 50 | 51 | protected void abortMerge() { 52 | //we failed, now abort the process 53 | GitCommand abort = GitCommand.MERGE; 54 | GitLineHandler abortHandler = new GitLineHandler(project, root, abort); 55 | abortHandler.addParameters("--abort"); 56 | abortResult = git.runCommand(abortHandler); 57 | 58 | if (!abortResult.success()) { 59 | //We have really messed up! What can I do now? 60 | } 61 | } 62 | 63 | @NotNull 64 | public GitCommandResult getMergeResult() { 65 | return mergeResult; 66 | } 67 | 68 | @Nullable 69 | public GitCommandResult getAbortResult() { 70 | return abortResult; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/gr/jchrist/gitextender/handlers/UpdatedFilesNotifier.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import com.intellij.openapi.util.text.StringUtil; 4 | import com.intellij.openapi.vcs.update.FileGroup; 5 | import com.intellij.openapi.vcs.update.UpdatedFiles; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | import java.util.List; 9 | 10 | public class UpdatedFilesNotifier { 11 | private final UpdatedFiles updatedFiles; 12 | 13 | public UpdatedFilesNotifier(@NotNull UpdatedFiles updatedFiles) { 14 | this.updatedFiles = updatedFiles; 15 | } 16 | 17 | @NotNull 18 | public String prepareNotificationWithUpdateInfo() { 19 | StringBuilder text = new StringBuilder(); 20 | final List groups = updatedFiles.getTopLevelGroups(); 21 | for (FileGroup group : groups) { 22 | appendGroup(text, group); 23 | } 24 | return text.toString(); 25 | } 26 | 27 | private void appendGroup(final StringBuilder text, final FileGroup group) { 28 | final int s = group.getFiles().size(); 29 | if (s > 0) { 30 | text.append("\n"); 31 | text.append(s).append(" ").append(StringUtil.pluralize("File", s)).append(" ").append(group.getUpdateName()); 32 | } 33 | 34 | final List list = group.getChildren(); 35 | for (FileGroup g : list) { 36 | appendGroup(text, g); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | gr.jchrist.gitextender 3 | Git Extender 4 | 0.8.2 5 | JChrist 6 | 7 | Update All 9 | local branches tracking a remote for all git roots in the current project
10 | Local branches that will be updated are the branches that exist locally and have been configured 11 | to track a remote branch.
12 |

It requires IDE version 2022.2 or higher and Java 17+

13 | It tries to fast-forward commits in remote branches to local branches. 14 | It can be configured through the settings to attempt a simple merge, 15 | if the local branch cannot be merged to the tracked remote using fast-forward only. 16 | In this case, if there are conflict errors, the merge will be aborted and an error notification will be shown. 17 | The update, then, should be performed manually for the reported branch, in order to resolve the conflicts. 18 | Any possible uncommitted changes to the current branch will be stashed
19 | After updating a branch, if there were any file changes, they will be displayed in IntelliJ Version Control tab. 20 |
21 | This plugin is available under Apache License, Version 2.0 22 | ]]>
23 | 24 | 26 |
  • 27 | 0.8.2: Update dependencies 28 |
  • 29 |
  • 30 | 0.8.1: Limit number of threads for updates. Closes [#55](https://github.com/JChrist/gitextender/issues/55) 31 |
  • 32 |
  • 33 | 0.8.0: Fix no display name for configurable. Closes [#70](https://github.com/JChrist/gitextender/issues/70) 34 |
  • 35 |
  • 36 | 0.7.0: Workaround issue with wrong thread creating the update tree, by disabling showing update tree 37 |
  • 38 |
  • 39 | 0.6.0: Fixed plugin display in menu 40 |
  • 41 |
  • 42 | 0.5.2: Fixed missing backgroundable task spinning notification and disabled concurrent executions 43 |
  • 44 |
  • 45 | 0.5.1: Updated threading model for updating repositories 46 |
  • 47 |
  • 48 | 0.5.0: Added an option for removing local branches that were tracking a remote one that was pruned 49 |
  • 50 |
  • 51 | 0.4.1: 52 | Fix for issue #8: Create UpdateInfoTree from the event dispatch thread 53 |
  • 54 |
  • 55 | 0.4.0: 56 | For projects with multiple modules as separate Git roots, a dialog will open up, 57 | offering the option to select which module(s) to update. 58 | Refactored persisted configuration settings. 59 |
  • 60 |
  • 61 | 0.3.1: Removed until build version from plugin.xml, so that the plugin is compatible with latest releases 62 |
  • 63 |
  • 64 | 0.3.0: Added configuration settings for GitExtender, offering options to control 65 | whether it will perform fast-forward-only merges, or if it will attempt simple merge and abort on error. 66 | Settings can be accessed via File->Settings->Other Settings->GitExtender Settings. 67 | Switched to java 8 support, so running it will require that the IDE runs on java 8 68 |
  • 69 |
  • 70 | 0.2.0: Keeping track of updated files, as results to be displayed after updating. ***Requires latest version: 145*** 71 | The displayed updated files may show invalid/incorrect differences (in the show diff dialog) 72 |
  • 73 |
  • 0.1.3: Changed pull method from rebase to merge, with the --ff-only flag (fast-forward only)
  • 74 |
  • 0.1.2: Using GitFetcher to fetch and prune remotes and show results before starting the update
  • 75 |
  • 0.1.1: 76 | Changed jdk to 1.7, so that the plugin works with IDEA running with 1.7 jdk 77 | Added check if any staged or unstaged changes exist in each repository, in order to stash only if needed
  • 78 |
  • 0.1: 79 | Initial version of Git Extender, with support for updating all local branches 80 | tracking a remote of all git roots in the current project, 81 | using rebase for all local commits and automatic stashing/popping of uncommitted changes
  • 82 | 83 | ]]> 84 |
    85 | 86 | 87 | 88 | 89 | com.intellij.modules.lang 90 | com.intellij.modules.vcs 91 | Git4Idea 92 | 93 | 94 | 95 | 96 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 113 | 114 | 115 | 116 | 117 | 118 |
    119 | -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/AbstractIT.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender; 2 | 3 | import com.intellij.ide.highlighter.ProjectFileType; 4 | import com.intellij.openapi.application.ApplicationManager; 5 | import com.intellij.openapi.diagnostic.Logger; 6 | import com.intellij.openapi.project.Project; 7 | import com.intellij.openapi.util.io.FileUtil; 8 | import com.intellij.openapi.util.text.StringUtil; 9 | import com.intellij.openapi.vcs.AbstractVcs; 10 | import com.intellij.openapi.vcs.ProjectLevelVcsManager; 11 | import com.intellij.openapi.vcs.VcsConfiguration; 12 | import com.intellij.openapi.vcs.VcsNotifier; 13 | import com.intellij.openapi.vcs.VcsShowConfirmationOption; 14 | import com.intellij.openapi.vcs.changes.ChangeListManager; 15 | import com.intellij.openapi.vcs.changes.ChangeListManagerImpl; 16 | import com.intellij.openapi.vfs.LocalFileSystem; 17 | import com.intellij.openapi.vfs.VfsUtil; 18 | import com.intellij.openapi.vfs.VirtualFile; 19 | import com.intellij.testFramework.HeavyPlatformTestCase; 20 | import com.intellij.testFramework.TestLoggerFactory; 21 | import com.intellij.util.ArrayUtil; 22 | import git4idea.DialogManager; 23 | import git4idea.GitUtil; 24 | import git4idea.GitVcs; 25 | import git4idea.commands.Git; 26 | import git4idea.config.GitVcsSettings; 27 | import git4idea.repo.GitRepository; 28 | import git4idea.repo.GitRepositoryManager; 29 | import org.junit.After; 30 | import org.junit.Before; 31 | import org.junit.Rule; 32 | import org.junit.rules.TestName; 33 | 34 | import java.io.File; 35 | import java.io.IOException; 36 | import java.util.Arrays; 37 | import java.util.Collection; 38 | import java.util.Collections; 39 | import java.util.concurrent.CountDownLatch; 40 | import java.util.concurrent.TimeUnit; 41 | 42 | public abstract class AbstractIT extends HeavyPlatformTestCase { 43 | private static final Logger logger = Logger.getInstance(GitTestUtil.class); 44 | 45 | protected File myTestRoot; 46 | protected VirtualFile myTestRootFile; 47 | protected VirtualFile myProjectRoot; 48 | protected String myProjectPath; 49 | protected String myTestStartedIndicator; 50 | protected ChangeListManagerImpl changeListManager; 51 | protected GitRepositoryManager myGitRepositoryManager; 52 | protected GitVcsSettings myGitSettings; 53 | protected Git myGit; 54 | protected GitVcs myVcs; 55 | protected DialogManager myDialogManager; 56 | protected VcsNotifier myVcsNotifier; 57 | 58 | @Rule 59 | public TestName testName = new TestName(); 60 | 61 | private boolean stopped = false; 62 | 63 | @Before 64 | public final void abstractSetUp() throws Exception { 65 | myTestRoot = new File(FileUtil.getTempDirectory(), "testRoot"); 66 | checkTestRootIsEmpty(myTestRoot); 67 | 68 | myTestRootFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(myTestRoot); 69 | this.refresh(); 70 | 71 | myTestStartedIndicator = enableDebugLogging(); 72 | 73 | myProjectPath = myProject.getBasePath(); 74 | 75 | changeListManager = (ChangeListManagerImpl) ChangeListManager.getInstance(myProject); 76 | 77 | myGitSettings = GitVcsSettings.getInstance(myProject); 78 | myGitSettings.getAppSettings().setPathToGit(GitExecutor.PathHolder.getGitExecutable()); 79 | 80 | myDialogManager = ApplicationManager.getApplication().getService(DialogManager.class); 81 | myVcsNotifier = myProject.getService(VcsNotifier.class); 82 | 83 | myGitRepositoryManager = GitUtil.getRepositoryManager(myProject); 84 | myGit = ApplicationManager.getApplication().getService(Git.class); 85 | myVcs = GitVcs.getInstance(myProject); 86 | myVcs.doActivate(); 87 | 88 | addSilently(); 89 | removeSilently(); 90 | } 91 | 92 | @After 93 | public final void abstractTearDown() throws Exception { 94 | if (stopped) return; 95 | stopped = true; 96 | try { 97 | //EdtTestUtil.runInEdtAndWait( () -> super.tearDown() ); 98 | } finally { 99 | if (myAssertionsInTestDetected && myTestStartedIndicator != null) { 100 | TestLoggerFactory.dumpLogToStdout(myTestStartedIndicator); 101 | } 102 | } 103 | } 104 | 105 | /** 106 | * Returns log categories which will be switched to DEBUG level. 107 | * Implementations must add theirs categories to the ones from super class, 108 | * not to erase log categories from the super class. 109 | * (e.g. by calling `super.getDebugLogCategories().plus(additionalCategories)`. 110 | */ 111 | protected Collection getDebugLogCategories() { 112 | return Collections.emptyList(); 113 | } 114 | 115 | public File getIprFile() throws IOException { 116 | File projectRoot = new File(myTestRoot, "project"); 117 | return FileUtil.createTempFile(projectRoot, getName() + "_", ProjectFileType.DOT_DEFAULT_EXTENSION); 118 | } 119 | 120 | @Override 121 | public void setUpModule() { 122 | // we don't need a module in Git tests 123 | } 124 | 125 | @Override 126 | public boolean runInDispatchThread() { 127 | return true; 128 | } 129 | 130 | /*@Override 131 | protected boolean isRunInWriteAction() { 132 | return true; 133 | } 134 | */ 135 | 136 | @Override 137 | public String getName() { 138 | String name = super.getName(); 139 | if (name != null) { 140 | return name; 141 | } 142 | return testName.getMethodName(); 143 | } 144 | 145 | @Override 146 | public String getTestName(boolean lowercaseFirstLetter) { 147 | String name = super.getTestName(lowercaseFirstLetter); 148 | name = StringUtil.shortenTextWithEllipsis(name.trim().replace(" ", "_"), 12, 6, "_"); 149 | if (name.startsWith("_")) { 150 | name = name.substring(1); 151 | } 152 | return name; 153 | } 154 | 155 | protected void refresh() { 156 | VfsUtil.markDirtyAndRefresh(false, true, false, myTestRootFile); 157 | } 158 | 159 | public void updateRepos() { 160 | updateRepos(null); 161 | } 162 | 163 | public void updateRepos(GitRepository repository) { 164 | var grm = getGitRepositoryManager(); 165 | runOutOfEdt(() -> { 166 | if (repository != null) { 167 | repository.update(); 168 | } 169 | grm.updateAllRepositories(); 170 | }); 171 | } 172 | 173 | private void checkTestRootIsEmpty(File testRoot) { 174 | File[] files = testRoot.listFiles(); 175 | if (files != null && files.length > 0) { 176 | LOG.warn("Test root was not cleaned up during some previous test run. " + "testRoot: " + testRoot + 177 | ", files: " + Arrays.toString(files)); 178 | for (File file : files) { 179 | LOG.assertTrue(FileUtil.delete(file)); 180 | } 181 | } 182 | } 183 | 184 | private String enableDebugLogging() { 185 | TestLoggerFactory.enableDebugLogging(getTestRootDisposable(), ArrayUtil.toStringArray(getDebugLogCategories())); 186 | String testStartedIndicator = createTestStartedIndicator(); 187 | LOG.info(testStartedIndicator); 188 | return testStartedIndicator; 189 | } 190 | 191 | private String createTestStartedIndicator() { 192 | return "Starting " + getClass().getName() + "." + getTestName(false) + Math.random(); 193 | } 194 | 195 | protected void addSilently() { 196 | doActionSilently(VcsConfiguration.StandardConfirmation.ADD); 197 | } 198 | 199 | protected void removeSilently() { 200 | doActionSilently(VcsConfiguration.StandardConfirmation.REMOVE); 201 | } 202 | 203 | protected void doActionSilently(VcsConfiguration.StandardConfirmation op) { 204 | setStandardConfirmation(myProject, GitVcs.NAME, op, VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY); 205 | } 206 | 207 | public static void setStandardConfirmation( 208 | Project project, String vcsName, VcsConfiguration.StandardConfirmation op, 209 | VcsShowConfirmationOption.Value value) { 210 | ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project); 211 | AbstractVcs vcs = vcsManager.findVcsByName(vcsName); 212 | VcsShowConfirmationOption option = vcsManager.getStandardConfirmation(op, vcs); 213 | option.setValue(value); 214 | } 215 | 216 | public File getTestRoot() { 217 | return myTestRoot; 218 | } 219 | 220 | public VirtualFile getTestRootFile() { 221 | return myTestRootFile; 222 | } 223 | 224 | public VirtualFile getProjectRoot() { 225 | return myProjectRoot; 226 | } 227 | 228 | public String getProjectPath() { 229 | return myProjectPath; 230 | } 231 | 232 | public String getTestStartedIndicator() { 233 | return myTestStartedIndicator; 234 | } 235 | 236 | public ChangeListManagerImpl getChangeListManager() { 237 | return changeListManager; 238 | } 239 | 240 | public GitRepositoryManager getGitRepositoryManager() { 241 | return myGitRepositoryManager; 242 | } 243 | 244 | public GitVcsSettings getGitSettings() { 245 | return myGitSettings; 246 | } 247 | 248 | public Git getGit() { 249 | return myGit; 250 | } 251 | 252 | public GitVcs getVcs() { 253 | return myVcs; 254 | } 255 | 256 | public DialogManager getDialogManager() { 257 | return myDialogManager; 258 | } 259 | 260 | public VcsNotifier getVcsNotifier() { 261 | return myVcsNotifier; 262 | } 263 | 264 | public static void runOutOfEdt(Runnable r) { 265 | final var latch = new CountDownLatch(1); 266 | ApplicationManager.getApplication().executeOnPooledThread(() -> { 267 | r.run(); 268 | latch.countDown(); 269 | }); 270 | try { 271 | latch.await(10, TimeUnit.SECONDS); 272 | } catch (Exception e) { 273 | logger.warn("error waiting", e); 274 | } 275 | } 276 | 277 | 278 | } 279 | -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/BranchUpdateResultTest.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender; 2 | 3 | import org.junit.Test; 4 | 5 | import static gr.jchrist.gitextender.TestingUtil.error; 6 | import static gr.jchrist.gitextender.TestingUtil.success; 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | 9 | public class BranchUpdateResultTest { 10 | @Test 11 | public void testIsSuccess() throws Exception { 12 | //success by fast forward 13 | assertThat(new BranchUpdateResult(success, success, null, null).isSuccess()).isTrue(); 14 | //success by simple merge 15 | assertThat(new BranchUpdateResult(success, error, success, null).isSuccess()).isTrue(); 16 | 17 | //error in checkout 18 | assertThat(new BranchUpdateResult(error, null, null, null).isSuccess()).isFalse(); 19 | 20 | //error in both merges with abort 21 | assertThat(new BranchUpdateResult(error, error, error, success).isSuccess()).isFalse(); 22 | 23 | //error in both merges with no abort result 24 | assertThat(new BranchUpdateResult(error, error, error, null).isSuccess()).isFalse(); 25 | 26 | //error in both merges with error abort result 27 | assertThat(new BranchUpdateResult(error, error, error, error).isSuccess()).isFalse(); 28 | } 29 | 30 | @Test 31 | public void testCheckoutCheck() throws Exception { 32 | BranchUpdateResult bur = new BranchUpdateResult(); 33 | bur.checkoutResult = success; 34 | assertThat(bur.isCheckoutSuccess()).isTrue(); 35 | assertThat(bur.isCheckoutError()).isFalse(); 36 | 37 | bur.checkoutResult = error; 38 | assertThat(bur.isCheckoutSuccess()).isFalse(); 39 | assertThat(bur.isCheckoutError()).isTrue(); 40 | } 41 | 42 | @Test 43 | public void testMergeCheck() throws Exception { 44 | BranchUpdateResult bur = new BranchUpdateResult(); 45 | bur.mergeFastForwardResult = success; 46 | bur.mergeSimpleResult = null; 47 | assertThat(bur.isMergeSuccess()).isTrue(); 48 | assertThat(bur.isMergeError()).isFalse(); 49 | 50 | bur.mergeFastForwardResult = error; 51 | bur.mergeSimpleResult = success; 52 | assertThat(bur.isMergeSuccess()).isTrue(); 53 | assertThat(bur.isMergeError()).isFalse(); 54 | 55 | bur.mergeFastForwardResult = error; 56 | bur.mergeSimpleResult = error; 57 | assertThat(bur.isMergeSuccess()).isFalse(); 58 | assertThat(bur.isMergeError()).isTrue(); 59 | 60 | bur.mergeFastForwardResult = null; 61 | bur.mergeSimpleResult = null; 62 | assertThat(bur.isMergeSuccess()).isFalse(); 63 | assertThat(bur.isMergeError()).isTrue(); 64 | } 65 | 66 | @Test 67 | public void testAbortCheck() throws Exception { 68 | BranchUpdateResult bur = new BranchUpdateResult(); 69 | 70 | assertThat(bur.isAbortSucceeded()).isFalse(); 71 | 72 | bur.abortResult = error; 73 | assertThat(bur.isAbortSucceeded()).isFalse(); 74 | 75 | bur.abortResult = success; 76 | assertThat(bur.isAbortSucceeded()).isTrue(); 77 | } 78 | 79 | @Test 80 | public void testGets() throws Exception { 81 | BranchUpdateResult bur = new BranchUpdateResult(success, success, success, success); 82 | assertThat(bur.getCheckoutResult()).isSameAs(success); 83 | assertThat(bur.getMergeFastForwardResult()).isSameAs(success); 84 | assertThat(bur.getMergeSimpleResult()).isSameAs(success); 85 | assertThat(bur.getAbortResult()).isSameAs(success); 86 | } 87 | } -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/GitExecutor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2000-2015 JetBrains s.r.o. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package gr.jchrist.gitextender; 17 | 18 | import com.intellij.execution.process.CapturingProcessHandler; 19 | import com.intellij.execution.process.ProcessOutput; 20 | import com.intellij.openapi.diagnostic.Logger; 21 | import com.intellij.openapi.util.io.FileUtil; 22 | import com.intellij.openapi.util.text.StringUtil; 23 | import com.intellij.openapi.vfs.CharsetToolkit; 24 | import org.jetbrains.annotations.NotNull; 25 | 26 | import java.io.File; 27 | import java.io.IOException; 28 | import java.util.ArrayList; 29 | import java.util.List; 30 | 31 | public class GitExecutor { 32 | 33 | protected static final Logger LOG = Logger.getInstance(GitExecutor.class); 34 | 35 | public static class ExecutionException extends RuntimeException { 36 | 37 | private final int myExitCode; 38 | @NotNull private final String myOutput; 39 | 40 | ExecutionException(int exitCode, @NotNull String output) { 41 | super("Failed with exit code " + exitCode+". Output: "+output); 42 | myExitCode = exitCode; 43 | myOutput = output; 44 | } 45 | 46 | public int getExitCode() { 47 | return myExitCode; 48 | } 49 | 50 | @NotNull 51 | public String getOutput() { 52 | return myOutput; 53 | } 54 | } 55 | 56 | private static String ourCurrentDir; 57 | 58 | private static void cdAbs(@NotNull String absolutePath) { 59 | ourCurrentDir = absolutePath; 60 | debug("# cd " + shortenPath(absolutePath)); 61 | } 62 | 63 | public static void debug(@NotNull String msg) { 64 | if (!StringUtil.isEmptyOrSpaces(msg)) { 65 | LOG.info(msg); 66 | } 67 | } 68 | 69 | private static void cdRel(@NotNull String relativePath) { 70 | cdAbs(ourCurrentDir + "/" + relativePath); 71 | } 72 | 73 | public static void cd(@NotNull String relativeOrAbsolutePath) { 74 | if (relativeOrAbsolutePath.startsWith("/") || relativeOrAbsolutePath.charAt(1) == ':') { 75 | cdAbs(relativeOrAbsolutePath); 76 | } else { 77 | cdRel(relativeOrAbsolutePath); 78 | } 79 | } 80 | 81 | @NotNull 82 | public static File touch(String filePath) { 83 | try { 84 | File file = child(filePath); 85 | assert !file.exists() : "File " + file + " shouldn't exist yet"; 86 | //noinspection ResultOfMethodCallIgnored 87 | new File(file.getParent()).mkdirs(); // ensure to create the directories 88 | boolean fileCreated = file.createNewFile(); 89 | assert fileCreated; 90 | debug("# touch " + filePath); 91 | return file; 92 | } catch (IOException e) { 93 | throw new RuntimeException(e); 94 | } 95 | } 96 | 97 | @NotNull 98 | public static File touch(@NotNull String fileName, @NotNull String content) { 99 | File filePath = touch(fileName); 100 | echo(fileName, content); 101 | return filePath; 102 | } 103 | 104 | public static void echo(@NotNull String fileName, @NotNull String content) { 105 | try { 106 | FileUtil.writeToFile(child(fileName), content.getBytes(), true); 107 | } catch (IOException e) { 108 | throw new RuntimeException(e); 109 | } 110 | } 111 | 112 | public static void append(@NotNull File file, @NotNull String content) throws IOException { 113 | FileUtil.writeToFile(file, content.getBytes(), true); 114 | } 115 | 116 | public static void append(@NotNull String fileName, @NotNull String content) throws IOException { 117 | append(child(fileName), content); 118 | } 119 | 120 | @NotNull 121 | protected static String run(@NotNull File workingDir, @NotNull List params, boolean ignoreNonZeroExitCode) 122 | throws ExecutionException 123 | { 124 | final ProcessBuilder builder = new ProcessBuilder().command(params); 125 | builder.directory(workingDir); 126 | builder.redirectErrorStream(true); 127 | Process clientProcess; 128 | try { 129 | clientProcess = builder.start(); 130 | } catch (IOException e) { 131 | throw new RuntimeException(e); 132 | } 133 | 134 | String commandLine = StringUtil.join(params, " "); 135 | CapturingProcessHandler handler = new CapturingProcessHandler(clientProcess, CharsetToolkit.getDefaultSystemCharset(), commandLine); 136 | ProcessOutput result = handler.runProcess(30 * 1000); 137 | if (result.isTimeout()) { 138 | throw new RuntimeException("Timeout waiting for the command execution. Command: " + commandLine); 139 | } 140 | 141 | String stdout = result.getStdout().trim(); 142 | if (result.getExitCode() != 0) { 143 | if (ignoreNonZeroExitCode) { 144 | debug("{" + result.getExitCode() + "}"); 145 | } 146 | debug(stdout); 147 | if (!ignoreNonZeroExitCode) { 148 | throw new ExecutionException(result.getExitCode(), stdout); 149 | } 150 | } else { 151 | debug(stdout); 152 | } 153 | return stdout; 154 | } 155 | 156 | @NotNull 157 | public static List splitCommandInParameters(@NotNull String command) { 158 | List split = new ArrayList<>(); 159 | 160 | boolean insideParam = false; 161 | StringBuilder currentParam = new StringBuilder(); 162 | for (char c : command.toCharArray()) { 163 | boolean flush = false; 164 | if (insideParam) { 165 | if (c == '\'') { 166 | insideParam = false; 167 | flush = true; 168 | } else { 169 | currentParam.append(c); 170 | } 171 | } else if (c == '\'') { 172 | insideParam = true; 173 | } else if (c == ' ') { 174 | flush = true; 175 | } else { 176 | currentParam.append(c); 177 | } 178 | 179 | if (flush) { 180 | if (!StringUtil.isEmptyOrSpaces(currentParam.toString())) { 181 | split.add(currentParam.toString()); 182 | } 183 | currentParam = new StringBuilder(); 184 | } 185 | } 186 | 187 | // last flush 188 | if (!StringUtil.isEmptyOrSpaces(currentParam.toString())) { 189 | split.add(currentParam.toString()); 190 | } 191 | return split; 192 | } 193 | 194 | @NotNull 195 | private static String shortenPath(@NotNull String path) { 196 | String[] split = path.split("/"); 197 | if (split.length > 3) { 198 | // split[0] is empty, because the path starts from / 199 | return String.format("/%s/.../%s/%s", split[1], split[split.length - 2], split[split.length - 1]); 200 | } 201 | return path; 202 | } 203 | 204 | @NotNull 205 | protected static File child(@NotNull String fileName) { 206 | assert ourCurrentDir != null : "Current dir hasn't been initialized yet. Call cd at least once before any other command."; 207 | return new File(ourCurrentDir, fileName); 208 | } 209 | 210 | @NotNull 211 | protected static File ourCurrentDir() { 212 | assert ourCurrentDir != null : "Current dir hasn't been initialized yet. Call cd at least once before any other command."; 213 | return new File(ourCurrentDir); 214 | } 215 | 216 | private static final int MAX_RETRIES = 3; 217 | private static boolean myVersionPrinted; 218 | 219 | //using inner class to avoid extra work during class loading of unrelated tests 220 | public static class PathHolder { 221 | private static String GIT_EXECUTABLE = null; 222 | public static String getGitExecutable() { 223 | if (GIT_EXECUTABLE != null) { 224 | return GIT_EXECUTABLE; 225 | } 226 | if (System.getProperty("os.name").toLowerCase().contains("windows")) { 227 | GIT_EXECUTABLE = "git.exe"; 228 | } else { 229 | GIT_EXECUTABLE = "git"; 230 | } 231 | return GIT_EXECUTABLE; 232 | } 233 | } 234 | 235 | public static String git(String command) { 236 | return git(command, false); 237 | } 238 | 239 | public static String git(String command, boolean ignoreNonZeroExitCode) { 240 | printVersionTheFirstTime(); 241 | return doCallGit(command, ignoreNonZeroExitCode); 242 | } 243 | 244 | @NotNull 245 | private static String doCallGit(String command, boolean ignoreNonZeroExitCode) { 246 | List split = splitCommandInParameters(command); 247 | split.add(0, PathHolder.getGitExecutable()); 248 | File workingDir = ourCurrentDir(); 249 | debug("[" + workingDir.getName() + "] # git " + command); 250 | for (int attempt = 0; attempt < MAX_RETRIES; attempt++) { 251 | String stdout; 252 | try { 253 | stdout = run(workingDir, split, ignoreNonZeroExitCode); 254 | if (!isIndexLockFileError(stdout)) { 255 | return stdout; 256 | } 257 | } catch (ExecutionException e) { 258 | stdout = e.getOutput(); 259 | if (!isIndexLockFileError(stdout)) { 260 | throw e; 261 | } 262 | } 263 | LOG.info("Index lock file error, attempt #" + attempt + ": " + stdout); 264 | } 265 | throw new RuntimeException("fatal error during execution of Git command: $command"); 266 | } 267 | 268 | private static boolean isIndexLockFileError(@NotNull String stdout) { 269 | return stdout.contains("fatal") && stdout.contains("Unable to create") && stdout.contains(".git/index.lock"); 270 | } 271 | 272 | public static void add() { 273 | add("."); 274 | } 275 | 276 | public static void add(@NotNull String path) { 277 | git("add --verbose " + path); 278 | } 279 | 280 | @NotNull 281 | public static String addCommit(@NotNull String message) { 282 | add(); 283 | return commit(message); 284 | } 285 | 286 | public static void checkout(@NotNull String... params) { 287 | git("checkout " + StringUtil.join(params, " ")); 288 | } 289 | 290 | public static String commit(@NotNull String message) { 291 | git("commit -m '" + message + "'"); 292 | return last(); 293 | } 294 | 295 | @NotNull 296 | public static String tac(@NotNull String file, @NotNull String content) { 297 | touch(file, content); 298 | return addCommit("touched " + file); 299 | } 300 | 301 | @NotNull 302 | public static String tac(@NotNull String file) { 303 | touch(file, "content" + Math.random()); 304 | return addCommit("touched " + file); 305 | } 306 | 307 | @NotNull 308 | public static String push() { 309 | return git("push"); 310 | } 311 | 312 | @NotNull 313 | public static String push(String remoteName, String branch) { 314 | return git("push -u " + remoteName + " " + branch); 315 | } 316 | 317 | @NotNull 318 | public static String last() { 319 | return git("log -1 --pretty=%H"); 320 | } 321 | 322 | private static void printVersionTheFirstTime() { 323 | if (!myVersionPrinted) { 324 | myVersionPrinted = true; 325 | doCallGit("version", false); 326 | } 327 | } 328 | } 329 | -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/GitTestUtil.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender; 2 | 3 | import com.intellij.notification.Notification; 4 | import com.intellij.notification.NotificationType; 5 | import com.intellij.openapi.project.Project; 6 | import com.intellij.openapi.vcs.ProjectLevelVcsManager; 7 | import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl; 8 | import com.intellij.openapi.vfs.LocalFileSystem; 9 | import com.intellij.openapi.vfs.VirtualFile; 10 | import git4idea.GitUtil; 11 | import git4idea.GitVcs; 12 | import git4idea.repo.GitRepository; 13 | import git4idea.repo.GitRepositoryManager; 14 | import org.jetbrains.annotations.NotNull; 15 | 16 | import java.io.File; 17 | import java.io.IOException; 18 | import java.util.concurrent.atomic.AtomicReference; 19 | 20 | import static gr.jchrist.gitextender.GitExecutor.addCommit; 21 | import static gr.jchrist.gitextender.GitExecutor.append; 22 | import static gr.jchrist.gitextender.GitExecutor.cd; 23 | import static gr.jchrist.gitextender.GitExecutor.checkout; 24 | import static gr.jchrist.gitextender.GitExecutor.git; 25 | import static gr.jchrist.gitextender.GitExecutor.last; 26 | import static gr.jchrist.gitextender.GitExecutor.push; 27 | import static gr.jchrist.gitextender.GitExecutor.tac; 28 | import static org.assertj.core.api.Assertions.assertThat; 29 | 30 | public class GitTestUtil { 31 | public static void cloneRepo(@NotNull String source, @NotNull String destination, boolean bare) { 32 | cd(source); 33 | git("clone "+(bare ? "--bare " : "") + "-- . " + destination); 34 | } 35 | 36 | @NotNull 37 | public static GitRepository createRemoteRepositoryAndCloneToLocal( 38 | @NotNull Project project, @NotNull String root, @NotNull String remotePath, @NotNull String remoteAccessPath) { 39 | cd(remotePath); 40 | git("init --bare --initial-branch=" + ProjectUpdateITest.MAIN_BRANCH_NAME); 41 | setupGitConfig(); 42 | 43 | cloneRepo(remotePath, remoteAccessPath, false); 44 | cd(remoteAccessPath); 45 | setupGitConfig(); 46 | 47 | tac("initial_file.txt"); 48 | push(); 49 | 50 | checkout("-b", "develop"); 51 | push("origin", "develop"); 52 | 53 | cloneRepo(remotePath, root, false); 54 | 55 | VirtualFile gitDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(root, GitUtil.DOT_GIT)); 56 | assertThat(gitDir).isNotNull(); 57 | GitRepository repo = registerRepo(project, root); 58 | 59 | cd(root); 60 | setupGitConfig(); 61 | checkout("develop"); 62 | checkout("main"); 63 | 64 | return repo; 65 | } 66 | 67 | @NotNull 68 | public static GitRepository registerRepo(Project project, String root) { 69 | ProjectLevelVcsManagerImpl vcsManager = (ProjectLevelVcsManagerImpl)ProjectLevelVcsManager.getInstance(project); 70 | vcsManager.setDirectoryMapping(root, GitVcs.NAME); 71 | VirtualFile file = LocalFileSystem.getInstance().findFileByIoFile(new File(root)); 72 | assertThat(vcsManager.getAllVcsRoots().length).isNotZero(); 73 | GitRepositoryManager grm = GitUtil.getRepositoryManager(project); 74 | 75 | AtomicReference ref = new AtomicReference<>(); 76 | AbstractIT.runOutOfEdt(() -> { 77 | var repository = grm.getRepositoryForRoot(file); 78 | ref.set(repository); 79 | }); 80 | var repository = ref.get(); 81 | assertThat(repository).as("Couldn't find repository for root " + root).isNotNull(); 82 | return repository; 83 | } 84 | 85 | public static void setupGitConfig() { 86 | git("config user.name 'JChrist'"); 87 | git("config user.email 'jchrist@jchrist.gr'"); 88 | git("config push.default simple"); 89 | } 90 | 91 | @NotNull 92 | public static String makeCommit(String file) throws IOException { 93 | append(file, "some content"); 94 | addCommit("some message"); 95 | return last(); 96 | } 97 | 98 | public static Notification assertNotification(@NotNull NotificationType type, 99 | @NotNull String title, 100 | @NotNull String content, 101 | @NotNull Notification actual) { 102 | assertThat(actual.getType()).as("Incorrect notification type: " + tos(actual)).isEqualTo(type); 103 | assertThat(actual.getTitle()).as("Incorrect notification title: " + tos(actual)).isEqualTo(title); 104 | assertThat(cleanupForAssertion(actual.getContent())) 105 | .as("Incorrect notification content: " + tos(actual)) 106 | .isEqualTo(cleanupForAssertion(content)); 107 | return actual; 108 | } 109 | 110 | @NotNull 111 | public static String cleanupForAssertion(@NotNull String content) { 112 | return content.replace("
    ", "\n").replace("\n", " ").replaceAll("[ ]{2,}", " ").replaceAll(" href='[^']*'", "").trim(); 113 | } 114 | 115 | @NotNull 116 | private static String tos(@NotNull Notification notification) { 117 | return notification.getTitle() + "|" + notification.getContent(); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/ProjectUpdateITest.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender; 2 | 3 | import com.intellij.notification.Notification; 4 | import com.intellij.notification.NotificationType; 5 | import com.intellij.notification.Notifications; 6 | import com.intellij.openapi.actionSystem.AnActionEvent; 7 | import com.intellij.openapi.application.Application; 8 | import com.intellij.openapi.application.ApplicationManager; 9 | import com.intellij.openapi.command.WriteCommandAction; 10 | import com.intellij.openapi.diagnostic.Logger; 11 | import com.intellij.openapi.util.Computable; 12 | import com.intellij.testFramework.TestDataProvider; 13 | import com.intellij.util.messages.MessageBusConnection; 14 | import git4idea.branch.GitBranchesCollection; 15 | import git4idea.repo.GitRepository; 16 | import gr.jchrist.gitextender.configuration.GitExtenderSettings; 17 | import gr.jchrist.gitextender.configuration.GitExtenderSettingsHandler; 18 | import org.jetbrains.annotations.Nullable; 19 | import org.junit.After; 20 | import org.junit.Before; 21 | import org.junit.Test; 22 | import org.junit.runner.RunWith; 23 | import org.junit.runners.JUnit4; 24 | 25 | import java.nio.file.Files; 26 | import java.nio.file.LinkOption; 27 | import java.nio.file.Paths; 28 | import java.util.ArrayList; 29 | import java.util.Arrays; 30 | import java.util.Collections; 31 | import java.util.List; 32 | import java.util.concurrent.TimeUnit; 33 | 34 | import static gr.jchrist.gitextender.GitExecutor.cd; 35 | import static gr.jchrist.gitextender.GitExecutor.checkout; 36 | import static gr.jchrist.gitextender.GitExecutor.git; 37 | import static gr.jchrist.gitextender.GitExecutor.push; 38 | import static gr.jchrist.gitextender.GitExecutor.tac; 39 | import static org.assertj.core.api.Assertions.assertThat; 40 | 41 | @RunWith(JUnit4.class) 42 | public class ProjectUpdateITest extends AbstractIT { 43 | public static final String MAIN_BRANCH_NAME = "main"; 44 | private static final Logger logger = Logger.getInstance(ProjectUpdateITest.class); 45 | 46 | private static final String remoteName = "testRemote"; 47 | private static final String remoteAccessName = "testRemoteAccess"; 48 | private String remoteRepoPath; 49 | private String remoteRepoAccessPath; 50 | private GitRepository repository; 51 | 52 | private MessageBusConnection mbc; 53 | private final List capturedInfos = new ArrayList<>(); 54 | private final List capturedErrors = new ArrayList<>(); 55 | 56 | private AnActionEvent event; 57 | private GitExtenderUpdateAll updater; 58 | private GitExtenderSettings settings; 59 | private GitExtenderSettingsHandler appSettingsHandler; 60 | 61 | @Before 62 | public final void before() throws Exception { 63 | remoteRepoPath = Files.createTempDirectory(remoteName).toRealPath(LinkOption.NOFOLLOW_LINKS).toString(); 64 | remoteRepoAccessPath = Files.createTempDirectory(remoteAccessName).toRealPath(LinkOption.NOFOLLOW_LINKS).toString(); 65 | 66 | logger.info("creating test remote in directory: " + remoteRepoPath+" with access (non-bare) in:"+remoteRepoAccessPath); 67 | 68 | repository = GitTestUtil.createRemoteRepositoryAndCloneToLocal(super.getProject(), super.getProjectPath(), remoteRepoPath, remoteRepoAccessPath); 69 | final var grm = super.getGitRepositoryManager(); 70 | runOutOfEdt(() -> { 71 | repository.update(); 72 | grm.updateAllRepositories(); 73 | }); 74 | 75 | logger.info("Starting up with repos: " + grm.getRepositories() + 76 | " Branch track infos: "+ grm.getRepositories().get(0).getBranchTrackInfos()); 77 | 78 | updater = new GitExtenderUpdateAll(); 79 | final var tdp = new TestDataProvider(super.getProject()); 80 | event = AnActionEvent.createFromAnAction(updater, null, "somewhere", tdp::getData); 81 | 82 | Application app = ApplicationManager.getApplication(); 83 | logger.info("initialized app: "+app); 84 | mbc = app.getMessageBus().connect(); 85 | mbc.setDefaultHandler( 86 | (event1, params) -> { 87 | assertThat(params).hasSize(1); 88 | assertThat(params[0]).isInstanceOf(Notification.class); 89 | Notification n = (Notification) params[0]; 90 | logger.info("captured notification: "+n.getTitle()+" "+n.getContent()); 91 | if(n.getType().equals(NotificationType.ERROR)) { 92 | capturedErrors.add(n); 93 | } else { 94 | capturedInfos.add(n); 95 | } 96 | }); 97 | mbc.subscribe(Notifications.TOPIC); 98 | logger.info("created message bus connection and subscribed to notifications:"+mbc); 99 | appSettingsHandler = new GitExtenderSettingsHandler(); 100 | settings = new GitExtenderSettings(); 101 | appSettingsHandler.saveSettings(settings); 102 | } 103 | 104 | @After 105 | public final void after() throws Exception { 106 | if(mbc != null) { 107 | mbc.disconnect(); 108 | } 109 | try { 110 | repository.dispose(); 111 | } catch (Exception e) { 112 | logger.warn("error disposing git repo"); 113 | } 114 | } 115 | 116 | @Test 117 | public void updateNoChanges() throws Exception { 118 | runUpdate(); 119 | assertNoErrors(); 120 | assertOnMainBranch(); 121 | } 122 | 123 | @Test 124 | public void updateRemoteOnlyChanges() throws Exception { 125 | final String newFileName = "test_new_file.txt"; 126 | cd(remoteRepoAccessPath); 127 | checkout("develop"); 128 | tac(newFileName); 129 | push(); 130 | 131 | cd(super.getProjectPath()); 132 | checkout(MAIN_BRANCH_NAME); 133 | 134 | runUpdate(); 135 | 136 | assertNoErrors(); 137 | 138 | assertOnMainBranch(); 139 | 140 | checkout("develop"); 141 | assertThat(Paths.get(super.getProjectPath(), newFileName)).exists(); 142 | } 143 | 144 | @Test 145 | public void updateLocalRemoteDivergedOnlyFFNotUpdated() throws Exception { 146 | final String remoteFileName = "test_new_file.txt"; 147 | final String localFileName = "local_test_new_file.txt"; 148 | cd(remoteRepoAccessPath); 149 | checkout("develop"); 150 | tac(remoteFileName); 151 | push(); 152 | 153 | cd(super.getProjectPath()); 154 | checkout("develop"); 155 | tac(localFileName); 156 | //not pushing this since it would get rejected (remote is 1 commit ahead) 157 | checkout(MAIN_BRANCH_NAME); 158 | 159 | final var grm = getGitRepositoryManager(); 160 | updateRepos(repository); 161 | 162 | runUpdate(); 163 | 164 | assertError(Collections.singletonList("fast-forward only"), 165 | Arrays.asList("Local branch: develop", "Remote branch: origin/develop")); 166 | 167 | assertOnMainBranch(); 168 | 169 | checkout("develop"); 170 | assertThat(Paths.get(super.getProjectPath(), localFileName)).exists(); 171 | assertThat(Paths.get(super.getProjectPath(), remoteFileName)).doesNotExist(); 172 | } 173 | 174 | @Test 175 | public void updateLocalRemoteDivergedSimpleMergeUpdated() throws Exception { 176 | final String remoteFileName = "test_new_file.txt"; 177 | final String localFileName = "local_test_new_file.txt"; 178 | cd(remoteRepoAccessPath); 179 | checkout("develop"); 180 | tac(remoteFileName); 181 | push(); 182 | 183 | cd(super.getProjectPath()); 184 | checkout("develop"); 185 | tac(localFileName); 186 | //not pushing this since it would get rejected (remote is 1 commit ahead) 187 | checkout(MAIN_BRANCH_NAME); 188 | 189 | updateRepos(repository); 190 | 191 | //enable merge/abort 192 | settings.setAttemptMergeAbort(true); 193 | appSettingsHandler.saveSettings(settings); 194 | 195 | runUpdate(); 196 | 197 | assertNoErrors(); 198 | //assertError(Collections.singletonList("fast-forward only"), 199 | // Arrays.asList("Local branch: develop", "Remote branch: origin/develop")); 200 | 201 | assertOnMainBranch(); 202 | 203 | checkout("develop"); 204 | assertThat(Paths.get(super.getProjectPath(), localFileName)).exists(); 205 | assertThat(Paths.get(super.getProjectPath(), remoteFileName)).exists(); 206 | } 207 | 208 | @Test 209 | public void updateLocalRemoteConflictOnFileAborted() throws Exception { 210 | //add a new file to the remote on develop 211 | final String fileName = "test_new_file.txt"; 212 | final String remoteContent = "remote content"; 213 | final String localContent = "local content"; 214 | cd(remoteRepoAccessPath); 215 | checkout("develop"); 216 | tac(fileName, remoteContent); 217 | push(); 218 | 219 | //and add the same file on our local develop (with different content from the remote) 220 | cd(super.getProjectPath()); 221 | checkout("develop"); 222 | tac(fileName, localContent); 223 | //not pushing this since it would get rejected (remote is 1 commit ahead) 224 | checkout(MAIN_BRANCH_NAME); 225 | 226 | updateRepos(repository); 227 | 228 | //enable merge/abort 229 | settings.setAttemptMergeAbort(true); 230 | appSettingsHandler.saveSettings(settings); 231 | 232 | runUpdate(); 233 | 234 | assertError(Collections.singletonList("failed"), Collections.singletonList("fast-forward"), 235 | Arrays.asList("Local branch: develop", "Remote branch: origin/develop", "Merge was aborted"), 236 | Collections.singletonList("fast-forward")); 237 | 238 | assertOnMainBranch(); 239 | 240 | checkout("develop"); 241 | assertThat(Paths.get(super.getProjectPath(), fileName)) 242 | .as("expected to abort merge, so local file should be as it was before merging") 243 | .exists().hasBinaryContent(localContent.getBytes()); 244 | } 245 | 246 | @Test 247 | public void updateWithPrunedRemotesLocalDeleted() { 248 | final String remoteFileName = "test_new_file.txt"; 249 | cd(remoteRepoAccessPath); 250 | checkout("develop"); 251 | tac(remoteFileName); 252 | push(); 253 | 254 | cd(super.getProjectPath()); 255 | checkout("develop"); 256 | git("pull"); 257 | 258 | updateRepos(); 259 | 260 | //now delete branch on remote 261 | cd(remoteRepoAccessPath); 262 | checkout(MAIN_BRANCH_NAME); 263 | git("branch -D develop"); 264 | //delete remote branch 265 | git("push origin --delete develop"); 266 | 267 | //and get back to our local 268 | cd(super.getProjectPath()); 269 | 270 | //enable merge/abort 271 | settings.setAttemptMergeAbort(true); 272 | settings.setPruneLocals(true); 273 | appSettingsHandler.saveSettings(settings); 274 | 275 | runUpdate(); 276 | 277 | assertNoErrors(); 278 | 279 | //this means that the pruned remote branch led us to delete the local one and switch to main 280 | assertOnMainBranch(); 281 | assertThat(super.getGitRepositoryManager().getRepositories()).hasSize(1); 282 | GitBranchesCollection gbl = super.getGitRepositoryManager().getRepositories().get(0).getBranches(); 283 | assertThat(gbl.findLocalBranch(MAIN_BRANCH_NAME)).as("no main branch found locally").isNotNull(); 284 | assertThat(gbl.findLocalBranch("develop")).as("develop branch found, while expected to have been auto-deleted").isNull(); 285 | } 286 | 287 | private void runUpdate() { 288 | // Boolean result = WriteCommandAction.runWriteCommandAction(super.getProject(), 289 | // (Computable) ()-> {updater.actionPerformed(event); return true;}); 290 | updater.actionPerformed(event); 291 | waitForUpdateToFinish(); 292 | logger.info("update action performed"); 293 | } 294 | 295 | private void assertNoErrors() { 296 | assertNotifications(0); 297 | } 298 | 299 | private void assertError(List titleParts, List contentParts) { 300 | assertError(titleParts, Collections.emptyList(), contentParts, Collections.emptyList()); 301 | } 302 | 303 | private void assertError(List titleParts, List notContainedTitleParts, 304 | List contentParts, List notContainedContentParts) { 305 | Notification error = assertNotifications(1); 306 | assertThat(error).isNotNull(); 307 | 308 | assertThat(error.getTitle()) 309 | .as("unexpected error notification title") 310 | .contains(titleParts) 311 | .satisfies(err -> notContainedTitleParts.forEach(part -> assertThat(err).doesNotContain(part))); 312 | 313 | assertThat(error.getContent()).as("unexpected error notification content") 314 | .contains(contentParts) 315 | .satisfies(err -> notContainedContentParts.forEach(part -> assertThat(err).doesNotContain(part))); 316 | } 317 | 318 | @Nullable 319 | private Notification assertNotifications(int expectedErrors) { 320 | assertThat(capturedInfos) 321 | .as("expected to capture one informational notification, that update finished") 322 | .hasSize(1); 323 | 324 | assertThat(capturedErrors) 325 | .as("invalid number of error notifications captured, we expected to find: "+expectedErrors) 326 | .hasSize(expectedErrors); 327 | 328 | if(expectedErrors > 0) { 329 | return capturedErrors.get(0); 330 | } 331 | 332 | return null; 333 | } 334 | 335 | private void assertOnMainBranch() { 336 | assertThat(repository.getCurrentBranchName()) 337 | .as("we didn't get back to our original branch after updating") 338 | .isEqualTo("main") 339 | .isEqualTo(getCurrentBranchFromGit()); 340 | } 341 | 342 | private String getCurrentBranchFromGit() { 343 | String result = git("status"); 344 | // expected result will be similar to: 345 | // On branch main 346 | // Your branch is up-to-date with 'origin/main'. 347 | // nothing to commit, working tree clean 348 | result = result.replace("\n", "
    "); 349 | String[] firstLineWords = result.split("
    ")[0].split(" "); 350 | String branch = firstLineWords[firstLineWords.length-1]; 351 | logger.info("current branch is:["+branch+"] as reported from (formatted) git status: "+result); 352 | return branch; 353 | } 354 | 355 | private void waitForUpdateToFinish() { 356 | if (updater != null && updater.updateCountDown != null) { 357 | try { 358 | updater.updateCountDown.await(10, TimeUnit.SECONDS); 359 | int retries = 0; 360 | while (updater.executingFlag.get() && retries < 100) { 361 | TimeUnit.MILLISECONDS.sleep(100); 362 | retries++; 363 | } 364 | } catch (Exception ex) { 365 | logger.warn("error waiting for update to finish! it took more than 1m!", ex); 366 | fail("error waiting for update to finish! it took more than 1m!"); 367 | } 368 | } 369 | } 370 | } 371 | -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/TestingUtil.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender; 2 | 3 | import git4idea.commands.GitCommandResult; 4 | 5 | import java.util.Collections; 6 | 7 | public abstract class TestingUtil { 8 | public static final GitCommandResult error = 9 | new GitCommandResult(true, 1, 10 | Collections.singletonList("test error output"), 11 | Collections.singletonList("error")); 12 | public static final GitCommandResult success = 13 | new GitCommandResult(false, 0, 14 | Collections.emptyList(), 15 | Collections.singletonList("success")); 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/configuration/GitExtenderSettingsTest.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.configuration; 2 | 3 | import com.intellij.testFramework.fixtures.BasePlatformTestCase; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.junit.runners.JUnit4; 7 | 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | 10 | /** 11 | * @author jchrist 12 | * @since 2017/01/14 13 | */ 14 | @RunWith(JUnit4.class) 15 | public class GitExtenderSettingsTest extends BasePlatformTestCase { 16 | 17 | @Test 18 | public void testGetAttemptMergeAbort() throws Exception { 19 | GitExtenderSettings ges = new GitExtenderSettings(); 20 | assertThat(ges.getAttemptMergeAbort()).as("get failure").isFalse(); 21 | ges.setAttemptMergeAbort(true); 22 | assertThat(ges.getAttemptMergeAbort()).as("get failure").isTrue(); 23 | } 24 | 25 | @Test 26 | public void testEquals() throws Exception { 27 | GitExtenderSettings settings = new GitExtenderSettings(); 28 | GitExtenderSettings settings2 = new GitExtenderSettings(); 29 | assertThat(settings.equals(settings2)).isTrue(); 30 | assertThat(settings.equals(new Object())).isFalse(); 31 | assertThat(settings.equals(new GitExtenderSettings())).isTrue(); 32 | assertThat(settings.equals(new GitExtenderSettings(true, true))).isFalse(); 33 | } 34 | 35 | @Test 36 | public void testHashcode() throws Exception { 37 | assertThat(new GitExtenderSettings().hashCode()).isZero(); 38 | assertThat(new GitExtenderSettings(true, false).hashCode()).isOne(); 39 | assertThat(new GitExtenderSettings(false, true).hashCode()).isEqualTo(10); 40 | assertThat(new GitExtenderSettings(true, true).hashCode()).isEqualTo(11); 41 | } 42 | 43 | @Test 44 | public void testToString() throws Exception { 45 | assertThat(new GitExtenderSettings().toString()).contains("attemptMergeAbort=false").contains("pruneLocals=false"); 46 | assertThat(new GitExtenderSettings(true, false).toString()).contains("attemptMergeAbort=true").contains("pruneLocals=false"); 47 | assertThat(new GitExtenderSettings(false, true).toString()).contains("attemptMergeAbort=false").contains("pruneLocals=true"); 48 | assertThat(new GitExtenderSettings(true, true).toString()).contains("attemptMergeAbort=true").contains("pruneLocals=true"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/configuration/ProjectSettingsHandlerTest.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.configuration; 2 | 3 | import com.intellij.testFramework.fixtures.BasePlatformTestCase; 4 | import org.junit.After; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.junit.runners.JUnit4; 9 | 10 | import java.util.Arrays; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | 14 | @RunWith(JUnit4.class) 15 | public class ProjectSettingsHandlerTest extends BasePlatformTestCase { 16 | ProjectSettingsHandler handler; 17 | 18 | @Before 19 | public final void testSetUp() throws Exception { 20 | handler = new ProjectSettingsHandler(super.getProject()); 21 | handler.clearSelectedModules(); 22 | } 23 | 24 | @After 25 | public final void testTearDown() throws Exception { 26 | handler.clearSelectedModules(); 27 | } 28 | 29 | @Test 30 | public void loadSelectedModules() throws Exception { 31 | assertThat(handler.loadSelectedModules()).as("expected no modules selected initially").isEmpty(); 32 | final String module1 = "module1"; 33 | handler.addSelectedModule(module1); 34 | assertThat(handler.loadSelectedModules()).as("expected single module present") 35 | .containsExactly(module1); 36 | 37 | final String module2 = "module2"; 38 | handler.addSelectedModule(module2); 39 | assertThat(handler.loadSelectedModules()).as("expected 2 modules present") 40 | .containsExactly(module1, module2); 41 | 42 | handler.addSelectedModule(module1); 43 | handler.addSelectedModule(module2); 44 | assertThat(handler.loadSelectedModules()).as("expected 2 modules present") 45 | .containsExactly(module1, module2); 46 | 47 | handler.removeSelectedModule("invalid module"); 48 | assertThat(handler.loadSelectedModules()).as("expected single module present") 49 | .containsExactly(module1, module2); 50 | 51 | handler.removeSelectedModule(module1); 52 | assertThat(handler.loadSelectedModules()).as("expected single module present") 53 | .containsExactly(module2); 54 | 55 | handler.clearSelectedModules(); 56 | assertThat(handler.loadSelectedModules()).as("expected no modules selected initially").isEmpty(); 57 | 58 | handler.addSelectedModule(module1); 59 | handler.removeSelectedModule(module1); 60 | assertThat(handler.loadSelectedModules()).as("expected no modules selected initially").isEmpty(); 61 | } 62 | 63 | @Test 64 | public void setSelectedModules() throws Exception { 65 | handler.setSelectedModules(Arrays.asList("module1", "module2")); 66 | assertThat(handler.loadSelectedModules()).containsExactly("module1", "module2"); 67 | } 68 | 69 | @Test 70 | public void testGetProject() throws Exception { 71 | assertThat(handler.getProject()).isEqualTo(super.getProject()); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/configuration/SettingsDialogTest.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.configuration; 2 | 3 | import com.intellij.testFramework.fixtures.BasePlatformTestCase; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.junit.runners.JUnit4; 7 | 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | 10 | /** 11 | * @author jchrist 12 | * @since 2017/01/14 13 | */ 14 | @RunWith(JUnit4.class) 15 | public class SettingsDialogTest extends BasePlatformTestCase { 16 | 17 | @Test 18 | public void testInit() throws Throwable { 19 | super.runTestRunnable(() -> { 20 | SettingsDialog sd = new SettingsDialog(super.getProject()); 21 | assertThat(sd).isNotNull(); 22 | assertThat(sd.getSettingsView()).isNotNull(); 23 | assertThat(sd.getSettingsView().getMainPanel()).isNotNull(); 24 | }); 25 | } 26 | 27 | @Test 28 | public void testValidation() throws Throwable { 29 | super.runTestRunnable(() -> { 30 | SettingsDialog sd = new SettingsDialog(super.getProject()); 31 | assertThat(sd.doValidate()).isNull(); 32 | }); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/configuration/SettingsViewTest.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.configuration; 2 | 3 | import com.intellij.testFramework.LightPlatform4TestCase; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | 9 | /** 10 | * @author jchrist 11 | * @since 2017/01/15 12 | */ 13 | public class SettingsViewTest extends LightPlatform4TestCase { 14 | private SettingsView settingsView; 15 | 16 | @Before 17 | public void before() throws Exception { 18 | settingsView = new SettingsView(); 19 | if (settingsView.isModified()) { 20 | settingsView.apply(); 21 | } 22 | 23 | assertThat(settingsView.isModified()).isFalse(); 24 | } 25 | 26 | @Test 27 | public void testGetId() throws Exception { 28 | assertThat(settingsView.getId()).isEqualTo(SettingsView.DIALOG_TITLE); 29 | } 30 | 31 | @Test 32 | public void testGetDisplayName() throws Exception { 33 | assertThat(settingsView.getDisplayName()).isEqualTo(SettingsView.DIALOG_TITLE); 34 | } 35 | 36 | @Test 37 | public void testGetHelpTopic() throws Exception { 38 | assertThat(settingsView.getHelpTopic()).isNull(); 39 | } 40 | 41 | @Test 42 | public void testCreateComponent() throws Exception { 43 | assertThat(settingsView.createComponent()).isNotNull(); 44 | } 45 | 46 | @Test 47 | public void testIsModifiedApply() throws Exception { 48 | assertThat(settingsView.isModified()).isFalse(); 49 | settingsView.getAttemptMergeAbort().setSelected(true); 50 | assertThat(settingsView.isModified()).isTrue(); 51 | settingsView.apply(); 52 | assertThat(settingsView.isModified()).isFalse(); 53 | assertThat(settingsView.getAttemptMergeAbort().isSelected()).isTrue(); 54 | } 55 | 56 | @Test 57 | public void testPruneLocalsIsModifiedApply() throws Exception { 58 | assertThat(settingsView.getPruneLocals().isSelected()).isFalse(); 59 | assertThat(settingsView.isModified()).isFalse(); 60 | settingsView.getPruneLocals().setSelected(true); 61 | assertThat(settingsView.isModified()).isTrue(); 62 | settingsView.apply(); 63 | assertThat(settingsView.isModified()).isFalse(); 64 | assertThat(settingsView.getPruneLocals().isSelected()).isTrue(); 65 | } 66 | 67 | @Test 68 | public void testDisposeUIResources() throws Exception { 69 | settingsView.disposeUIResources(); 70 | assertThat(settingsView.getMainPanel()).isNull(); 71 | assertThat(settingsView.getAttemptMergeAbort()).isNull(); 72 | assertThat(settingsView.getPruneLocals()).isNull(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/dialog/SelectModuleDialogTest.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.dialog; 2 | 3 | import com.intellij.testFramework.fixtures.BasePlatformTestCase; 4 | import gr.jchrist.gitextender.configuration.ProjectSettingsHandler; 5 | import org.junit.After; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.junit.runners.JUnit4; 10 | 11 | import java.util.ArrayList; 12 | import java.util.Arrays; 13 | import java.util.List; 14 | 15 | import static org.assertj.core.api.Assertions.assertThat; 16 | 17 | @RunWith(JUnit4.class) 18 | public class SelectModuleDialogTest extends BasePlatformTestCase { 19 | private ProjectSettingsHandler projectSettingsHandler; 20 | private List testRepos = new ArrayList<>(Arrays.asList("repo1", "repo2", "repo3")); 21 | private boolean init = false; 22 | private boolean td = false; 23 | 24 | @Before 25 | @Override 26 | public final void setUp() throws Exception { 27 | if (init) return; 28 | init = true; 29 | super.setUp(); 30 | projectSettingsHandler = new ProjectSettingsHandler(super.getProject()); 31 | } 32 | 33 | @After 34 | @Override 35 | public final void tearDown() throws Exception { 36 | if (td) return; 37 | td = true; 38 | super.tearDown(); 39 | } 40 | 41 | @Test 42 | public void init() throws Throwable { 43 | //super.runTestRunnable(() -> { 44 | SelectModuleDialog smd = new SelectModuleDialog(projectSettingsHandler, testRepos); 45 | assertThat(smd).isNotNull(); 46 | //}); 47 | } 48 | 49 | @Test 50 | public void selectAllNone() throws Throwable { 51 | //super.runTestRunnable(() -> { 52 | SelectModuleDialog smd = new SelectModuleDialog(projectSettingsHandler, testRepos); 53 | assertThat(smd).isNotNull(); 54 | smd.selectAllBtn.doClick(); 55 | assertThat(smd.repoChooser.getMarkedElements()).hasSize(testRepos.size()).containsAll(testRepos); 56 | assertThat(projectSettingsHandler.loadSelectedModules()).hasSize(testRepos.size()).containsAll(testRepos); 57 | smd.selectNoneBtn.doClick(); 58 | assertThat(smd.repoChooser.getMarkedElements()).isEmpty(); 59 | assertThat(projectSettingsHandler.loadSelectedModules()).isEmpty(); 60 | //}); 61 | } 62 | 63 | @Test 64 | public void savedSelectedModules() throws Throwable { 65 | projectSettingsHandler.setSelectedModules(Arrays.asList(testRepos.get(0), "invalid module")); 66 | //super.runTestRunnable(() -> { 67 | SelectModuleDialog smd = new SelectModuleDialog(projectSettingsHandler, testRepos); 68 | assertThat(smd).isNotNull(); 69 | assertThat(smd.repoChooser.getMarkedElements()).hasSize(1).contains(testRepos.get(0)); 70 | //}); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/handlers/AfterMergeHandlerTest.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import gr.jchrist.gitextender.BranchUpdateResult; 4 | import org.junit.Test; 5 | 6 | import static gr.jchrist.gitextender.TestingUtil.error; 7 | import static gr.jchrist.gitextender.TestingUtil.success; 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | 10 | public class AfterMergeHandlerTest { 11 | @Test 12 | public void afterSuccessfulMerge() throws Exception { 13 | MergeState mergeState = new MergeState(); 14 | BranchUpdateResult branchUpdateResult = new BranchUpdateResult( 15 | success, success, null, null); 16 | assertThat(AfterMergeHandler.getInstance(branchUpdateResult, mergeState)) 17 | .as("unexpected after merge handler for successful merge result") 18 | .isInstanceOf(AfterSuccessfulMergeHandler.class); 19 | } 20 | 21 | @Test 22 | public void afterFailureMerge() throws Exception { 23 | MergeState mergeState = new MergeState(); 24 | BranchUpdateResult branchUpdateResult = new BranchUpdateResult( 25 | success, error, error, null); 26 | 27 | assertThat(AfterMergeHandler.getInstance(branchUpdateResult, mergeState)) 28 | .as("unexpected after merge handler for successful merge result") 29 | .isInstanceOf(AfterFailedMergeHandler.class); 30 | } 31 | } -------------------------------------------------------------------------------- /src/test/java/gr/jchrist/gitextender/handlers/UpdatedFilesNotifierTest.java: -------------------------------------------------------------------------------- 1 | package gr.jchrist.gitextender.handlers; 2 | 3 | import com.intellij.openapi.vcs.update.UpdatedFiles; 4 | import org.junit.Test; 5 | 6 | import static org.assertj.core.api.Assertions.assertThat; 7 | 8 | public class UpdatedFilesNotifierTest { 9 | @Test 10 | public void prepareNotificationWithUpdateInfo() throws Exception { 11 | UpdatedFiles uf = UpdatedFiles.create(); 12 | uf.getTopLevelGroups().get(0).add("test path", "test repo name", null); 13 | String result = new UpdatedFilesNotifier(uf).prepareNotificationWithUpdateInfo(); 14 | assertThat(result).isNotNull().isNotEmpty(); 15 | } 16 | } --------------------------------------------------------------------------------