Skip to content

Commit 3503ba4

Browse files
committed
Refactor the loading of the Sonar Home Directory
1 parent 42f22ef commit 3503ba4

8 files changed

Lines changed: 56 additions & 34 deletions

File tree

its/it-tests/src/test/java/com/sonar/scanner/lib/it/PropertiesTest.java

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,22 +26,25 @@
2626
import java.nio.file.Files;
2727
import java.nio.file.Path;
2828
import java.nio.file.Paths;
29-
import java.util.HashMap;
3029
import java.util.Map;
3130
import org.junit.ClassRule;
31+
import org.junit.Rule;
3232
import org.junit.Test;
33+
import org.junit.rules.TemporaryFolder;
3334

3435
import static org.assertj.core.api.Assertions.assertThat;
3536

3637
public class PropertiesTest {
3738
@ClassRule
3839
public static final OrchestratorRule ORCHESTRATOR = ScannerJavaLibraryTestSuite.ORCHESTRATOR;
3940

41+
@Rule
42+
public TemporaryFolder temp = new TemporaryFolder();
43+
4044
@Test
4145
public void testRuntimeEnvironmentPassedAsUserAgent() throws IOException {
4246
SimpleScanner scanner = new SimpleScanner();
43-
Map<String, String> params = new HashMap<>();
44-
BuildResult buildResult = scanner.executeSimpleProject(project("js-sample"), ORCHESTRATOR.getServer().getUrl(), params, Map.of());
47+
BuildResult buildResult = scanner.executeSimpleProject(project("js-sample"), ORCHESTRATOR.getServer().getUrl(), Map.of(), Map.of());
4548
assertThat(buildResult.getLastStatus()).isZero();
4649
assertThat(buildResult.getLogs()).contains("2 files indexed");
4750

@@ -53,13 +56,32 @@ public void testRuntimeEnvironmentPassedAsUserAgent() throws IOException {
5356
@Test
5457
public void passConfigurationUsingEnvVariables() throws IOException {
5558
SimpleScanner scanner = new SimpleScanner();
56-
Map<String, String> params = new HashMap<>();
57-
BuildResult buildResult = scanner.executeSimpleProject(project("js-sample"), ORCHESTRATOR.getServer().getUrl(), params, Map.of("SONAR_SCANNER_JSON_PARAMS", "{\"sonar.exclusions\": \"**/Hello.js\"}"));
59+
BuildResult buildResult = scanner.executeSimpleProject(project("js-sample"), ORCHESTRATOR.getServer().getUrl(), Map.of(), Map.of("SONAR_SCANNER_JSON_PARAMS", "{\"sonar.exclusions\": \"**/Hello.js\"}"));
5860
assertThat(buildResult.getLastStatus()).isZero();
5961

6062
assertThat(buildResult.getLogs()).contains("1 file indexed");
6163
}
6264

65+
@Test
66+
public void overrideHomeDirectoryWithEnv() throws IOException {
67+
var userHome = temp.newFolder();
68+
SimpleScanner scanner = new SimpleScanner();
69+
BuildResult buildResult = scanner.executeSimpleProject(project("js-sample"), ORCHESTRATOR.getServer().getUrl(), Map.of(), Map.of("SONAR_USER_HOME", userHome.getAbsolutePath()));
70+
assertThat(buildResult.getLastStatus()).isZero();
71+
72+
assertThat(userHome.toPath().resolve("cache")).isDirectoryRecursivelyContaining(("glob:**/*scanner-engine*.jar"));
73+
}
74+
75+
@Test
76+
public void overrideHomeDirectoryWithProps() throws IOException {
77+
var userHome = temp.newFolder();
78+
SimpleScanner scanner = new SimpleScanner();
79+
BuildResult buildResult = scanner.executeSimpleProject(project("js-sample"), ORCHESTRATOR.getServer().getUrl(), Map.of("sonar.userHome", userHome.getAbsolutePath()), Map.of());
80+
assertThat(buildResult.getLastStatus()).isZero();
81+
82+
assertThat(userHome.toPath().resolve("cache")).isDirectoryRecursivelyContaining(("glob:**/*scanner-engine*.jar"));
83+
}
84+
6385
private static Path project(String projectName) {
6486
return Paths.get("..", "projects", projectName);
6587
}

lib/src/main/java/org/sonarsource/scanner/lib/EnvironmentConfig.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ public class EnvironmentConfig {
3535
private static final String SONARQUBE_SCANNER_PARAMS = "SONARQUBE_SCANNER_PARAMS";
3636
private static final String GENERIC_ENV_PREFIX = "SONAR_SCANNER_";
3737
private static final String SONAR_HOST_URL_ENV_VAR = "SONAR_HOST_URL";
38+
private static final String SONAR_USER_HOME_ENV_VAR = "SONAR_USER_HOME";
3839

3940
private EnvironmentConfig() {
4041
// only static methods
@@ -47,6 +48,7 @@ public static Map<String, String> load(LogOutput logger) {
4748
static Map<String, String> load(Map<String, String> env, LogOutput logger) {
4849
var loadedProps = new HashMap<String, String>();
4950
Optional.ofNullable(env.get(SONAR_HOST_URL_ENV_VAR)).ifPresent(url -> loadedProps.put(ScannerProperties.HOST_URL, url));
51+
Optional.ofNullable(env.get(SONAR_USER_HOME_ENV_VAR)).ifPresent(path -> loadedProps.put(ScannerProperties.SONAR_USER_HOME, path));
5052
env.forEach((key, value) -> {
5153
if (!key.equals(SONAR_SCANNER_JSON_PARAMS) && key.startsWith(GENERIC_ENV_PREFIX)) {
5254
processEnvVariable(key, value, loadedProps, logger);

lib/src/main/java/org/sonarsource/scanner/lib/ScannerProperties.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,18 @@
2727
*/
2828
public interface ScannerProperties {
2929
/**
30-
* HTTP URL of Sonar server, "http://localhost:9000" by default
30+
* URL of the Sonar server, default to SonarCloud
3131
*/
3232
String HOST_URL = "sonar.host.url";
3333

3434
/**
3535
* Working directory containing generated reports and temporary data.
3636
*/
3737
String WORK_DIR = "sonar.working.directory";
38-
38+
39+
/**
40+
* Base dir for various locations (cache, SSL, …). Default to ~/.sonar
41+
*/
42+
String SONAR_USER_HOME = "sonar.userHome";
43+
3944
}

lib/src/main/java/org/sonarsource/scanner/lib/internal/JarDownloaderFactory.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ class JarDownloaderFactory {
3737

3838
JarDownloader create() {
3939
FileCache fileCache = new FileCacheBuilder(logger)
40-
.setUserHome(userHome)
40+
.setSonarUserHome(userHome)
4141
.build();
4242
BootstrapIndexDownloader bootstrapIndexDownloader = new BootstrapIndexDownloader(serverConnection, logger);
4343
JarDownloader.ScannerFileDownloader scannerFileDownloader = new JarDownloader.ScannerFileDownloader(serverConnection);

lib/src/main/java/org/sonarsource/scanner/lib/internal/cache/FileCacheBuilder.java

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -19,41 +19,32 @@
1919
*/
2020
package org.sonarsource.scanner.lib.internal.cache;
2121

22-
import java.io.File;
22+
import java.nio.file.Path;
23+
import java.nio.file.Paths;
2324
import javax.annotation.Nullable;
2425

2526
public class FileCacheBuilder {
2627
private final Logger logger;
27-
private File userHome;
28+
private Path sonarUserHome;
2829

2930
public FileCacheBuilder(Logger logger) {
3031
this.logger = logger;
3132
}
3233

33-
public FileCacheBuilder setUserHome(File d) {
34-
this.userHome = d;
35-
return this;
36-
}
37-
38-
public FileCacheBuilder setUserHome(@Nullable String path) {
39-
this.userHome = (path == null) ? null : new File(path);
34+
public FileCacheBuilder setSonarUserHome(@Nullable String userHomeProperty) {
35+
this.sonarUserHome = (userHomeProperty == null) ? null : Paths.get(userHomeProperty);
4036
return this;
4137
}
4238

4339
public FileCache build() {
44-
if (userHome == null) {
45-
userHome = findHome();
40+
if (sonarUserHome == null) {
41+
sonarUserHome = findDefaultHome();
4642
}
47-
File cacheDir = new File(userHome, "cache");
48-
return FileCache.create(cacheDir.toPath(), logger);
43+
var cacheDir = sonarUserHome.resolve("cache");
44+
return FileCache.create(cacheDir, logger);
4945
}
5046

51-
private static File findHome() {
52-
String path = System.getenv("SONAR_USER_HOME");
53-
if (path == null) {
54-
// Default
55-
path = System.getProperty("user.home") + File.separator + ".sonar";
56-
}
57-
return new File(path);
47+
private static Path findDefaultHome() {
48+
return Paths.get("").resolve(".sonar");
5849
}
5950
}

lib/src/test/java/org/sonarsource/scanner/lib/EnvironmentConfigTest.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,12 @@ class EnvironmentConfigTest {
3737
@Test
3838
void shouldProcessSpecificEnvVariables() {
3939
var inputProperties = EnvironmentConfig.load(
40-
Map.of("SONAR_HOST_URL", "http://foo"), logOutput);
40+
Map.of("SONAR_HOST_URL", "http://foo",
41+
"SONAR_USER_HOME", "my/user/home"), logOutput);
4142

4243
assertThat(inputProperties).containsOnly(
43-
entry("sonar.host.url", "http://foo"));
44+
entry("sonar.host.url", "http://foo"),
45+
entry("sonar.userHome", "my/user/home"));
4446
}
4547

4648
@Test

lib/src/test/java/org/sonarsource/scanner/lib/internal/cache/FileCacheBuilderTest.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public class FileCacheBuilderTest {
3838
@Test
3939
public void setUserHome() throws Exception {
4040
File userHome = temp.newFolder();
41-
FileCache cache = new FileCacheBuilder(mock(Logger.class)).setUserHome(userHome).build();
41+
FileCache cache = new FileCacheBuilder(mock(Logger.class)).setSonarUserHome(userHome.getAbsolutePath()).build();
4242

4343
assertThat(cache.getDir()).isDirectory().exists();
4444
assertThat(cache.getDir().getName()).isEqualTo("cache");
@@ -47,7 +47,7 @@ public void setUserHome() throws Exception {
4747

4848
@Test
4949
public void user_home_property_can_be_null() {
50-
FileCache cache = new FileCacheBuilder(mock(Logger.class)).setUserHome((String) null).build();
50+
FileCache cache = new FileCacheBuilder(mock(Logger.class)).setSonarUserHome((String) null).build();
5151

5252
// does not fail. It uses default path or env variable
5353
assertThat(cache.getDir()).isDirectory().exists();
@@ -62,7 +62,7 @@ public void user_home_property_can_be_a_symlink() throws IOException {
6262
symlink.delete();
6363
Files.createSymbolicLink(symlink.toPath(), realSonarHome.toPath());
6464

65-
FileCache cache = new FileCacheBuilder(mock(Logger.class)).setUserHome(symlink).build();
65+
FileCache cache = new FileCacheBuilder(mock(Logger.class)).setSonarUserHome(symlink.getAbsolutePath()).build();
6666

6767
assertThat(cache.getDir()).isDirectory().exists();
6868
assertThat(cache.getDir().getName()).isEqualTo("cache");

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@
112112
<dependency>
113113
<groupId>org.assertj</groupId>
114114
<artifactId>assertj-core</artifactId>
115-
<version>3.11.1</version>
115+
<version>3.24.2</version>
116116
</dependency>
117117
<dependency>
118118
<groupId>commons-codec</groupId>

0 commit comments

Comments
 (0)