├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── lombok.config ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── github │ │ └── goober │ │ └── sonarqube │ │ └── plugin │ │ ├── PullRequestDecoratorPlugin.java │ │ └── decorator │ │ ├── PullRequestDecorator.java │ │ ├── PullRequestProperties.java │ │ ├── bitbucket │ │ ├── BitbucketClient.java │ │ ├── BitbucketProperties.java │ │ ├── BitbucketPropertiesSensor.java │ │ ├── BitbucketPullRequestDecorator.java │ │ ├── BitbucketPullRequestReport.java │ │ └── model │ │ │ ├── Annotation.java │ │ │ ├── CreateAnnotationsRequest.java │ │ │ ├── CreateReportRequest.java │ │ │ ├── DataValue.java │ │ │ ├── ReportData.java │ │ │ └── ServerProperties.java │ │ └── sonarqube │ │ ├── PullRequestReport.java │ │ ├── PullRequestReportCollector.java │ │ ├── QualityCondition.java │ │ ├── SonarQubeClient.java │ │ └── model │ │ ├── Component.java │ │ ├── Issue.java │ │ ├── Measure.java │ │ ├── MeasureResponse.java │ │ ├── Metric.java │ │ ├── MetricsResponse.java │ │ ├── Paging.java │ │ ├── Rating.java │ │ └── SearchIssuesResponse.java └── resources │ └── org │ └── sonar │ └── l10n │ └── pullRequestDecoratorPlugin_en.properties └── test └── java └── com └── github └── goober └── sonarqube └── plugin └── decorator └── bitbucket └── model └── ServerPropertiesTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/java,gradle 3 | # Edit at https://www.gitignore.io/?templates=java,gradle 4 | 5 | ### Java ### 6 | # Compiled class file 7 | *.class 8 | 9 | # Log file 10 | *.log 11 | 12 | # BlueJ files 13 | *.ctxt 14 | 15 | # Mobile Tools for Java (J2ME) 16 | .mtj.tmp/ 17 | 18 | # Package Files # 19 | *.jar 20 | *.war 21 | *.nar 22 | *.ear 23 | *.zip 24 | *.tar.gz 25 | *.rar 26 | 27 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 28 | hs_err_pid* 29 | 30 | ### Gradle ### 31 | .gradle 32 | build/ 33 | 34 | # Ignore Gradle GUI config 35 | gradle-app.setting 36 | 37 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 38 | !gradle-wrapper.jar 39 | 40 | # Cache of project 41 | .gradletasknamecache 42 | 43 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 44 | # gradle/wrapper/gradle-wrapper.properties 45 | 46 | ### Gradle Patch ### 47 | **/build/ 48 | 49 | # End of https://www.gitignore.io/api/java,gradle 50 | 51 | .idea 52 | out/ -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: java 4 | jdk: openjdk11 5 | 6 | install: true 7 | 8 | before_cache: 9 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 10 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 11 | cache: 12 | directories: 13 | - $HOME/.gradle/caches/ 14 | - $HOME/.gradle/wrapper/ 15 | 16 | script: 17 | - ./gradlew -s -Dorg.gradle.daemon=false clean build 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Archived 2 | The functionality has been updated and merged into the original plugin and any 3 | issues you find should be opened against [sonarqube-community-branch-plugin](https://github.com/mc1arke/sonarqube-community-branch-plugin) 4 | 5 | # Sonarqube Pull Request Decorator Plugin 6 | A plugin for [SonarQube](https://sonarqube.org) to allow pull request decorations in the Community Edition. 7 | 8 | **NOTE** This plugin is still a work in progress and should only be used for evaluation at this stage. 9 | There is an [open discussion](https://github.com/mc1arke/sonarqube-community-branch-plugin/issues/27) on whether to add 10 | support for pull request decorations directly in the `sonarqube-community-branch-plugin`. 11 | There is a possibility that the features of this plugin get pulled into that repository, depending on how the 12 | discussion moves forward. 13 | 14 | ## Compatibility 15 | The plugin requires SonarQube Community Edition version 7.8 or higher. 16 | [sonarqube-community-branch-plugin](https://github.com/mc1arke/sonarqube-community-branch-plugin) is also a prerequisite 17 | for this plugin to work properly since it enables branch and pull request analysis with the Community Edition. 18 | 19 | ## Installation 20 | Either build the project or [download a compatible release version of the plugin JAR](https://github.com/goober/sonarqube-pullrequest-decorator-plugin/releases). 21 | Copy the plugin JAR file to the `extensions/plugins/` directory of your SonarQube instance and restart SonarQube. 22 | 23 | ## Features 24 | The plugin aims to support the 25 | [features and parameters specified in the SonarQube documentation](https://docs.sonarqube.org/latest/analysis/pull-request/). 26 | 27 | ### Bitbucket Server 28 | The following properties is required to be set to enable the plugin for Bitbucket Server, 29 | and can be set either in `conf/sonar.properties` or through the user interface under 30 | Administration > General Settings > Pull Requests > **Integration with Bitbucket Server** 31 | 32 | | Property | Description | 33 | | -------------------------------------- | ----------------------------------------------------------------------- | 34 | | `sonar.pullrequest.bitbucket.endpoint` | The server endpoint. e.g `https://bitbucket.company.com` | 35 | | `sonar.pullrequest.bitbucket.token` | [The Personal Access Token](https://confluence.atlassian.com/bitbucketserver/personal-access-tokens-939515499.html) to authenticate with the Bitbucket Server API | 36 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.github.johnrengelman.shadow' version '5.1.0' 3 | id 'java' 4 | } 5 | 6 | group 'com.github.goober.sonarqube.plugin' 7 | 8 | repositories { 9 | mavenCentral() 10 | jcenter() 11 | } 12 | 13 | def sonarqubeVersion = '7.8' 14 | def jacksonVersion = '2.9.9' 15 | 16 | sourceCompatibility = JavaVersion.VERSION_1_8 17 | targetCompatibility = JavaVersion.VERSION_1_8 18 | 19 | dependencies { 20 | compile 'com.squareup.okhttp3:okhttp:4.0.1' 21 | compile "com.fasterxml.jackson.core:jackson-annotations:${jacksonVersion}" 22 | compile "com.fasterxml.jackson.core:jackson-core:${jacksonVersion}" 23 | compile "com.fasterxml.jackson.core:jackson-databind:${jacksonVersion}" 24 | compileOnly "org.sonarsource.sonarqube:sonar-plugin-api:${sonarqubeVersion}" 25 | 26 | compileOnly 'org.projectlombok:lombok:1.18.8' 27 | annotationProcessor 'org.projectlombok:lombok:1.18.8' 28 | 29 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.5.2' 30 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.5.2' 31 | } 32 | 33 | assemble.dependsOn( 34 | shadowJar { 35 | archiveClassifier = null 36 | } 37 | ) 38 | 39 | jar { 40 | manifest { 41 | attributes 'Plugin-Description': 'Decorates pull requests with SonarQube analysis report', 42 | 'SonarLint-Supported': false, 43 | 'Plugin-Homepage': 'https://github.com/goober/sonarqube-pull-request-decorator-plugin', 44 | 'Plugin-License': 'Apache License 2.0', 45 | 'Plugin-Version': "${project.version}", 46 | 'Plugin-Organization': 'Mathias Åhsberg', 47 | 'Sonar-Version': "${sonarqubeVersion}", 48 | 'Plugin-IssueTrackerUrl': 'https://github.com/goober/sonarqube-pull-request-decorator-plugin/issues', 49 | 'Plugin-Key': 'pullRequestDecoratorPlugin', 50 | 'Plugin-Class': 'com.github.goober.sonarqube.plugin.PullRequestDecoratorPlugin', 51 | 'Plugin-Name': 'Pull Request Decorator Plugin' 52 | } 53 | } 54 | 55 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | version=0.0.2-SNAPSHOT 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/goober/sonarqube-pullrequest-decorator-plugin/b8cbfdb0d3f7ba6deff77e1e468c7feec0f489c1/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Aug 06 21:08:18 GMT 2019 2 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-all.zip 3 | distributionBase=GRADLE_USER_HOME 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin, switch paths to Windows format before running java 129 | if $cygwin ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=$((i+1)) 158 | done 159 | case $i in 160 | (0) set -- ;; 161 | (1) set -- "$args0" ;; 162 | (2) set -- "$args0" "$args1" ;; 163 | (3) set -- "$args0" "$args1" "$args2" ;; 164 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=$(save "$@") 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 184 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 185 | cd "$(dirname "$0")" 186 | fi 187 | 188 | exec "$JAVACMD" "$@" 189 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem http://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /lombok.config: -------------------------------------------------------------------------------- 1 | lombok.anyConstructor.addConstructorProperties=true 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'sonarqube-pullrequest-decorator-plugin' 2 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/PullRequestDecoratorPlugin.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 Michael Clarke 3 | * 4 | * This program is free software; you can redistribute it and/or 5 | * modify it under the terms of the GNU Lesser General Public 6 | * License as published by the Free Software Foundation; either 7 | * version 3 of the License, or (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public License 15 | * along with this program; if not, write to the Free Software Foundation, 16 | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 | * 18 | */ 19 | package com.github.goober.sonarqube.plugin; 20 | 21 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.BitbucketClient; 22 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.BitbucketProperties; 23 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.BitbucketPropertiesSensor; 24 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.BitbucketPullRequestDecorator; 25 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.PullRequestReportCollector; 26 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.SonarQubeClient; 27 | import org.sonar.api.Plugin; 28 | import org.sonar.api.SonarQubeSide; 29 | 30 | public class PullRequestDecoratorPlugin implements Plugin { 31 | 32 | @Override 33 | public void define(Context context) { 34 | if (SonarQubeSide.SCANNER == context.getRuntime().getSonarQubeSide()) { 35 | context.addExtension(BitbucketPropertiesSensor.class); 36 | } 37 | if (SonarQubeSide.COMPUTE_ENGINE == context.getRuntime().getSonarQubeSide()) { 38 | context.addExtensions(PullRequestReportCollector.class, SonarQubeClient.class, 39 | BitbucketClient.class, BitbucketPullRequestDecorator.class); 40 | } 41 | 42 | context.addExtensions(BitbucketProperties.definitions()); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/PullRequestDecorator.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator; 2 | 3 | import org.sonar.api.ce.posttask.Branch; 4 | import org.sonar.api.ce.posttask.PostProjectAnalysisTask; 5 | import org.sonar.api.utils.log.Loggers; 6 | 7 | import java.util.Optional; 8 | 9 | public interface PullRequestDecorator extends PostProjectAnalysisTask { 10 | 11 | @Override 12 | default void finished(ProjectAnalysis analysis) { 13 | Optional pullrequest = analysis.getBranch().filter(b -> Branch.Type.PULL_REQUEST.equals(b.getType())); 14 | if (!pullrequest.isPresent()) { 15 | Loggers.get(PullRequestDecorator.class).debug("Analysis of {} is not affecting a pull request, ignoring", analysis.getProject().getKey()); 16 | return; 17 | } 18 | if (isActivated()) { 19 | decorate(analysis); 20 | } else { 21 | Loggers.get(PullRequestDecorator.class).info("{} is deactivated. Please read the documentation on how to setup the required properties to activate it", 22 | getClass().getCanonicalName()); 23 | } 24 | } 25 | 26 | default boolean isActivated() { 27 | return false; 28 | } 29 | 30 | void decorate(ProjectAnalysis analysis); 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/PullRequestProperties.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator; 2 | 3 | public enum PullRequestProperties { 4 | BRANCH("sonar.pullrequest.branch"), 5 | BASE("sonar.pullrequest.base"), 6 | KEY("sonar.pullrequest.key"); 7 | 8 | private String key; 9 | 10 | PullRequestProperties(String key) { 11 | this.key = key; 12 | } 13 | 14 | public String getKey() { 15 | return key; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/BitbucketClient.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 4 | import com.fasterxml.jackson.databind.DeserializationFeature; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.model.CreateAnnotationsRequest; 7 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.model.CreateReportRequest; 8 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.model.ServerProperties; 9 | import okhttp3.MediaType; 10 | import okhttp3.OkHttpClient; 11 | import okhttp3.Request; 12 | import okhttp3.RequestBody; 13 | import okhttp3.Response; 14 | import org.sonar.api.ce.ComputeEngineSide; 15 | import org.sonar.api.config.Configuration; 16 | import org.sonar.api.utils.log.Logger; 17 | import org.sonar.api.utils.log.Loggers; 18 | 19 | import java.io.IOException; 20 | import java.util.Optional; 21 | 22 | import static java.lang.String.format; 23 | 24 | @ComputeEngineSide 25 | public class BitbucketClient { 26 | private static final Logger LOGGER = Loggers.get(BitbucketClient.class); 27 | private static final String REPORT_KEY = "com.github.goober.sonarqube.plugin.decorator"; 28 | private final Configuration configuration; 29 | 30 | private OkHttpClient client; 31 | private ObjectMapper objectMapper; 32 | 33 | public BitbucketClient(Configuration configuration) { 34 | this.configuration = configuration; 35 | } 36 | 37 | boolean isConfigured() { 38 | return configuration.hasKey(BitbucketProperties.ENDPOINT.getKey()) && 39 | configuration.hasKey(BitbucketProperties.TOKEN.getKey()); 40 | } 41 | 42 | ServerProperties getServerProperties() throws IOException { 43 | Request req = new Request.Builder() 44 | .get() 45 | .url(format("%s/rest/api/1.0/application-properties", baseUrl())) 46 | .build(); 47 | try(Response response = getClient().newCall(req).execute()) { 48 | validate(response); 49 | 50 | return getObjectMapper().reader().forType(ServerProperties.class) 51 | .readValue(response.body().string()); 52 | } 53 | } 54 | 55 | void createReport(String project, String repository, String commit, CreateReportRequest request) throws IOException { 56 | String body = getObjectMapper().writeValueAsString(request); 57 | Request req = new Request.Builder() 58 | .put(RequestBody.create(body, MediaType.parse("application/json"))) 59 | .url(format("%s/rest/insights/1.0/projects/%s/repos/%s/commits/%s/reports/%s", baseUrl(), project, repository, commit, REPORT_KEY)) 60 | .build(); 61 | 62 | try (Response response = getClient().newCall(req).execute()) { 63 | validate(response); 64 | } 65 | } 66 | 67 | void createAnnotations(String project, String repository, String commit, CreateAnnotationsRequest request) throws IOException { 68 | if (request.getAnnotations().isEmpty()) { 69 | return; 70 | } 71 | Request req = new Request.Builder() 72 | .post(RequestBody.create(getObjectMapper().writeValueAsString(request), MediaType.parse("application/json"))) 73 | .url(format("%s/rest/insights/1.0/projects/%s/repos/%s/commits/%s/reports/%s/annotations", baseUrl(), project, repository, commit, REPORT_KEY)) 74 | .build(); 75 | try (Response response = getClient().newCall(req).execute()) { 76 | validate(response); 77 | } 78 | } 79 | 80 | void deleteAnnotations(String project, String repository, String commit) throws IOException { 81 | Request req = new Request.Builder() 82 | .delete() 83 | .url(format("%s/rest/insights/1.0/projects/%s/repos/%s/commits/%s/reports/%s/annotations", baseUrl(), project, repository, commit, REPORT_KEY)) 84 | .build(); 85 | try (Response response = getClient().newCall(req).execute()) { 86 | validate(response); 87 | } 88 | } 89 | 90 | private void validate(Response response) throws IOException { 91 | if (!response.isSuccessful()) { 92 | LOGGER.error("{} - {}", response.code(), response.body() == null ? "" : response.body().string()); 93 | throw new IOException(format("Bitbucket responded with an unsuccessful response %d", response.code())); 94 | } 95 | } 96 | 97 | private OkHttpClient getClient() { 98 | client = Optional.ofNullable(client).orElseGet(() -> 99 | new OkHttpClient.Builder() 100 | .authenticator(((route, response) -> 101 | response.request() 102 | .newBuilder() 103 | .header("Authorization", format("Bearer %s", getToken())) 104 | .build() 105 | )) 106 | .build() 107 | ); 108 | return client; 109 | } 110 | 111 | private ObjectMapper getObjectMapper() { 112 | objectMapper = Optional.ofNullable(objectMapper).orElseGet(() -> new ObjectMapper() 113 | .setSerializationInclusion(Include.NON_NULL) 114 | .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) 115 | ); 116 | return objectMapper; 117 | } 118 | 119 | private String baseUrl() { 120 | return configuration.get(BitbucketProperties.ENDPOINT.getKey()) 121 | .orElseThrow(() -> 122 | new IllegalArgumentException(format("Missing required property %s", BitbucketProperties.ENDPOINT.getKey())) 123 | ); 124 | } 125 | 126 | private String getToken() { 127 | return configuration.get(BitbucketProperties.TOKEN.getKey()) 128 | .orElseThrow(() -> new IllegalArgumentException("Personal Access Token for Bitbucket Server is missing")); 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/BitbucketProperties.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket; 2 | 3 | import org.sonar.api.config.PropertyDefinition; 4 | import org.sonar.api.resources.Qualifiers; 5 | 6 | import java.util.Arrays; 7 | import java.util.Collection; 8 | 9 | public enum BitbucketProperties { 10 | ENDPOINT("sonar.pullrequest.bitbucket.endpoint"), 11 | TOKEN("sonar.pullrequest.bitbucket.token.secured"), 12 | 13 | PROJECT("sonar.pullrequest.bitbucket.project"), 14 | REPOSITORY("sonar.pullrequest.bitbucket.repository"); 15 | 16 | private String key; 17 | 18 | BitbucketProperties(String key) { 19 | this.key = key; 20 | } 21 | 22 | public String getKey() { 23 | return key; 24 | } 25 | 26 | public static Collection definitions() { 27 | return Arrays.asList(PropertyDefinition.builder(ENDPOINT.getKey()) 28 | .index(0) 29 | .name("The URL of the Bitbucket Server") 30 | .description("This is the base URL for your Bitbucket Server instance") 31 | .onQualifiers(Qualifiers.PROJECT) 32 | .category("pullrequest").subCategory("bitbucket") 33 | .build(), 34 | PropertyDefinition.builder(TOKEN.getKey()) 35 | .index(1) 36 | .name("Personal access token") 37 | .description("The personal access token of the user that will be used to decorate the pull requests") 38 | .onQualifiers(Qualifiers.PROJECT) 39 | .category("pullrequest").subCategory("bitbucket") 40 | .build(), 41 | PropertyDefinition.builder(PROJECT.getKey()) 42 | .index(2) 43 | .name("Bitbucket Server project key") 44 | .description("You can find it in the Bitbucket Server repository URL") 45 | .onlyOnQualifiers(Qualifiers.PROJECT) 46 | .category("pullrequest").subCategory("bitbucket") 47 | .build(), 48 | PropertyDefinition.builder(REPOSITORY.getKey()) 49 | .index(3) 50 | .name("Bitbucket Server repository slug") 51 | .description("You can find it in the Bitbucket Server repository URL") 52 | .onlyOnQualifiers(Qualifiers.PROJECT) 53 | .category("pullrequest").subCategory("bitbucket") 54 | .build()); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/BitbucketPropertiesSensor.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket; 2 | 3 | import com.github.goober.sonarqube.plugin.decorator.PullRequestProperties; 4 | import org.sonar.api.batch.sensor.Sensor; 5 | import org.sonar.api.batch.sensor.SensorContext; 6 | import org.sonar.api.batch.sensor.SensorDescriptor; 7 | 8 | import java.util.Arrays; 9 | import java.util.stream.Stream; 10 | 11 | public class BitbucketPropertiesSensor implements Sensor { 12 | 13 | @Override 14 | public void describe(SensorDescriptor sensorDescriptor) { 15 | sensorDescriptor.name("Bitbucket Properties Sensor"); 16 | } 17 | 18 | @Override 19 | public void execute(SensorContext context) { 20 | Stream.concat( 21 | Arrays.stream(BitbucketProperties.values()) 22 | .map(BitbucketProperties::getKey), 23 | Arrays.stream(PullRequestProperties.values() 24 | ).map(PullRequestProperties::getKey) 25 | ).forEach(key -> context.config().get(key) 26 | .ifPresent(value -> context.addContextProperty(key, value))); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/BitbucketPullRequestDecorator.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket; 2 | 3 | import com.github.goober.sonarqube.plugin.decorator.PullRequestDecorator; 4 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.model.CreateAnnotationsRequest; 5 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.model.ServerProperties; 6 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.PullRequestReportCollector; 7 | import lombok.RequiredArgsConstructor; 8 | import org.sonar.api.utils.log.Logger; 9 | import org.sonar.api.utils.log.Loggers; 10 | 11 | import java.io.IOException; 12 | 13 | import static java.lang.String.format; 14 | 15 | @RequiredArgsConstructor 16 | public class BitbucketPullRequestDecorator implements PullRequestDecorator { 17 | 18 | private static final Logger LOGGER = Loggers.get(BitbucketPullRequestDecorator.class); 19 | 20 | private final PullRequestReportCollector reportCollector; 21 | private final BitbucketClient bitbucketClient; 22 | 23 | @Override 24 | public boolean isActivated() { 25 | return bitbucketClient.isConfigured() && hasApiSupport(); 26 | } 27 | 28 | @Override 29 | public void decorate(ProjectAnalysis analysis) { 30 | try { 31 | BitbucketPullRequestReport report = new BitbucketPullRequestReport(reportCollector.collect(analysis)); 32 | 33 | bitbucketClient.createReport(report.getProject(), 34 | report.getRepository(), 35 | report.getRevision(), 36 | report.toCreateReportRequest() 37 | ); 38 | 39 | bitbucketClient.deleteAnnotations(report.getProject(), report.getRepository(), report.getRevision()); 40 | 41 | bitbucketClient.createAnnotations(report.getProject(), 42 | report.getRepository(), 43 | report.getRevision(), 44 | CreateAnnotationsRequest.builder() 45 | .annotations(report.getAnnotations()) 46 | .build()); 47 | 48 | } catch (IOException e) { 49 | LOGGER.error("Could not decorate pull request for project {}", analysis.getProject().getKey(), e); 50 | } 51 | } 52 | 53 | private boolean hasApiSupport() { 54 | try { 55 | ServerProperties server = bitbucketClient.getServerProperties(); 56 | LOGGER.debug(format("Your Bitbucket Server installation is version %s", server.getVersion())); 57 | if (server.hasCodeInsightsApi()) { 58 | return true; 59 | } else { 60 | LOGGER.info(format("Bitbucket Server version is to old: %s . The minimum version that supports code insights is %s", 61 | server.getVersion(), ServerProperties.CODE_INSIGHT_VERSION)); 62 | } 63 | } catch (IOException e) { 64 | LOGGER.error("Could not determine Bitbucket Server version", e); 65 | return false; 66 | } 67 | return false; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/BitbucketPullRequestReport.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket; 2 | 3 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.model.Annotation; 4 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.model.CreateReportRequest; 5 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.model.DataValue; 6 | import com.github.goober.sonarqube.plugin.decorator.bitbucket.model.ReportData; 7 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.PullRequestReport; 8 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.QualityCondition; 9 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.Issue; 10 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.Measure; 11 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.Rating; 12 | import lombok.NonNull; 13 | import lombok.RequiredArgsConstructor; 14 | import org.sonar.api.ce.posttask.QualityGate; 15 | 16 | import java.math.BigDecimal; 17 | import java.util.ArrayList; 18 | import java.util.Arrays; 19 | import java.util.List; 20 | import java.util.Optional; 21 | import java.util.Set; 22 | import java.util.stream.Collectors; 23 | 24 | import static java.lang.String.format; 25 | 26 | @RequiredArgsConstructor 27 | class BitbucketPullRequestReport { 28 | 29 | @NonNull 30 | private final PullRequestReport report; 31 | 32 | String getProject() { 33 | return report.getRequiredProperty(BitbucketProperties.PROJECT.getKey()); 34 | } 35 | 36 | String getRepository() { 37 | return report.getRequiredProperty(BitbucketProperties.REPOSITORY.getKey()); 38 | } 39 | 40 | String getRevision() { 41 | return report.getRevision() 42 | .orElseThrow(() -> new IllegalArgumentException("Missing revision information")); 43 | } 44 | 45 | String getResult() { 46 | return Optional.ofNullable(report.getStatus()) 47 | .map(this::asInsightStatus) 48 | .orElse("PASS"); 49 | } 50 | 51 | String getReportDetails() { 52 | String header = report.getStatus().equals(QualityGate.Status.ERROR) ? "Quality Gate failed" : "Quality Gate passed"; 53 | String body = ""; 54 | if (report.getStatus().equals(QualityGate.Status.ERROR)) { 55 | body = report.getQualityConditions().stream() 56 | .filter(c -> QualityGate.EvaluationStatus.ERROR.equals(c.getCondition().getStatus())) 57 | .map(c -> format("- %s %n", toString(c))) 58 | .collect(Collectors.joining("")); 59 | } 60 | return format("%s%n%s", header, body); 61 | } 62 | 63 | List getReportData() { 64 | List reportData = new ArrayList<>(); 65 | if (report.hasMeasures()) { 66 | reportData.addAll(Arrays.asList( 67 | ReportData.builder() 68 | .title("Bugs") 69 | .value(new DataValue.Text(report.getMeasure("new_bugs") 70 | .flatMap(Measure::firstValue) 71 | .orElse("-"))) 72 | .build(), 73 | ReportData.builder() 74 | .title("Code Coverage") 75 | .value(report.getMeasure("new_coverage") 76 | .flatMap(Measure::firstValue) 77 | .map(BigDecimal::new) 78 | .map(DataValue.Percentage::new) 79 | .map(DataValue.class::cast) 80 | .orElseGet(() -> new DataValue.Text("-")) 81 | ) 82 | .build(), 83 | ReportData.builder() 84 | .title("Vulnerabilities") 85 | .value(new DataValue.Text(report.getMeasure("new_vulnerabilities") 86 | .flatMap(Measure::firstValue) 87 | .orElse("-"))) 88 | .build(), 89 | ReportData.builder() 90 | .title("Duplication") 91 | .value(report.getMeasure("new_duplicated_lines_density") 92 | .flatMap(Measure::firstValue) 93 | .map(BigDecimal::new) 94 | .map(DataValue.Percentage::new) 95 | .map(DataValue.class::cast) 96 | .orElseGet(() -> new DataValue.Text("-"))) 97 | .build(), 98 | ReportData.builder() 99 | .title("Code Smells") 100 | .value(new DataValue.Text(report.getMeasure("new_code_smells") 101 | .flatMap(Measure::firstValue) 102 | .orElse("-"))) 103 | .build() 104 | )); 105 | } 106 | reportData.add(ReportData.builder() 107 | .title("Details") 108 | .value(DataValue.Link.builder() 109 | .linktext("Go to SonarQube") 110 | .href(report.getUrl()) 111 | .build()) 112 | .build()); 113 | return reportData; 114 | } 115 | 116 | CreateReportRequest toCreateReportRequest() { 117 | return CreateReportRequest.builder() 118 | .title("SonarQube") 119 | .vendor("SonarQube") 120 | .logoUrl("https://www.sonarqube.org/favicon-152.png") 121 | .details(getReportDetails()) 122 | .data(getReportData()) 123 | .result(getResult()) 124 | .createdDate(report.getCreationTimestamp()) 125 | .build(); 126 | } 127 | 128 | Set getAnnotations() { 129 | return report.getIssues().stream() 130 | .map(this::toAnnotation) 131 | .collect(Collectors.toSet()); 132 | } 133 | 134 | private Annotation toAnnotation(Issue issue) { 135 | return Annotation.builder() 136 | .line(issue.getLine()) 137 | .path(issue.getPath()) 138 | .message(issue.getMessage()) 139 | .link(issue.getIssueUrl()) 140 | .externalId(issue.getKey()) 141 | .severity(toBitbucketSeverity(issue)) 142 | .type(toBitbucketType(issue.getType())) 143 | .build(); 144 | } 145 | 146 | private String toBitbucketSeverity(Issue issue) { 147 | if (issue.getSeverity() == null) { 148 | return "LOW"; 149 | } 150 | switch (issue.getSeverity()) { 151 | case "BLOCKER": 152 | case "CRITICAL": 153 | return "HIGH"; 154 | case "MAJOR": 155 | return "MEDIUM"; 156 | default: 157 | return "LOW"; 158 | } 159 | } 160 | 161 | private String toBitbucketType(String sonarqubeType) { 162 | switch (sonarqubeType) { 163 | case "SECURITY_HOTSPOT": 164 | case "VULNERABILITY": 165 | return "VULNERABILITY"; 166 | case "CODE_SMELL": 167 | return "CODE_SMELL"; 168 | case "BUG": 169 | return "BUG"; 170 | default: 171 | return ""; 172 | } 173 | } 174 | 175 | private String toString(QualityCondition condition) { 176 | if (condition.getMetric().getType().equals("RATING")) { 177 | return format("%s %s (%s %s)", 178 | Rating.valueOf(Integer.parseInt(condition.getCondition().getValue())), 179 | condition.getMetric().getName(), 180 | condition.getCondition().getOperator().equals(QualityGate.Operator.GREATER_THAN) ? "is worse than" : "is better than", 181 | Rating.valueOf(Integer.parseInt(condition.getCondition().getErrorThreshold()))); 182 | } 183 | return format("%s %s (%s %s)", 184 | condition.getCondition().getValue(), 185 | condition.getMetric().getName(), 186 | condition.getCondition().getOperator().equals(QualityGate.Operator.GREATER_THAN) ? "is greater than" : "is less than", 187 | condition.getCondition().getErrorThreshold()); 188 | } 189 | 190 | private String asInsightStatus(QualityGate.Status status) { 191 | return QualityGate.Status.ERROR.equals(status) ? "FAIL" : "PASS"; 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/model/Annotation.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket.model; 2 | 3 | import lombok.Builder; 4 | import lombok.Value; 5 | 6 | @Value 7 | @Builder 8 | public class Annotation { 9 | String externalId; 10 | int line; 11 | String link; 12 | String message; 13 | String path; 14 | String severity; 15 | String type; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/model/CreateAnnotationsRequest.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket.model; 2 | 3 | import lombok.Builder; 4 | import lombok.Value; 5 | 6 | import java.util.Set; 7 | 8 | @Value 9 | @Builder 10 | public class CreateAnnotationsRequest { 11 | Set annotations; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/model/CreateReportRequest.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket.model; 2 | 3 | import lombok.Builder; 4 | import lombok.Value; 5 | 6 | import java.time.Instant; 7 | import java.util.List; 8 | 9 | @Value 10 | @Builder 11 | public class CreateReportRequest { 12 | List data; 13 | String details; 14 | String title; 15 | String vendor; 16 | Instant createdDate; 17 | String link; 18 | String logoUrl; 19 | String result; 20 | } -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/model/DataValue.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonValue; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.EqualsAndHashCode; 7 | import lombok.Value; 8 | 9 | import java.math.BigDecimal; 10 | 11 | public abstract class DataValue { 12 | 13 | @Value 14 | @Builder 15 | @EqualsAndHashCode(callSuper=false) 16 | public static class Link extends DataValue { 17 | String linktext; 18 | String href; 19 | } 20 | 21 | @AllArgsConstructor 22 | @Value 23 | @EqualsAndHashCode(callSuper=false) 24 | public static class Text extends DataValue { 25 | @JsonValue 26 | String value; 27 | } 28 | 29 | @AllArgsConstructor 30 | @Value 31 | @EqualsAndHashCode(callSuper = false) 32 | public static class Percentage extends DataValue { 33 | @JsonValue 34 | BigDecimal value; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/model/ReportData.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket.model; 2 | 3 | import lombok.Builder; 4 | import lombok.Value; 5 | 6 | @Value 7 | @Builder 8 | public class ReportData { 9 | String title; 10 | DataValue value; 11 | String type; 12 | 13 | public static class ReportDataBuilder { 14 | String type; 15 | DataValue value; 16 | 17 | public ReportDataBuilder value(DataValue value) { 18 | this.value = value; 19 | if(value instanceof DataValue.Link) { 20 | this.type = "LINK"; 21 | } else if(value instanceof DataValue.Percentage) { 22 | this.type = "PERCENTAGE"; 23 | } else { 24 | this.type = "TEXT"; 25 | } 26 | return this; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/model/ServerProperties.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Value; 5 | 6 | @Value 7 | @AllArgsConstructor 8 | public class ServerProperties { 9 | public static final String CODE_INSIGHT_VERSION = "5.15"; 10 | 11 | String version; 12 | 13 | public boolean hasCodeInsightsApi() { 14 | return compareTo(CODE_INSIGHT_VERSION) >= 0; 15 | } 16 | 17 | private int compareTo(String other) { 18 | String[] current = semver(version); 19 | String[] minimum = semver(other); 20 | 21 | int length = Math.max(current.length, minimum.length); 22 | for(int i = 0; i < length; i++) { 23 | int thisPart = i < current.length ? 24 | Integer.parseInt(current[i]) : 0; 25 | int thatPart = i < minimum.length ? 26 | Integer.parseInt(minimum[i]) : 0; 27 | if(thisPart < thatPart) 28 | return -1; 29 | if(thisPart > thatPart) 30 | return 1; 31 | } 32 | return 0; 33 | } 34 | 35 | private String[] semver(String v) { 36 | return v.split("\\."); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/PullRequestReport.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube; 2 | 3 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.Issue; 4 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.Measure; 5 | import lombok.AccessLevel; 6 | import lombok.Builder; 7 | import lombok.Getter; 8 | import lombok.NonNull; 9 | import lombok.Value; 10 | import org.sonar.api.ce.posttask.Analysis; 11 | import org.sonar.api.ce.posttask.PostProjectAnalysisTask; 12 | import org.sonar.api.ce.posttask.QualityGate; 13 | 14 | import java.time.Instant; 15 | import java.util.Date; 16 | import java.util.Map; 17 | import java.util.Optional; 18 | import java.util.Set; 19 | 20 | import static java.lang.String.format; 21 | 22 | @Value 23 | @Builder 24 | public class PullRequestReport { 25 | @NonNull 26 | @Getter(AccessLevel.NONE) 27 | PostProjectAnalysisTask.ProjectAnalysis analysis; 28 | 29 | String pullRequestId; 30 | 31 | String url; 32 | 33 | Set qualityConditions; 34 | Map measures; 35 | 36 | Set issues; 37 | 38 | public Instant getCreationTimestamp() { 39 | return analysis.getAnalysis() 40 | .map(Analysis::getDate) 41 | .map(Date::toInstant) 42 | .orElse(Instant.now()); 43 | } 44 | 45 | public String getRequiredProperty(String key) { 46 | return Optional.ofNullable(analysis.getScannerContext().getProperties().get(key)) 47 | .orElseThrow(() -> new IllegalArgumentException(format("Missing required property %s", key))); 48 | } 49 | 50 | public Optional getRevision() { 51 | return analysis.getAnalysis() 52 | .flatMap(Analysis::getRevision); 53 | } 54 | 55 | public boolean hasMeasures() { 56 | return !measures.isEmpty(); 57 | } 58 | 59 | public Optional getMeasure(String key) { 60 | return Optional.ofNullable(measures.get(key)); 61 | } 62 | 63 | public QualityGate.Status getStatus() { 64 | return analysis.getQualityGate().getStatus(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/PullRequestReportCollector.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube; 2 | 3 | import com.github.goober.sonarqube.plugin.decorator.PullRequestProperties; 4 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.MeasureResponse; 5 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.Metric; 6 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.SearchIssuesResponse; 7 | import lombok.RequiredArgsConstructor; 8 | import org.sonar.api.ce.ComputeEngineSide; 9 | import org.sonar.api.ce.posttask.Branch; 10 | import org.sonar.api.ce.posttask.PostProjectAnalysisTask; 11 | import org.sonar.api.utils.log.Logger; 12 | import org.sonar.api.utils.log.Loggers; 13 | 14 | import java.io.IOException; 15 | import java.util.Map; 16 | import java.util.Set; 17 | import java.util.stream.Collectors; 18 | 19 | import static java.lang.String.format; 20 | import static java.util.stream.Collectors.toMap; 21 | 22 | @ComputeEngineSide 23 | @RequiredArgsConstructor 24 | public class PullRequestReportCollector { 25 | 26 | private static final Logger LOGGER = Loggers.get(PullRequestReportCollector.class); 27 | 28 | private final SonarQubeClient sonarqubeClient; 29 | 30 | public PullRequestReport collect(PostProjectAnalysisTask.ProjectAnalysis analysis) throws IOException { 31 | String pullRequestId = analysis.getBranch().flatMap(Branch::getName) 32 | .orElseThrow(() -> new IllegalArgumentException(format("Missing required property %s", PullRequestProperties.KEY.getKey()))); 33 | 34 | Map metrics = sonarqubeClient.listMetrics().getMetrics().stream() 35 | .collect(toMap(Metric::getKey, m -> m)); 36 | 37 | Set qualityConditions = analysis.getQualityGate().getConditions().stream() 38 | .map(condition -> new QualityCondition(condition, metrics.get(condition.getMetricKey()))) 39 | .collect(Collectors.toSet()); 40 | 41 | MeasureResponse measures = sonarqubeClient.listMeasures(analysis.getProject().getKey(), pullRequestId, 42 | "new_code_smells", 43 | "new_bugs", 44 | "new_vulnerabilities", 45 | "new_coverage", 46 | "new_duplicated_lines_density"); 47 | 48 | SearchIssuesResponse issues = sonarqubeClient.listOpenIssues(analysis.getProject().getKey(), pullRequestId); 49 | 50 | return PullRequestReport.builder() 51 | .pullRequestId(pullRequestId) 52 | .url(measures.getDashboardUrl()) 53 | .issues(issues.getIssues()) 54 | .qualityConditions(qualityConditions) 55 | .analysis(analysis) 56 | .measures(measures.getMeasures()) 57 | .build(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/QualityCondition.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube; 2 | 3 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.Metric; 4 | import lombok.Value; 5 | import org.sonar.api.ce.posttask.QualityGate; 6 | 7 | @Value 8 | public class QualityCondition { 9 | QualityGate.Condition condition; 10 | Metric metric; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/SonarQubeClient.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 4 | import com.fasterxml.jackson.databind.DeserializationFeature; 5 | import com.fasterxml.jackson.databind.InjectableValues; 6 | import com.fasterxml.jackson.databind.ObjectMapper; 7 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.MeasureResponse; 8 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.MetricsResponse; 9 | import com.github.goober.sonarqube.plugin.decorator.sonarqube.model.SearchIssuesResponse; 10 | import lombok.RequiredArgsConstructor; 11 | import okhttp3.OkHttpClient; 12 | import okhttp3.Request; 13 | import okhttp3.Response; 14 | import org.sonar.api.ce.ComputeEngineSide; 15 | import org.sonar.api.config.Configuration; 16 | import org.sonar.api.platform.Server; 17 | import org.sonar.api.utils.log.Logger; 18 | import org.sonar.api.utils.log.Loggers; 19 | 20 | import java.io.IOException; 21 | import java.util.Optional; 22 | 23 | import static java.lang.String.format; 24 | 25 | @ComputeEngineSide 26 | @RequiredArgsConstructor 27 | public class SonarQubeClient { 28 | 29 | private static final Logger LOGGER = Loggers.get(SonarQubeClient.class); 30 | 31 | private final Server server; 32 | private final Configuration configuration; 33 | 34 | private OkHttpClient client; 35 | 36 | private ObjectMapper objectMapper; 37 | 38 | public SearchIssuesResponse listOpenIssues(String project, String pullRequestId) throws IOException { 39 | Request request = new Request.Builder() 40 | .url(String.format("%s/api/issues/search?projects=%s&pullRequest=%s", getLocalUrl(), project, pullRequestId)) 41 | .build(); 42 | 43 | try (Response response = getClient().newCall(request).execute()) { 44 | if (response.isSuccessful()) { 45 | return objectMapper().reader(new InjectableValues.Std() 46 | .addValue("baseUrl", server.getPublicRootUrl())) 47 | .forType(SearchIssuesResponse.class) 48 | .readValue(response.body().string()); 49 | } 50 | LOGGER.error("{} - {}", response.code(), response.body() == null ? "" : response.body().string()); 51 | throw new IOException(format("SonarQube's API responded with an unsuccessful response code %d", response.code())); 52 | } 53 | } 54 | 55 | public MetricsResponse listMetrics() throws IOException { 56 | Request request = new Request.Builder() 57 | .url(String.format("%s/api/metrics/search?ps=500", getLocalUrl())) 58 | .build(); 59 | try (Response response = getClient().newCall(request).execute()) { 60 | if (response.isSuccessful()) { 61 | return objectMapper().reader().forType(MetricsResponse.class).readValue(response.body().string()); 62 | } 63 | LOGGER.error("{} - {}", response.code(), response.body() == null ? "" : response.body().string()); 64 | throw new IOException(format("SonarQube's API responded with an unsuccessful response code %d", response.code())); 65 | } 66 | } 67 | 68 | public MeasureResponse listMeasures(String project, String pullRequestId, String... measures) throws IOException { 69 | Request request = new Request.Builder() 70 | .url(String.format("%s/api/measures/component?component=%s&pullRequest=%s&metricKeys=%s", 71 | getLocalUrl(), 72 | project, 73 | pullRequestId, 74 | String.join(",", measures))) 75 | .build(); 76 | try (Response response = getClient().newCall(request).execute()) { 77 | if (response.isSuccessful()) { 78 | return objectMapper().reader(new InjectableValues.Std() 79 | .addValue("dashboardUrl", getDashboardUrl(project, pullRequestId))) 80 | .forType(MeasureResponse.class) 81 | .readValue(response.body().string()); 82 | } 83 | LOGGER.error("{} - {}", response.code(), response.body() == null ? "" : response.body().string()); 84 | throw new IOException(format("SonarQube's API responded with an unsuccessful response code %d", response.code())); 85 | } 86 | } 87 | 88 | private String getDashboardUrl(String project, String pullRequestId) { 89 | return String.format("%s/dashboard?id=%s&pullRequest=%s", server.getPublicRootUrl(), project, pullRequestId); 90 | } 91 | 92 | private String getLocalUrl() { 93 | return "http://localhost:" + configuration.get("sonar.web.port").orElse("9000") + server.getContextPath(); 94 | } 95 | 96 | private OkHttpClient getClient() { 97 | client = Optional.ofNullable(client).orElseGet(OkHttpClient::new); 98 | return client; 99 | } 100 | 101 | private ObjectMapper objectMapper() { 102 | objectMapper = Optional.ofNullable(objectMapper) 103 | .orElseGet(() -> new ObjectMapper() 104 | .setSerializationInclusion(Include.NON_NULL) 105 | .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) 106 | ); 107 | return objectMapper; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/model/Component.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube.model; 2 | 3 | import lombok.Builder; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.Value; 6 | 7 | import java.util.Set; 8 | 9 | @Value 10 | @Builder 11 | @RequiredArgsConstructor 12 | public class Component { 13 | Set measures; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/model/Issue.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube.model; 2 | 3 | import com.fasterxml.jackson.annotation.JacksonInject; 4 | import lombok.AccessLevel; 5 | import lombok.Builder; 6 | import lombok.Getter; 7 | import lombok.Value; 8 | 9 | @Builder 10 | @Value 11 | public class Issue { 12 | String key; 13 | String rule; 14 | String severity; 15 | Integer line; 16 | String component; 17 | String message; 18 | String type; 19 | String project; 20 | String pullRequest; 21 | 22 | @JacksonInject("baseUrl") 23 | @Getter(AccessLevel.NONE) 24 | String baseUrl; 25 | 26 | public String getIssueUrl() { 27 | return String.format("%s/project/issues?id=%s&pullRequest=%s&open=%s", baseUrl, project, pullRequest, key); 28 | } 29 | 30 | public String getPath() { 31 | return component.substring(component.lastIndexOf(':') + 1); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/model/Measure.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube.model; 2 | 3 | import lombok.Builder; 4 | import lombok.Value; 5 | 6 | import java.util.Optional; 7 | import java.util.Set; 8 | 9 | @Value 10 | @Builder 11 | public class Measure { 12 | String metric; 13 | Set periods; 14 | 15 | public Optional firstValue() { 16 | return periods.stream().findFirst().map(Period::getValue); 17 | } 18 | 19 | @Value 20 | static class Period { 21 | String value; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/model/MeasureResponse.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube.model; 2 | 3 | import com.fasterxml.jackson.annotation.JacksonInject; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.Value; 6 | 7 | import java.util.Map; 8 | 9 | import static java.util.stream.Collectors.toMap; 10 | 11 | @Value 12 | @RequiredArgsConstructor 13 | public class MeasureResponse { 14 | Component component; 15 | @JacksonInject("dashboardUrl") 16 | String dashboardUrl; 17 | 18 | public Map getMeasures() { 19 | return component.getMeasures().stream().collect(toMap(Measure::getMetric, m -> m)); 20 | } 21 | 22 | public boolean hasMeasurements() { 23 | return !component.getMeasures().isEmpty(); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/model/Metric.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube.model; 2 | 3 | import lombok.Builder; 4 | import lombok.Value; 5 | 6 | @Builder 7 | @Value 8 | public class Metric { 9 | 10 | String key; 11 | String name; 12 | String description; 13 | String type; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/model/MetricsResponse.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube.model; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import lombok.Value; 5 | 6 | import java.util.Set; 7 | 8 | @Value 9 | @RequiredArgsConstructor 10 | public class MetricsResponse { 11 | Set metrics; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/model/Paging.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube.model; 2 | 3 | import lombok.Builder; 4 | import lombok.Value; 5 | 6 | @Value 7 | @Builder 8 | public class Paging { 9 | 10 | Integer pageIndex; 11 | Integer pageSize; 12 | Integer total; 13 | } -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/model/Rating.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube.model; 2 | 3 | import java.util.Arrays; 4 | 5 | public enum Rating { 6 | E(5), 7 | D(4), 8 | C(3), 9 | B(2), 10 | A(1); 11 | 12 | private final int index; 13 | 14 | Rating(int index) { 15 | this.index = index; 16 | } 17 | 18 | public static Rating valueOf(int index) { 19 | return Arrays.stream(values()).filter(r -> r.index == index).findFirst() 20 | .orElseThrow(() -> new IllegalArgumentException(String.format("Unknown value '%s'", index))); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/github/goober/sonarqube/plugin/decorator/sonarqube/model/SearchIssuesResponse.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.sonarqube.model; 2 | 3 | import lombok.Builder; 4 | import lombok.Value; 5 | 6 | import java.util.Set; 7 | 8 | @Value 9 | @Builder 10 | public class SearchIssuesResponse { 11 | 12 | Integer total; 13 | Integer p; 14 | Integer ps; 15 | Paging paging; 16 | 17 | Set issues; 18 | 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/main/resources/org/sonar/l10n/pullRequestDecoratorPlugin_en.properties: -------------------------------------------------------------------------------- 1 | property.category.pullrequest=Pull Requests 2 | property.category.pullrequest.bitbucket=Integration with Bitbucket Server 3 | property.category.pullrequest.bitbucket.description=Configure the integration to enable pull request decorations for Bitbucket Server. 4 | -------------------------------------------------------------------------------- /src/test/java/com/github/goober/sonarqube/plugin/decorator/bitbucket/model/ServerPropertiesTest.java: -------------------------------------------------------------------------------- 1 | package com.github.goober.sonarqube.plugin.decorator.bitbucket.model; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.assertFalse; 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | 8 | public class ServerPropertiesTest { 9 | 10 | @Test 11 | public void server_with_version_without_code_insights_returns_false() { 12 | ServerProperties underTest = new ServerProperties("2.1"); 13 | assertFalse(underTest.hasCodeInsightsApi()); 14 | } 15 | 16 | @Test 17 | public void server_version_greater_than_minimum_for_code_insights_returns_true() { 18 | ServerProperties underTest = new ServerProperties("6.7.1"); 19 | assertTrue(underTest.hasCodeInsightsApi()); 20 | } 21 | 22 | @Test 23 | public void server_version_equals_to_minimum_for_code_insights_return_true() { 24 | ServerProperties underTest = new ServerProperties(ServerProperties.CODE_INSIGHT_VERSION); 25 | assertTrue(underTest.hasCodeInsightsApi()); 26 | } 27 | } 28 | --------------------------------------------------------------------------------