]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-11950 add scm revision scanner parameter
authorMichal Duda <michal.duda@sonarsource.com>
Tue, 7 May 2019 12:28:09 +0000 (14:28 +0200)
committerSonarTech <sonartech@sonarsource.com>
Wed, 22 May 2019 18:21:17 +0000 (20:21 +0200)
12 files changed:
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ProjectAttributes.java
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStep.java
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistAnalysisStep.java
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportComponent.java
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateEventsStepTest.java
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportPersistAnalysisStepTest.java
server/sonar-docs/src/pages/project-administration/webhooks.md
sonar-scanner-engine/src/main/java/org/sonar/scanner/report/MetadataPublisher.java
sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ScanProperties.java
sonar-scanner-engine/src/test/java/org/sonar/scanner/report/MetadataPublisherTest.java

index 051c7f0cec32b96fa1571cc30e8f2a005899067d..9d0cefd5e2e861b592748ebbd4ed41abee4d62ab 100644 (file)
@@ -30,14 +30,19 @@ public class ProjectAttributes {
   @Nullable
   private final String buildString;
 
-  public ProjectAttributes(String projectVersion, @Nullable String buildString) {
+  @Nullable
+  private final String scmRevisionId;
+
+  public ProjectAttributes(String projectVersion, @Nullable String buildString, @Nullable String scmRevisionId) {
     this.projectVersion = requireNonNull(projectVersion, "project version can't be null");
     this.buildString = buildString;
+    this.scmRevisionId = scmRevisionId;
   }
 
   public ProjectAttributes(ProjectAttributes projectAttributes) {
     this.projectVersion = projectAttributes.projectVersion;
     this.buildString = projectAttributes.buildString;
+    this.scmRevisionId = projectAttributes.scmRevisionId;
   }
 
   public String getProjectVersion() {
@@ -48,11 +53,16 @@ public class ProjectAttributes {
     return Optional.ofNullable(buildString);
   }
 
+  public Optional<String> getScmRevisionId() {
+    return Optional.ofNullable(scmRevisionId);
+  }
+
   @Override
   public String toString() {
     return "ProjectAttributes{" +
       "projectVersion='" + projectVersion + '\'' +
       "buildString='" + buildString + '\'' +
+      "scmRevisionId='" + scmRevisionId + '\'' +
       '}';
   }
 }
index b4788259f408b2b05954bd5d207a5ebc29eb3e69..96abdd05c0eb812b0d6b5446a3b195a721eb6a49 100644 (file)
@@ -113,7 +113,8 @@ public class BuildComponentTreeStep implements ComputationStep {
   private static ProjectAttributes createProjectAttributes(ScannerReport.Metadata metadata, @Nullable SnapshotDto baseAnalysis) {
     String projectVersion = computeProjectVersion(trimToNull(metadata.getProjectVersion()), baseAnalysis);
     String buildString = trimToNull(metadata.getBuildString());
-    return new ProjectAttributes(projectVersion, buildString);
+    String scmRevisionId = trimToNull(metadata.getScmRevisionId());
+    return new ProjectAttributes(projectVersion, buildString, scmRevisionId);
   }
 
   private static String computeProjectVersion(@Nullable String projectVersion, @Nullable SnapshotDto baseAnalysis) {
index c6bc3bdc068516e96e5cebc0329622f1e7e3e6a4..134e0a0867bf1580b8f9451429d0c1575dc68f69 100644 (file)
@@ -104,7 +104,7 @@ public class PersistAnalysisStep implements ComputationStep {
       String componentUuid = component.getUuid();
       String projectVersion = component.getType() == PROJECT ? component.getProjectAttributes().getProjectVersion() : null;
       String buildString = component.getType() == PROJECT ? component.getProjectAttributes().getBuildString().orElse(null) : null;
-      return new SnapshotDto()
+      SnapshotDto dto = new SnapshotDto()
         .setUuid(snapshotUuid)
         .setProjectVersion(projectVersion)
         .setBuildString(buildString)
@@ -113,6 +113,12 @@ public class PersistAnalysisStep implements ComputationStep {
         .setStatus(SnapshotDto.STATUS_UNPROCESSED)
         .setCreatedAt(analysisDate)
         .setBuildDate(system2.now());
+
+      if (component.getType() == PROJECT) {
+        component.getProjectAttributes().getScmRevisionId().ifPresent(dto::setRevision);
+      }
+
+      return dto;
     }
 
     private void persist(SnapshotDto snapshotDto, DbSession dbSession) {
index e1e7d216e73ad48a4e0cafe59d7eca5086c0065d..d0f4c51e5b04979a6d8e4b7b040ea348777a4704 100644 (file)
@@ -249,7 +249,7 @@ public class ComponentImplTest {
       .setReportAttributes(ReportAttributes.newBuilder(dbKey.hashCode()).build());
     if (type == PROJECT) {
       String buildString = randomAlphabetic(15);
-      builder.setProjectAttributes(new ProjectAttributes("version_1", buildString));
+      builder.setProjectAttributes(new ProjectAttributes("version_1", buildString, "453def"));
     }
     return builder;
   }
index c62af5f23b09247bc139a0a263e3de4b0d6dd8d9..8ce64c942dd47435d5cc39e67e75c5303bdf1d52 100644 (file)
@@ -64,7 +64,7 @@ public class ComponentTreeBuilderTest {
   private static final String NO_SCM_BASE_PATH = "";
   // both no project as "" or null should be supported
   private static final ProjectAttributes SOME_PROJECT_ATTRIBUTES = new ProjectAttributes(
-    randomAlphabetic(20), new Random().nextBoolean() ? null : randomAlphabetic(12));
+    randomAlphabetic(20), new Random().nextBoolean() ? null : randomAlphabetic(12), "1def5123");
 
   @Rule
   public ExpectedException expectedException = ExpectedException.none();
@@ -131,7 +131,7 @@ public class ComponentTreeBuilderTest {
       .setRef(42)
       .setName(nameInReport)
       .setDescription(descriptionInReport)
-      .build(), NO_SCM_BASE_PATH, new ProjectAttributes("6.5", buildString));
+      .build(), NO_SCM_BASE_PATH, new ProjectAttributes("6.5", buildString, "4124af4"));
 
     assertThat(root.getUuid()).isEqualTo("generated_K1_uuid");
     assertThat(root.getDbKey()).isEqualTo("generated_K1");
index 68b6439652558f1a9be3c4d4d5c7af223d1e21de..0b10c06c7bb4d0138789edd65c2cd990ab2d0823 100644 (file)
@@ -70,7 +70,7 @@ public class ReportComponent implements Component {
     this.description = builder.description;
     this.uuid = builder.uuid;
     this.projectAttributes = Optional.ofNullable(builder.projectVersion)
-      .map(v -> new ProjectAttributes(v, builder.buildString))
+      .map(v -> new ProjectAttributes(v, builder.buildString, builder.scmRevisionId))
       .orElse(null);
     this.reportAttributes = ReportAttributes.newBuilder(builder.ref)
       .build();
@@ -207,6 +207,7 @@ public class ReportComponent implements Component {
     private String shortName;
     private String projectVersion;
     private String buildString;
+    private String scmRevisionId;
     private String description;
     private FileAttributes fileAttributes;
     private final List<Component> children = new ArrayList<>();
@@ -262,6 +263,11 @@ public class ReportComponent implements Component {
       return this;
     }
 
+    public Builder setScmRevisionId(@Nullable String scmRevisionId) {
+      this.scmRevisionId = scmRevisionId;
+      return this;
+    }
+
     public Builder setFileAttributes(FileAttributes fileAttributes) {
       checkState(type == Type.FILE, "Only Component of type File can have File attributes");
       this.fileAttributes = fileAttributes;
index 23e7c2d4d5b6acfbc123497d0afba899a75c93b6..23ffaa83399cc5e88bf89b7cdac99b36d761ccbf 100644 (file)
@@ -67,6 +67,7 @@ public class QualityGateEventsStepTest {
     .setKey("key 1")
     .setProjectVersion(PROJECT_VERSION)
     .setBuildString("V1.9")
+    .setScmRevisionId("456def")
     .addChildren(ReportComponent.builder(Component.Type.DIRECTORY, 2).build())
     .build();
   private static final String INVALID_ALERT_STATUS = "trololo";
index 932c459716509ef83c11a0f6e40eb277543f3fdf..68bca2c288f33d99df84fe20d9ebe31d8fcc878b 100644 (file)
@@ -55,6 +55,7 @@ public class ReportPersistAnalysisStepTest extends BaseStepTest {
 
   private static final String PROJECT_KEY = "PROJECT_KEY";
   private static final String ANALYSIS_UUID = "U1";
+  private static final String REVISION_ID = "5f6432a1";
 
   @Rule
   public DbTester dbTester = DbTester.create(System2.INSTANCE);
@@ -77,6 +78,7 @@ public class ReportPersistAnalysisStepTest extends BaseStepTest {
     analysisDate = DateUtils.parseDateQuietly("2015-06-01").getTime();
     analysisMetadataHolder.setUuid(ANALYSIS_UUID);
     analysisMetadataHolder.setAnalysisDate(analysisDate);
+    analysisMetadataHolder.setScmRevisionId(REVISION_ID);
     dbIdsRepository = new DbIdsRepositoryImpl();
 
     now = DateUtils.parseDateQuietly("2015-06-02").getTime();
@@ -116,6 +118,7 @@ public class ReportPersistAnalysisStepTest extends BaseStepTest {
       .setKey(PROJECT_KEY)
       .setProjectVersion(projectVersion)
       .setBuildString(buildString)
+      .setScmRevisionId(REVISION_ID)
       .addChildren(directory)
       .build();
     treeRootHolder.setRoot(project);
@@ -137,6 +140,7 @@ public class ReportPersistAnalysisStepTest extends BaseStepTest {
     assertThat(projectSnapshot.getStatus()).isEqualTo("U");
     assertThat(projectSnapshot.getCreatedAt()).isEqualTo(analysisDate);
     assertThat(projectSnapshot.getBuildDate()).isEqualTo(now);
+    assertThat(projectSnapshot.getRevision()).isEqualTo(REVISION_ID);
 
     assertThat(dbIdsRepository.getComponentId(directory)).isEqualTo(directoryDto.getId());
     assertThat(dbIdsRepository.getComponentId(file)).isEqualTo(fileDto.getId());
index c921146c595f1e7c29f990e3203b92b2eab3c021..f547adc7a8bacf54901424abf326f7cbf116c257 100644 (file)
@@ -133,14 +133,13 @@ If you provide additional properties to your SonarScanner using the pattern `son
 For example these additional parameters:
 
 ```
-sonar-scanner -Dsonar.analysis.scmRevision=628f5175ada0d685fd7164baa7c6382c1f25cab4 -Dsonar.analysis.buildNumber=12345
+sonar-scanner -Dsonar.analysis.buildNumber=12345
 ```
 
 Would add this to the payload:
 
 ```
 "properties": {
-  "sonar.analysis.scmRevision": "628f5175ada0d685fd7164baa7c6382c1f25cab4",
   "sonar.analysis.buildNumber": "12345"
 }
 ```
index 9bf40f4a94e6ac6a65cd5f0dea8063648bd19660..dc79f7262f453ceb901e5b78e9d6433096b7117b 100644 (file)
@@ -23,6 +23,7 @@ import java.io.File;
 import java.nio.file.Path;
 import java.util.LinkedList;
 import java.util.Map.Entry;
+import java.util.Optional;
 import java.util.regex.Pattern;
 import javax.annotation.Nullable;
 import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
@@ -145,13 +146,23 @@ public class MetadataPublisher implements ReportPublisherStep {
         LOG.debug(e.getMessage());
       }
       try {
-        builder.setScmRevisionId(scmProvider.revisionId(projectBasedir));
+        computeScmRevision().ifPresent(builder::setScmRevisionId);
       } catch (UnsupportedOperationException e) {
         LOG.debug(e.getMessage());
       }
     }
   }
 
+  private Optional<String> computeScmRevision() {
+    Optional<String> scmRevision = properties.getScmRevision();
+    ScmProvider scmProvider = scmConfiguration.provider();
+    if (!scmRevision.isPresent() && scmProvider != null) {
+      scmRevision = Optional.ofNullable(scmProvider.revisionId(moduleHierarchy.root().getBaseDir()));
+    }
+
+    return scmRevision;
+  }
+
   private void addBranchInformation(ScannerReport.Metadata.Builder builder) {
     builder.setBranchName(branchConfiguration.branchName());
     BranchType branchType = toProtobufBranchType(branchConfiguration.branchType());
index 1da90cf6bf7f994c2d687da5ad7393436fe33695..36fd9b5d41ede30b5710e0b0b53d0995bda76628 100644 (file)
@@ -40,6 +40,7 @@ public class ScanProperties {
   public static final String SONAR_REPORT_EXPORT_PATH = "sonar.report.export.path";
   public static final String PRELOAD_FILE_METADATA_KEY = "sonar.preloadFileMetadata";
   public static final String FORCE_RELOAD_KEY = "sonar.scm.forceReloadAll";
+  public static final String SCM_REVISION = "sonar.scm.revision";
 
   private final Configuration configuration;
   private final DefaultInputProject project;
@@ -78,6 +79,10 @@ public class ScanProperties {
     }
   }
 
+  public Optional<String> getScmRevision() {
+    return configuration.get(SCM_REVISION);
+  }
+
   /**
    * This should be called in the beginning of the analysis to fail fast
    */
index 2c90a1a8eed3f07624fe26b5536fe62c1a9c05a5..cf83df2448d8cd28d890cba7b03bf529928fbaac 100644 (file)
@@ -143,9 +143,9 @@ public class MetadataPublisherTest {
       .setRulesUpdatedAt(date.getTime())
       .build()));
     assertThat(metadata.getPluginsByKey()).containsOnly(entry("java", org.sonar.scanner.protocol.output.ScannerReport.Metadata.Plugin.newBuilder()
-        .setKey("java")
-        .setUpdatedAt(12345)
-        .build()),
+      .setKey("java")
+      .setUpdatedAt(12345)
+      .build()),
       entry("php", org.sonar.scanner.protocol.output.ScannerReport.Metadata.Plugin.newBuilder()
         .setKey("php")
         .setUpdatedAt(45678)
@@ -304,6 +304,19 @@ public class MetadataPublisherTest {
     assertThat(metadata.getScmRevisionId()).isEqualTo(revisionId);
   }
 
+  public void revision_from_scanner_props_overrides_scm_provider_revision_if_specified() throws IOException {
+    String revisionId = "some-sha1";
+    when(scmProvider.revisionId(any(Path.class))).thenReturn(revisionId);
+    when(properties.getScmRevision()).thenReturn(Optional.of("123"));
+
+    File outputDir = temp.newFolder();
+    underTest.publish(new ScannerReportWriter(outputDir));
+
+    ScannerReportReader reader = new ScannerReportReader(outputDir);
+    ScannerReport.Metadata metadata = reader.readMetadata();
+    assertThat(metadata.getScmRevisionId()).isEqualTo("123");
+  }
+
   @Test
   public void should_not_crash_when_scm_provider_does_not_support_relativePathFromScmRoot() throws IOException {
     String revisionId = "some-sha1";