diff --git a/core/src/main/java/org/sonarsource/sonarlint/core/client/api/connected/ProjectBinding.java b/core/src/main/java/org/sonarsource/sonarlint/core/client/api/connected/ProjectBinding.java index 2225a8040a..d119abe377 100644 --- a/core/src/main/java/org/sonarsource/sonarlint/core/client/api/connected/ProjectBinding.java +++ b/core/src/main/java/org/sonarsource/sonarlint/core/client/api/connected/ProjectBinding.java @@ -20,6 +20,7 @@ package org.sonarsource.sonarlint.core.client.api.connected; import java.util.Objects; +import java.util.Optional; /** * Describes the link between a project in the IDE and a project in SonarQube. @@ -49,6 +50,21 @@ public String idePathPrefix() { return idePathPrefix; } + public Optional serverPathToIdePath(String serverPath) { + if (!serverPath.startsWith(sqPathPrefix())) { + return Optional.empty(); + } + int localPrefixLen = sqPathPrefix().length(); + if (localPrefixLen > 0) { + localPrefixLen++; + } + String actualLocalPrefix = idePathPrefix(); + if (!actualLocalPrefix.isEmpty()) { + actualLocalPrefix = actualLocalPrefix + "/"; + } + return Optional.of(actualLocalPrefix + serverPath.substring(localPrefixLen)); + } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/core/src/test/java/org/sonarsource/sonarlint/core/client/api/connected/ProjectBindingTests.java b/core/src/test/java/org/sonarsource/sonarlint/core/client/api/connected/ProjectBindingTests.java index 242208b5bb..f3a86b4c8d 100644 --- a/core/src/test/java/org/sonarsource/sonarlint/core/client/api/connected/ProjectBindingTests.java +++ b/core/src/test/java/org/sonarsource/sonarlint/core/client/api/connected/ProjectBindingTests.java @@ -50,4 +50,28 @@ void equals_and_hashCode_should_use_all_fields() { assertThat(projectBinding1.hashCode()).isNotEqualTo(projectBinding4.hashCode()); assertThat(projectBinding1.hashCode()).isEqualTo(projectBinding5.hashCode()); } + + @Test + void serverPathToIdePath_no_match_from_server_path() { + ProjectBinding projectBinding = new ProjectBinding("key", "sqPrefix", "localPrefix"); + assertThat(projectBinding.serverPathToIdePath("notSqPrefix/some/path")).isEmpty(); + } + + @Test + void serverPathToIdePath_general_case() { + ProjectBinding projectBinding = new ProjectBinding("key", "sq/path/prefix", "local/prefix"); + assertThat(projectBinding.serverPathToIdePath("sq/path/prefix/some/path")).hasValue("local/prefix/some/path"); + } + + @Test + void serverPathToIdePath_empty_local_path() { + ProjectBinding projectBinding = new ProjectBinding("key", "sq/path/prefix", ""); + assertThat(projectBinding.serverPathToIdePath("sq/path/prefix/some/path")).hasValue("some/path"); + } + + @Test + void serverPathToIdePath_empty_sq_path() { + ProjectBinding projectBinding = new ProjectBinding("key", "", "local/prefix"); + assertThat(projectBinding.serverPathToIdePath("some/path")).hasValue("local/prefix/some/path"); + } }