diff options
author | Julien HENRY <julien.henry@sonarsource.com> | 2017-07-31 13:12:10 +0200 |
---|---|---|
committer | Julien HENRY <julien.henry@sonarsource.com> | 2017-08-04 14:58:16 +0200 |
commit | 75e47ba5a19b3d4ab901d2ed7a180714b141d580 (patch) | |
tree | 9f15f196571ed354b9a17e0a790734813d7493ed /sonar-scanner-engine | |
parent | 2183aa17c17e8cb7385bf1662a57368c0b2979fd (diff) | |
download | sonarqube-75e47ba5a19b3d4ab901d2ed7a180714b141d580.tar.gz sonarqube-75e47ba5a19b3d4ab901d2ed7a180714b141d580.zip |
Rework file indexing
* Drop cycle ModuleFileSystem -> FileIndexer -> ModuleFileSystem
* Ensure basedir is initialized once
* Drop useless FileSystemLogger, and log in ModuleFileSystemInitializer
Diffstat (limited to 'sonar-scanner-engine')
44 files changed, 421 insertions, 489 deletions
diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/analysis/AnalysisTempFolderProvider.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/analysis/AnalysisTempFolderProvider.java index 1c0ec317ad7..6114108cc26 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/analysis/AnalysisTempFolderProvider.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/analysis/AnalysisTempFolderProvider.java @@ -22,7 +22,6 @@ package org.sonar.scanner.analysis; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; - import org.picocontainer.ComponentLifecycle; import org.picocontainer.PicoContainer; import org.picocontainer.injectors.ProviderAdapter; @@ -37,7 +36,7 @@ public class AnalysisTempFolderProvider extends ProviderAdapter implements Compo public TempFolder provide(InputModuleHierarchy moduleHierarchy) { if (projectTempFolder == null) { - Path workingDir = moduleHierarchy.root().getWorkDir().toPath(); + Path workingDir = moduleHierarchy.root().getWorkDir(); Path tempDir = workingDir.normalize().resolve(TMP_NAME); try { Files.deleteIfExists(tempDir); diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/IssueTransition.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/IssueTransition.java index 8dffa1f7015..02bf0524150 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/IssueTransition.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/tracking/IssueTransition.java @@ -65,7 +65,7 @@ public class IssueTransition { localIssueTracking.init(); } - ScannerReportReader reader = new ScannerReportReader(reportPublisher.getReportDir()); + ScannerReportReader reader = new ScannerReportReader(reportPublisher.getReportDir().toFile()); int nbComponents = inputComponentStore.all().size(); if (nbComponents == 0) { diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/TaskResult.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/TaskResult.java index e5f17cbb443..d9f1e193a78 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/TaskResult.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/TaskResult.java @@ -73,7 +73,7 @@ public class TaskResult implements org.sonar.scanner.mediumtest.ScanTaskObserver } ReportPublisher reportPublisher = container.getComponentByType(ReportPublisher.class); - reader = new ScannerReportReader(reportPublisher.getReportDir()); + reader = new ScannerReportReader(reportPublisher.getReportDir().toFile()); if (!container.getComponentByType(AnalysisMode.class).isIssues()) { Metadata readMetadata = getReportReader().readMetadata(); int rootComponentRef = readMetadata.getRootComponentRef(); diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/AbstractPhaseExecutor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/AbstractPhaseExecutor.java index e4e5c81356e..c759111ae38 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/AbstractPhaseExecutor.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/AbstractPhaseExecutor.java @@ -28,7 +28,7 @@ import org.sonar.scanner.events.EventBus; import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader; import org.sonar.scanner.rule.QProfileVerifier; import org.sonar.scanner.scan.filesystem.DefaultModuleFileSystem; -import org.sonar.scanner.scan.filesystem.FileSystemLogger; +import org.sonar.scanner.scan.filesystem.FileIndexer; public abstract class AbstractPhaseExecutor { @@ -37,25 +37,25 @@ public abstract class AbstractPhaseExecutor { private final InitializersExecutor initializersExecutor; private final SensorsExecutor sensorsExecutor; private final SensorContext sensorContext; - private final FileSystemLogger fsLogger; private final DefaultModuleFileSystem fs; private final QProfileVerifier profileVerifier; private final IssueExclusionsLoader issueExclusionsLoader; private final InputModuleHierarchy hierarchy; + private final FileIndexer fileIndexer; public AbstractPhaseExecutor(InitializersExecutor initializersExecutor, PostJobsExecutor postJobsExecutor, SensorsExecutor sensorsExecutor, - SensorContext sensorContext, InputModuleHierarchy hierarchy, EventBus eventBus, FileSystemLogger fsLogger, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier, - IssueExclusionsLoader issueExclusionsLoader) { + SensorContext sensorContext, InputModuleHierarchy hierarchy, EventBus eventBus, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier, + IssueExclusionsLoader issueExclusionsLoader, FileIndexer fileIndexer) { this.postJobsExecutor = postJobsExecutor; this.initializersExecutor = initializersExecutor; this.sensorsExecutor = sensorsExecutor; this.sensorContext = sensorContext; this.eventBus = eventBus; - this.fsLogger = fsLogger; this.fs = fs; this.profileVerifier = profileVerifier; this.issueExclusionsLoader = issueExclusionsLoader; this.hierarchy = hierarchy; + this.fileIndexer = fileIndexer; } /** @@ -107,12 +107,11 @@ public abstract class AbstractPhaseExecutor { private void indexFs() { String stepName = "Index filesystem"; eventBus.fireEvent(new BatchStepEvent(stepName, true)); - fs.index(); + fileIndexer.index(); eventBus.fireEvent(new BatchStepEvent(stepName, false)); } private void executeInitializersPhase() { initializersExecutor.execute(); - fsLogger.log(); } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/IssuesPhaseExecutor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/IssuesPhaseExecutor.java index b82ca8961a7..50ef68ab33f 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/IssuesPhaseExecutor.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/IssuesPhaseExecutor.java @@ -29,7 +29,7 @@ import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader; import org.sonar.scanner.issue.tracking.IssueTransition; import org.sonar.scanner.rule.QProfileVerifier; import org.sonar.scanner.scan.filesystem.DefaultModuleFileSystem; -import org.sonar.scanner.scan.filesystem.FileSystemLogger; +import org.sonar.scanner.scan.filesystem.FileIndexer; import org.sonar.scanner.scan.report.IssuesReports; public final class IssuesPhaseExecutor extends AbstractPhaseExecutor { @@ -41,9 +41,9 @@ public final class IssuesPhaseExecutor extends AbstractPhaseExecutor { private final IssueTransition localIssueTracking; public IssuesPhaseExecutor(InitializersExecutor initializersExecutor, PostJobsExecutor postJobsExecutor, SensorsExecutor sensorsExecutor, SensorContext sensorContext, - EventBus eventBus, FileSystemLogger fsLogger, IssuesReports jsonReport, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier, - IssueExclusionsLoader issueExclusionsLoader, IssueTransition localIssueTracking, InputModuleHierarchy moduleHierarchy) { - super(initializersExecutor, postJobsExecutor, sensorsExecutor, sensorContext, moduleHierarchy, eventBus, fsLogger, fs, profileVerifier, issueExclusionsLoader); + EventBus eventBus, IssuesReports jsonReport, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier, + IssueExclusionsLoader issueExclusionsLoader, IssueTransition localIssueTracking, InputModuleHierarchy moduleHierarchy, FileIndexer fileIndexer) { + super(initializersExecutor, postJobsExecutor, sensorsExecutor, sensorContext, moduleHierarchy, eventBus, fs, profileVerifier, issueExclusionsLoader, fileIndexer); this.eventBus = eventBus; this.issuesReport = jsonReport; this.localIssueTracking = localIssueTracking; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PublishPhaseExecutor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PublishPhaseExecutor.java index 84ff4b4d4bc..e0c22ad936e 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PublishPhaseExecutor.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PublishPhaseExecutor.java @@ -28,7 +28,7 @@ import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader; import org.sonar.scanner.report.ReportPublisher; import org.sonar.scanner.rule.QProfileVerifier; import org.sonar.scanner.scan.filesystem.DefaultModuleFileSystem; -import org.sonar.scanner.scan.filesystem.FileSystemLogger; +import org.sonar.scanner.scan.filesystem.FileIndexer; import org.sonar.scanner.scm.ScmPublisher; public final class PublishPhaseExecutor extends AbstractPhaseExecutor { @@ -39,9 +39,9 @@ public final class PublishPhaseExecutor extends AbstractPhaseExecutor { private final ScmPublisher scm; public PublishPhaseExecutor(InitializersExecutor initializersExecutor, PostJobsExecutor postJobsExecutor, SensorsExecutor sensorsExecutor, SensorContext sensorContext, - EventBus eventBus, ReportPublisher reportPublisher, FileSystemLogger fsLogger, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier, - IssueExclusionsLoader issueExclusionsLoader, CpdExecutor cpdExecutor, ScmPublisher scm, InputModuleHierarchy hierarchy) { - super(initializersExecutor, postJobsExecutor, sensorsExecutor, sensorContext, hierarchy, eventBus, fsLogger, fs, profileVerifier, issueExclusionsLoader); + EventBus eventBus, ReportPublisher reportPublisher, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier, + IssueExclusionsLoader issueExclusionsLoader, CpdExecutor cpdExecutor, ScmPublisher scm, InputModuleHierarchy hierarchy, FileIndexer fileIndexer) { + super(initializersExecutor, postJobsExecutor, sensorsExecutor, sensorContext, hierarchy, eventBus, fs, profileVerifier, issueExclusionsLoader, fileIndexer); this.eventBus = eventBus; this.reportPublisher = reportPublisher; this.cpdExecutor = cpdExecutor; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ReportPublisher.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ReportPublisher.java index a909a9a4aca..84eeab591f4 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ReportPublisher.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ReportPublisher.java @@ -74,7 +74,7 @@ public class ReportPublisher implements Startable { private final ReportPublisherStep[] publishers; private final Server server; - private File reportDir; + private Path reportDir; private ScannerReportWriter writer; public ReportPublisher(Configuration settings, ScannerWsClient wsClient, Server server, AnalysisContextReportPublisher contextPublisher, @@ -91,8 +91,8 @@ public class ReportPublisher implements Startable { @Override public void start() { - reportDir = new File(moduleHierarchy.root().getWorkDir(), "scanner-report"); - writer = new ScannerReportWriter(reportDir); + reportDir = moduleHierarchy.root().getWorkDir().resolve("scanner-report"); + writer = new ScannerReportWriter(reportDir.toFile()); contextPublisher.init(writer); if (!analysisMode.isIssues() && !analysisMode.isMediumTest()) { @@ -110,7 +110,7 @@ public class ReportPublisher implements Startable { } } - public File getReportDir() { + public Path getReportDir() { return reportDir; } @@ -144,11 +144,11 @@ public class ReportPublisher implements Startable { publisher.publish(writer); } long stopTime = System.currentTimeMillis(); - LOG.info("Analysis report generated in {}ms, dir size={}", stopTime - startTime, FileUtils.byteCountToDisplaySize(FileUtils.sizeOfDirectory(reportDir))); + LOG.info("Analysis report generated in {}ms, dir size={}", stopTime - startTime, FileUtils.byteCountToDisplaySize(FileUtils.sizeOfDirectory(reportDir.toFile()))); startTime = System.currentTimeMillis(); - File reportZip = temp.newFile("batch-report", ".zip"); - ZipUtils.zipDir(reportDir, reportZip); + File reportZip = temp.newFile("scanner-report", ".zip"); + ZipUtils.zipDir(reportDir.toFile(), reportZip); stopTime = System.currentTimeMillis(); LOG.info("Analysis reports compressed in {}ms, zip size={}", stopTime - startTime, FileUtils.byteCountToDisplaySize(FileUtils.sizeOf(reportZip))); return reportZip; @@ -228,7 +228,7 @@ public class ReportPublisher implements Startable { } private void dumpMetadata(Map<String, String> metadata) { - Path file = moduleHierarchy.root().getWorkDir().toPath().resolve(METADATA_DUMP_FILENAME); + Path file = moduleHierarchy.root().getWorkDir().resolve(METADATA_DUMP_FILENAME); try (Writer output = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { for (Map.Entry<String, String> entry : metadata.entrySet()) { output.write(entry.getKey()); diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/DefaultInputModuleHierarchy.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/DefaultInputModuleHierarchy.java index 4cf6dcbcab8..46ae0a0e28c 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/DefaultInputModuleHierarchy.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/DefaultInputModuleHierarchy.java @@ -19,22 +19,19 @@ */ package org.sonar.scanner.scan; +import com.google.common.collect.ImmutableMultimap; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; - import javax.annotation.CheckForNull; import javax.annotation.concurrent.Immutable; - import org.sonar.api.batch.fs.InputModule; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.api.scan.filesystem.PathResolver; -import com.google.common.collect.ImmutableMultimap; - @Immutable public class DefaultInputModuleHierarchy implements InputModuleHierarchy { private final PathResolver pathResolver = new PathResolver(); @@ -111,8 +108,8 @@ public class DefaultInputModuleHierarchy implements InputModuleHierarchy { return null; } DefaultInputModule inputModule = (DefaultInputModule) module; - Path parentBaseDir = parent.getBaseDir().toPath(); - Path moduleBaseDir = inputModule.getBaseDir().toPath(); + Path parentBaseDir = parent.getBaseDir(); + Path moduleBaseDir = inputModule.getBaseDir(); return pathResolver.relativePath(parentBaseDir, moduleBaseDir); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ModuleScanContainer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ModuleScanContainer.java index dbb3862d831..d43666bf93f 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ModuleScanContainer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ModuleScanContainer.java @@ -60,7 +60,6 @@ import org.sonar.scanner.rule.RulesProfileProvider; import org.sonar.scanner.scan.filesystem.DefaultModuleFileSystem; import org.sonar.scanner.scan.filesystem.ExclusionFilters; import org.sonar.scanner.scan.filesystem.FileIndexer; -import org.sonar.scanner.scan.filesystem.FileSystemLogger; import org.sonar.scanner.scan.filesystem.InputFileBuilder; import org.sonar.scanner.scan.filesystem.LanguageDetection; import org.sonar.scanner.scan.filesystem.MetadataGeneratorProvider; @@ -124,7 +123,6 @@ public class ModuleScanContainer extends ComponentContainer { LanguageDetection.class, FileIndexer.class, InputFileBuilder.class, - FileSystemLogger.class, DefaultModuleFileSystem.class, ModuleFileSystemInitializer.class, QProfileVerifier.class, diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectLock.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectLock.java index d8af158590d..ff9265a7f59 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectLock.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectLock.java @@ -23,7 +23,6 @@ import java.io.IOException; import java.nio.channels.OverlappingFileLockException; import java.nio.file.Files; import java.nio.file.Path; - import org.picocontainer.Startable; import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.home.cache.DirectoryLock; @@ -33,7 +32,7 @@ public class ProjectLock implements Startable { private final DirectoryLock lock; public ProjectLock(InputModuleHierarchy moduleHierarchy) { - Path directory = moduleHierarchy.root().getWorkDir().toPath(); + Path directory = moduleHierarchy.root().getWorkDir(); try { if (!directory.toFile().exists()) { Files.createDirectories(directory); @@ -43,7 +42,7 @@ public class ProjectLock implements Startable { } this.lock = new DirectoryLock(directory.toAbsolutePath(), new Slf4jLogger()); } - + public void tryLock() { try { if (!lock.tryLock()) { diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/WorkDirectoryCleaner.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/WorkDirectoryCleaner.java index 277b230fd88..83a9e8650f3 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/WorkDirectoryCleaner.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/WorkDirectoryCleaner.java @@ -24,7 +24,6 @@ import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Iterator; - import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.core.util.FileUtils; import org.sonar.home.cache.DirectoryLock; @@ -33,7 +32,7 @@ public class WorkDirectoryCleaner { private final Path workDir; public WorkDirectoryCleaner(InputModuleHierarchy moduleHierarchy) { - workDir = moduleHierarchy.root().getWorkDir().toPath(); + workDir = moduleHierarchy.root().getWorkDir(); } public void execute() { diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultModuleFileSystem.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultModuleFileSystem.java index e01e5202401..c2eed43a108 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultModuleFileSystem.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/DefaultModuleFileSystem.java @@ -20,57 +20,28 @@ package org.sonar.scanner.scan.filesystem; import com.google.common.annotations.VisibleForTesting; -import java.io.File; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; -import org.apache.commons.lang.StringUtils; -import org.sonar.api.CoreProperties; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.config.Configuration; -import org.sonar.api.utils.MessageException; import org.sonar.scanner.analysis.DefaultAnalysisMode; import org.sonar.scanner.repository.ProjectRepositories; -/** - * @since 3.5 - */ public class DefaultModuleFileSystem extends DefaultFileSystem { - private String moduleKey; - private FileIndexer indexer; - private Configuration settings; - - private List<File> sourceDirsOrFiles = new ArrayList<>(); - private List<File> testDirsOrFiles = new ArrayList<>(); - private boolean initialized; - private Charset charset = null; - - public DefaultModuleFileSystem(ModuleInputComponentStore moduleInputFileCache, DefaultInputModule module, - Configuration settings, FileIndexer indexer, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode, + public DefaultModuleFileSystem(ModuleInputComponentStore moduleInputFileCache, DefaultInputModule module, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode, ProjectRepositories projectRepositories) { - super(initializer.baseDir(), moduleInputFileCache); - setFields(module, settings, indexer, initializer, mode, projectRepositories); + super(module.getBaseDir(), moduleInputFileCache); + setFields(module, initializer, mode, projectRepositories); } @VisibleForTesting - public DefaultModuleFileSystem(DefaultInputModule module, - Configuration settings, FileIndexer indexer, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode, - ProjectRepositories projectRepositories) { - super(initializer.baseDir().toPath()); - setFields(module, settings, indexer, initializer, mode, projectRepositories); + public DefaultModuleFileSystem(DefaultInputModule module, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode, ProjectRepositories projectRepositories) { + super(module.getBaseDir()); + setFields(module, initializer, mode, projectRepositories); } - private void setFields(DefaultInputModule module, - Configuration settings, FileIndexer indexer, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode, - ProjectRepositories projectRepositories) { - this.moduleKey = module.key(); - this.settings = settings; - this.indexer = indexer; - setWorkDir(initializer.workingDir()); - this.sourceDirsOrFiles = initializer.sources(); - this.testDirsOrFiles = initializer.tests(); + private void setFields(DefaultInputModule module, ModuleFileSystemInitializer initializer, DefaultAnalysisMode mode, ProjectRepositories projectRepositories) { + setWorkDir(module.getWorkDir()); + setEncoding(initializer.defaultEncoding()); // filter the files sensors have access to if (!mode.scanAllFiles()) { @@ -78,69 +49,4 @@ public class DefaultModuleFileSystem extends DefaultFileSystem { } } - public boolean isInitialized() { - return initialized; - } - - public String moduleKey() { - return moduleKey; - } - - public List<File> sources() { - return sourceDirsOrFiles; - } - - public List<File> tests() { - return testDirsOrFiles; - } - - @Override - public Charset encoding() { - if (charset == null) { - String encoding = settings.get(CoreProperties.ENCODING_PROPERTY).orElse(null); - if (StringUtils.isNotEmpty(encoding)) { - charset = Charset.forName(StringUtils.trim(encoding)); - } else { - charset = Charset.defaultCharset(); - } - } - return charset; - } - - @Override - public boolean isDefaultJvmEncoding() { - return !settings.hasKey(CoreProperties.ENCODING_PROPERTY); - } - - @Override - protected void doPreloadFiles() { - if (!initialized) { - throw MessageException.of("Accessing the filesystem before the Sensor phase is not supported. Please update your plugin."); - } - } - - public void index() { - if (initialized) { - throw MessageException.of("Module filesystem can only be indexed once"); - } - initialized = true; - indexer.index(this); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DefaultModuleFileSystem that = (DefaultModuleFileSystem) o; - return moduleKey.equals(that.moduleKey); - } - - @Override - public int hashCode() { - return moduleKey.hashCode(); - } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/FileIndexer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/FileIndexer.java index 3af3741e987..6e00933fbd5 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/FileIndexer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/FileIndexer.java @@ -20,7 +20,6 @@ package org.sonar.scanner.scan.filesystem; import com.google.common.util.concurrent.ThreadFactoryBuilder; -import java.io.File; import java.io.IOException; import java.nio.file.FileSystemLoopException; import java.nio.file.FileVisitOption; @@ -70,29 +69,34 @@ public class FileIndexer { private final DefaultInputModule module; private final BatchIdGenerator batchIdGenerator; private final InputComponentStore componentStore; + private final ModuleFileSystemInitializer moduleFileSystemInitializer; private ExecutorService executorService; private final List<Future<Void>> tasks; + private final DefaultModuleFileSystem defaultModuleFileSystem; private ProgressReport progressReport; public FileIndexer(BatchIdGenerator batchIdGenerator, InputComponentStore componentStore, DefaultInputModule module, ExclusionFilters exclusionFilters, - DefaultComponentTree componentTree, InputFileBuilder inputFileBuilder, InputFileFilter[] filters) { + DefaultComponentTree componentTree, InputFileBuilder inputFileBuilder, ModuleFileSystemInitializer initializer, DefaultModuleFileSystem defaultModuleFileSystem, + InputFileFilter[] filters) { this.batchIdGenerator = batchIdGenerator; this.componentStore = componentStore; this.module = module; this.componentTree = componentTree; this.inputFileBuilder = inputFileBuilder; + this.moduleFileSystemInitializer = initializer; + this.defaultModuleFileSystem = defaultModuleFileSystem; this.filters = filters; this.exclusionFilters = exclusionFilters; this.tasks = new ArrayList<>(); } public FileIndexer(BatchIdGenerator batchIdGenerator, InputComponentStore componentStore, DefaultInputModule module, ExclusionFilters exclusionFilters, - DefaultComponentTree componentTree, InputFileBuilder inputFileBuilder) { - this(batchIdGenerator, componentStore, module, exclusionFilters, componentTree, inputFileBuilder, new InputFileFilter[0]); + DefaultComponentTree componentTree, InputFileBuilder inputFileBuilder, ModuleFileSystemInitializer initializer, DefaultModuleFileSystem defaultModuleFileSystem) { + this(batchIdGenerator, componentStore, module, exclusionFilters, componentTree, inputFileBuilder, initializer, defaultModuleFileSystem, new InputFileFilter[0]); } - void index(DefaultModuleFileSystem fileSystem) { + public void index() { int threads = Math.max(1, Runtime.getRuntime().availableProcessors() - 1); this.executorService = Executors.newFixedThreadPool(threads, new ThreadFactoryBuilder().setNameFormat("FileIndexer-%d").build()); @@ -102,8 +106,8 @@ public class FileIndexer { Progress progress = new Progress(); - indexFiles(fileSystem, progress, fileSystem.sources(), InputFile.Type.MAIN); - indexFiles(fileSystem, progress, fileSystem.tests(), InputFile.Type.TEST); + indexFiles(moduleFileSystemInitializer.sources(), InputFile.Type.MAIN, progress); + indexFiles(moduleFileSystemInitializer.tests(), InputFile.Type.TEST, progress); waitForTasksToComplete(); @@ -132,13 +136,13 @@ public class FileIndexer { return count == 1 ? "file" : "files"; } - private void indexFiles(DefaultModuleFileSystem fileSystem, Progress progress, List<File> sources, InputFile.Type type) { + private void indexFiles(List<Path> sources, InputFile.Type type, Progress progress) { try { - for (File dirOrFile : sources) { - if (dirOrFile.isDirectory()) { - indexDirectory(fileSystem, progress, dirOrFile.toPath(), type); + for (Path dirOrFile : sources) { + if (dirOrFile.toFile().isDirectory()) { + indexDirectory(dirOrFile, type, progress); } else { - tasks.add(executorService.submit(() -> indexFile(fileSystem, progress, dirOrFile.toPath(), type))); + tasks.add(executorService.submit(() -> indexFile(dirOrFile, type, progress))); } } } catch (IOException e) { @@ -146,21 +150,20 @@ public class FileIndexer { } } - private void indexDirectory(final DefaultModuleFileSystem fileSystem, final Progress status, final Path dirToIndex, final InputFile.Type type) throws IOException { + private void indexDirectory(Path dirToIndex, InputFile.Type type, Progress progress) throws IOException { Files.walkFileTree(dirToIndex.normalize(), Collections.singleton(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, - new IndexFileVisitor(fileSystem, status, type)); + new IndexFileVisitor(type, progress)); } - private Void indexFile(DefaultModuleFileSystem fileSystem, Progress progress, Path sourceFile, InputFile.Type type) throws IOException { + private Void indexFile(Path sourceFile, InputFile.Type type, Progress progress) throws IOException { // get case of real file without resolving link Path realFile = sourceFile.toRealPath(LinkOption.NOFOLLOW_LINKS); - DefaultInputFile inputFile = inputFileBuilder.create(realFile, type, fileSystem.encoding()); + DefaultInputFile inputFile = inputFileBuilder.create(realFile, type); if (inputFile != null) { if (exclusionFilters.accept(inputFile, type) && accept(inputFile)) { - String parentRelativePath = getParentRelativePath(fileSystem, inputFile); + String parentRelativePath = getParentRelativePath(inputFile); synchronized (this) { - fileSystem.add(inputFile); - indexParentDir(fileSystem, inputFile, parentRelativePath); + indexParentDir(inputFile, parentRelativePath); progress.markAsIndexed(inputFile); } LOG.debug("'{}' indexed {}with language '{}'", inputFile.relativePath(), type == Type.TEST ? "as test " : "", inputFile.language()); @@ -172,31 +175,32 @@ public class FileIndexer { return null; } - private static String getParentRelativePath(DefaultModuleFileSystem fileSystem, InputFile inputFile) { + private String getParentRelativePath(InputFile inputFile) { Path parentDir = inputFile.path().getParent(); - String relativePath = new PathResolver().relativePath(fileSystem.baseDirPath(), parentDir); + String relativePath = PathResolver.relativePath(module.getBaseDir(), parentDir); if (relativePath == null) { throw new IllegalStateException("Failed to compute relative path of file: " + inputFile); } return relativePath; } - private void indexParentDir(DefaultModuleFileSystem fileSystem, InputFile inputFile, String parentRelativePath) { + private void indexParentDir(InputFile inputFile, String parentRelativePath) { DefaultInputDir inputDir = (DefaultInputDir) componentStore.getDir(module.key(), parentRelativePath); if (inputDir == null) { - inputDir = new DefaultInputDir(fileSystem.moduleKey(), parentRelativePath, batchIdGenerator.get()); - inputDir.setModuleBaseDir(fileSystem.baseDirPath()); - fileSystem.add(inputDir); + inputDir = new DefaultInputDir(module.key(), parentRelativePath, batchIdGenerator.get()); + inputDir.setModuleBaseDir(module.getBaseDir()); componentTree.index(inputDir, module); + defaultModuleFileSystem.add(inputDir); } componentTree.index(inputFile, inputDir); + defaultModuleFileSystem.add(inputFile); } private boolean accept(InputFile indexedFile) { // InputFileFilter extensions. Might trigger generation of metadata for (InputFileFilter filter : filters) { if (!filter.accept(indexedFile)) { - LOG.debug("'{}' excluded by {}", indexedFile.relativePath(), filter.getClass().getName()); + LOG.debug("'{}' excluded by {}", indexedFile.toString(), filter.getClass().getName()); return false; } } @@ -204,12 +208,10 @@ public class FileIndexer { } private class IndexFileVisitor implements FileVisitor<Path> { - private DefaultModuleFileSystem fileSystem; - private Progress status; - private Type type; + private final Progress status; + private final Type type; - IndexFileVisitor(DefaultModuleFileSystem fileSystem, Progress status, InputFile.Type type) { - this.fileSystem = fileSystem; + IndexFileVisitor(InputFile.Type type, Progress status) { this.status = status; this.type = type; } @@ -230,7 +232,7 @@ public class FileIndexer { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!Files.isHidden(file)) { - tasks.add(executorService.submit(() -> indexFile(fileSystem, status, file, type))); + tasks.add(executorService.submit(() -> indexFile(file, type, status))); } return FileVisitResult.CONTINUE; } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/FileSystemLogger.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/FileSystemLogger.java deleted file mode 100644 index 3fde8e4183a..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/FileSystemLogger.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.scanner.scan.filesystem; - -import com.google.common.annotations.VisibleForTesting; -import java.io.File; -import java.nio.charset.Charset; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.batch.ScannerSide; -import org.sonar.api.scan.filesystem.PathResolver; - -@ScannerSide -public class FileSystemLogger { - - private final DefaultModuleFileSystem fs; - - public FileSystemLogger(DefaultModuleFileSystem fs) { - this.fs = fs; - } - - public void log() { - doLog(LoggerFactory.getLogger(getClass())); - } - - @VisibleForTesting - void doLog(Logger logger) { - logDir(logger, "Base dir: ", fs.baseDir()); - logDir(logger, "Working dir: ", fs.workDir()); - logPaths(logger, "Source paths: ", fs.baseDir(), fs.sources()); - logPaths(logger, "Test paths: ", fs.baseDir(), fs.tests()); - logEncoding(logger, fs.encoding()); - } - - private void logEncoding(Logger logger, Charset charset) { - if (!fs.isDefaultJvmEncoding()) { - logger.info("Source encoding: {}, default locale: {}", charset.displayName(), Locale.getDefault()); - } else { - logger.warn("Source encoding is platform dependent ({}), default locale: {}", charset.displayName(), Locale.getDefault()); - } - } - - private static void logPaths(Logger logger, String label, File baseDir, List<File> paths) { - if (!paths.isEmpty()) { - PathResolver resolver = new PathResolver(); - StringBuilder sb = new StringBuilder(label); - for (Iterator<File> it = paths.iterator(); it.hasNext();) { - File file = it.next(); - String relativePathToBaseDir = resolver.relativePath(baseDir, file); - if (relativePathToBaseDir == null) { - sb.append(file); - } else if (StringUtils.isBlank(relativePathToBaseDir)) { - sb.append("."); - } else { - sb.append(relativePathToBaseDir); - } - if (it.hasNext()) { - sb.append(", "); - } - } - logger.info(sb.toString()); - } - } - - private static void logDir(Logger logger, String label, @Nullable File dir) { - if (dir != null) { - logger.info(label + dir.getAbsolutePath()); - } - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/InputComponentStore.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/InputComponentStore.java index 6726cba970b..ffc0b2f7a0b 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/InputComponentStore.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/InputComponentStore.java @@ -159,7 +159,7 @@ public class InputComponentStore { } private Path getProjectBaseDir() { - return ((DefaultInputModule) root).getBaseDir().toPath(); + return ((DefaultInputModule) root).getBaseDir(); } @CheckForNull diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/InputFileBuilder.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/InputFileBuilder.java index fe8d125a5e9..7913cb711f9 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/InputFileBuilder.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/InputFileBuilder.java @@ -19,7 +19,6 @@ */ package org.sonar.scanner.scan.filesystem; -import java.nio.charset.Charset; import java.nio.file.Path; import javax.annotation.CheckForNull; import org.slf4j.Logger; @@ -36,17 +35,17 @@ public class InputFileBuilder { private static final Logger LOG = LoggerFactory.getLogger(InputFileBuilder.class); private final String moduleKey; private final Path moduleBaseDir; - private final PathResolver pathResolver; private final LanguageDetection langDetection; private final BatchIdGenerator idGenerator; private final MetadataGenerator metadataGenerator; private final boolean preloadMetadata; + private final ModuleFileSystemInitializer moduleFileSystemInitializer; - public InputFileBuilder(DefaultInputModule module, PathResolver pathResolver, LanguageDetection langDetection, MetadataGenerator metadataGenerator, - BatchIdGenerator idGenerator, Configuration settings) { + public InputFileBuilder(DefaultInputModule module, LanguageDetection langDetection, MetadataGenerator metadataGenerator, + BatchIdGenerator idGenerator, Configuration settings, ModuleFileSystemInitializer moduleFileSystemInitializer) { + this.moduleFileSystemInitializer = moduleFileSystemInitializer; this.moduleKey = module.key(); - this.moduleBaseDir = module.definition().getBaseDir().toPath(); - this.pathResolver = pathResolver; + this.moduleBaseDir = module.getBaseDir(); this.langDetection = langDetection; this.metadataGenerator = metadataGenerator; this.idGenerator = idGenerator; @@ -54,8 +53,8 @@ public class InputFileBuilder { } @CheckForNull - DefaultInputFile create(Path file, InputFile.Type type, Charset defaultEncoding) { - String relativePath = pathResolver.relativePath(moduleBaseDir, file); + DefaultInputFile create(Path file, InputFile.Type type) { + String relativePath = PathResolver.relativePath(moduleBaseDir, file); if (relativePath == null) { LOG.warn("File '{}' is ignored. It is not located in module basedir '{}'.", file.toAbsolutePath(), moduleBaseDir); return null; @@ -67,7 +66,7 @@ public class InputFileBuilder { } DefaultIndexedFile indexedFile = new DefaultIndexedFile(moduleKey, moduleBaseDir, relativePath, type, language, idGenerator.get()); - DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> metadataGenerator.setMetadata(f, defaultEncoding)); + DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> metadataGenerator.setMetadata(f, moduleFileSystemInitializer.defaultEncoding())); if (language != null) { inputFile.setPublish(true); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializer.java index f13b39b5325..f5828172008 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializer.java @@ -20,86 +20,108 @@ package org.sonar.scanner.scan.filesystem; import java.io.File; +import java.nio.charset.Charset; +import java.nio.file.Path; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; - -import org.apache.commons.io.FileUtils; +import java.util.Locale; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; +import org.apache.commons.lang.StringUtils; +import org.sonar.api.CoreProperties; import org.sonar.api.batch.ScannerSide; import org.sonar.api.batch.bootstrap.ProjectDefinition; +import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.scan.filesystem.PathResolver; -import org.sonar.api.utils.TempFolder; +import org.sonar.api.utils.log.Logger; +import org.sonar.api.utils.log.Loggers; import static org.sonar.scanner.config.DefaultConfiguration.parseAsCsv; -/** - * @since 3.5 - */ @ScannerSide +@Immutable public class ModuleFileSystemInitializer { - private File baseDir; - private File workingDir; - private List<File> sourceDirsOrFiles = new ArrayList<>(); - private List<File> testDirsOrFiles = new ArrayList<>(); + private static final Logger LOG = Loggers.get(ModuleFileSystemInitializer.class); - public ModuleFileSystemInitializer(ProjectDefinition module, TempFolder tempUtils, PathResolver pathResolver) { - baseDir = module.getBaseDir(); - initWorkingDir(module, tempUtils); - initSources(module, pathResolver); - initTests(module, pathResolver); - } + private final List<Path> sourceDirsOrFiles; + private final List<Path> testDirsOrFiles; + private final Charset encoding; - private void initWorkingDir(ProjectDefinition module, TempFolder tempUtils) { - workingDir = module.getWorkDir(); - if (workingDir == null) { - workingDir = tempUtils.newDir("work"); - } else { - try { - FileUtils.forceMkdir(workingDir); - } catch (Exception e) { - throw new IllegalStateException("Fail to create working dir: " + workingDir.getAbsolutePath(), e); - } - } + public ModuleFileSystemInitializer(DefaultInputModule inputModule, ProjectDefinition module) { + logDir("Base dir: ", inputModule.getBaseDir()); + logDir("Working dir: ", inputModule.getWorkDir()); + sourceDirsOrFiles = initSources(module, inputModule.getBaseDir(), ProjectDefinition.SOURCES_PROPERTY, "Source paths: "); + testDirsOrFiles = initSources(module, inputModule.getBaseDir(), ProjectDefinition.TESTS_PROPERTY, "Test paths: "); + encoding = initEncoding(module); } - private void initSources(ProjectDefinition module, PathResolver pathResolver) { - String srcPropValue = module.properties().get(ProjectDefinition.SOURCES_PROPERTY); + private static List<Path> initSources(ProjectDefinition module, Path baseDir, String propertyKey, String logLabel) { + List<Path> result = new ArrayList<>(); + String srcPropValue = module.properties().get(propertyKey); if (srcPropValue != null) { - for (String sourcePath : parseAsCsv(ProjectDefinition.SOURCES_PROPERTY, srcPropValue)) { - File dirOrFile = pathResolver.relativeFile(module.getBaseDir(), sourcePath); + for (String sourcePath : parseAsCsv(propertyKey, srcPropValue)) { + File dirOrFile = PathResolver.relativeFile(module.getBaseDir(), sourcePath); if (dirOrFile.exists()) { - sourceDirsOrFiles.add(dirOrFile); + result.add(dirOrFile.toPath()); } } } + logPaths(logLabel, baseDir, result); + return result; } - private void initTests(ProjectDefinition module, PathResolver pathResolver) { - String testPropValue = module.properties().get(ProjectDefinition.TESTS_PROPERTY); - if (testPropValue != null) { - for (String testPath : parseAsCsv(ProjectDefinition.TESTS_PROPERTY, testPropValue)) { - File dirOrFile = pathResolver.relativeFile(module.getBaseDir(), testPath); - if (dirOrFile.exists()) { - testDirsOrFiles.add(dirOrFile); - } - } + private static Charset initEncoding(ProjectDefinition module) { + String encodingStr = module.properties().get(CoreProperties.ENCODING_PROPERTY); + Charset result; + if (StringUtils.isNotEmpty(encodingStr)) { + result = Charset.forName(StringUtils.trim(encodingStr)); + LOG.info("Source encoding: {}, default locale: {}", result.displayName(), Locale.getDefault()); + } else { + result = Charset.defaultCharset(); + LOG.warn("Source encoding is platform dependent ({}), default locale: {}", result.displayName(), Locale.getDefault()); } + return result; } - File baseDir() { - return baseDir; + List<Path> sources() { + return sourceDirsOrFiles; } - File workingDir() { - return workingDir; + List<Path> tests() { + return testDirsOrFiles; } - List<File> sources() { - return sourceDirsOrFiles; + public Charset defaultEncoding() { + return encoding; } - List<File> tests() { - return testDirsOrFiles; + private static void logPaths(String label, Path baseDir, List<Path> paths) { + if (!paths.isEmpty()) { + StringBuilder sb = new StringBuilder(label); + for (Iterator<Path> it = paths.iterator(); it.hasNext();) { + Path file = it.next(); + String relativePathToBaseDir = PathResolver.relativePath(baseDir, file); + if (relativePathToBaseDir == null) { + sb.append(file); + } else if (StringUtils.isBlank(relativePathToBaseDir)) { + sb.append("."); + } else { + sb.append(relativePathToBaseDir); + } + if (it.hasNext()) { + sb.append(", "); + } + } + LOG.info(sb.toString()); + } + } + + private static void logDir(String label, @Nullable Path dir) { + if (dir != null) { + LOG.info(label + dir.toAbsolutePath().toString()); + } } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/ScmConfiguration.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/ScmConfiguration.java index 73f29557bc0..ef380a0c74e 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/ScmConfiguration.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scm/ScmConfiguration.java @@ -19,9 +19,9 @@ */ package org.sonar.scanner.scm; +import com.google.common.base.Joiner; import java.util.LinkedHashMap; import java.util.Map; - import org.apache.commons.lang.StringUtils; import org.picocontainer.Startable; import org.sonar.api.CoreProperties; @@ -37,8 +37,6 @@ import org.sonar.api.config.Configuration; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; -import com.google.common.base.Joiner; - @Properties({ @Property( key = ScmConfiguration.FORCE_RELOAD_KEY, @@ -123,7 +121,7 @@ public final class ScmConfiguration implements Startable { private void autodetection() { for (ScmProvider installedProvider : providerPerKey.values()) { - if (installedProvider.supports(moduleHierarchy.root().getBaseDir())) { + if (installedProvider.supports(moduleHierarchy.root().getBaseDir().toFile())) { if (this.provider == null) { this.provider = installedProvider; } else { diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/analysis/AnalysisTempFolderProviderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/analysis/AnalysisTempFolderProviderTest.java index ce458c8bb3a..8b45a3637a9 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/analysis/AnalysisTempFolderProviderTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/analysis/AnalysisTempFolderProviderTest.java @@ -19,13 +19,8 @@ */ package org.sonar.scanner.analysis; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.io.File; import java.io.IOException; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -34,6 +29,10 @@ import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.api.utils.TempFolder; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class AnalysisTempFolderProviderTest { @Rule @@ -48,7 +47,7 @@ public class AnalysisTempFolderProviderTest { moduleHierarchy = mock(InputModuleHierarchy.class); DefaultInputModule module = mock(DefaultInputModule.class); when(moduleHierarchy.root()).thenReturn(module); - when(module.getWorkDir()).thenReturn(temp.getRoot()); + when(module.getWorkDir()).thenReturn(temp.getRoot().toPath()); } @Test diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnaryTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnaryTest.java index c3c8b131b6a..54a254b4333 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnaryTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnaryTest.java @@ -20,10 +20,13 @@ package org.sonar.scanner.bootstrap; import com.google.common.collect.Lists; +import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.List; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.sonar.api.BatchExtension; import org.sonar.api.batch.BuildBreaker; import org.sonar.api.batch.CheckProject; @@ -34,6 +37,7 @@ import org.sonar.api.batch.Phase; import org.sonar.api.batch.PostJob; import org.sonar.api.batch.Sensor; import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.postjob.PostJobContext; import org.sonar.api.batch.sensor.SensorDescriptor; @@ -49,6 +53,9 @@ import static org.mockito.Mockito.mock; public class ScannerExtensionDictionnaryTest { + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + private ScannerExtensionDictionnary newSelector(Object... extensions) { ComponentContainer iocContainer = new ComponentContainer(); for (Object extension : extensions) { @@ -232,12 +239,13 @@ public class ScannerExtensionDictionnaryTest { } @Test - public void checkProject() { + public void checkProject() throws IOException { BatchExtension ok = new CheckProjectOK(); BatchExtension ko = new CheckProjectKO(); ScannerExtensionDictionnary selector = newSelector(ok, ko); - List<BatchExtension> extensions = Lists.newArrayList(selector.select(BatchExtension.class, new DefaultInputModule("foo"), true, null)); + List<BatchExtension> extensions = Lists.newArrayList(selector.select(BatchExtension.class, + new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())), true, null)); assertThat(extensions).hasSize(1); assertThat(extensions.get(0)).isInstanceOf(CheckProjectOK.class); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/index/DefaultIndexTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/index/DefaultIndexTest.java index d7d16341d8f..235e14c2621 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/index/DefaultIndexTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/index/DefaultIndexTest.java @@ -19,10 +19,6 @@ */ package org.sonar.scanner.index; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.io.IOException; import java.util.Collections; import org.junit.Before; @@ -48,6 +44,10 @@ import org.sonar.scanner.scan.filesystem.InputComponentStore; import org.sonar.scanner.scan.measure.MeasureCache; import org.sonar.scanner.sensor.DefaultSensorStorage; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class DefaultIndexTest { @org.junit.Rule @@ -74,10 +74,16 @@ public class DefaultIndexTest { baseDir = temp.newFolder(); - ProjectDefinition rootDef = ProjectDefinition.create().setKey("project").setBaseDir(baseDir); - ProjectDefinition moduleADef = ProjectDefinition.create().setKey("moduleA").setBaseDir(new java.io.File(baseDir, "moduleA")); - ProjectDefinition moduleBDef = ProjectDefinition.create().setKey("moduleB").setBaseDir(new java.io.File(baseDir, "moduleB")); - ProjectDefinition moduleB1Def = ProjectDefinition.create().setKey("moduleB1").setBaseDir(new java.io.File(baseDir, "moduleB/moduleB1")); + ProjectDefinition rootDef = ProjectDefinition.create().setKey("project").setBaseDir(baseDir).setWorkDir(temp.newFolder()); + java.io.File moduleABaseDir = new java.io.File(baseDir, "moduleA"); + moduleABaseDir.mkdir(); + ProjectDefinition moduleADef = ProjectDefinition.create().setKey("moduleA").setBaseDir(moduleABaseDir).setWorkDir(temp.newFolder()); + java.io.File moduleBBaseDir = new java.io.File(baseDir, "moduleB"); + moduleBBaseDir.mkdir(); + ProjectDefinition moduleBDef = ProjectDefinition.create().setKey("moduleB").setBaseDir(moduleBBaseDir).setWorkDir(temp.newFolder()); + java.io.File moduleB1BaseDir = new java.io.File(baseDir, "moduleB/moduleB1"); + moduleB1BaseDir.mkdir(); + ProjectDefinition moduleB1Def = ProjectDefinition.create().setKey("moduleB1").setBaseDir(moduleB1BaseDir).setWorkDir(temp.newFolder()); rootDef.addSubProject(moduleADef); rootDef.addSubProject(moduleBDef); @@ -96,8 +102,8 @@ public class DefaultIndexTest { } @Test - public void shouldGetHierarchy() { - InputComponent component = new DefaultInputModule("module1"); + public void shouldGetHierarchy() throws IOException { + InputComponent component = new DefaultInputModule(ProjectDefinition.create().setKey("module1").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); InputFile file1 = new TestInputFileBuilder("module1", "src/org/foo/Bar.java").build(); when(componentStore.getByKey("module1")).thenReturn(component); @@ -113,10 +119,12 @@ public class DefaultIndexTest { } @Test - public void shouldTransformToResource() { + public void shouldTransformToResource() throws IOException { DefaultInputModule component = new DefaultInputModule(ProjectDefinition.create() .setKey("module1") - .setProperty(CoreProperties.PROJECT_BRANCH_PROPERTY, "branch1"), 1); + .setProperty(CoreProperties.PROJECT_BRANCH_PROPERTY, "branch1") + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()), 1); InputFile file1 = new TestInputFileBuilder("module1", "src/org/foo/Bar.java").build(); InputDir dir = new DefaultInputDir("module1", "src"); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DeprecatedIssueAdapterForFilterTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DeprecatedIssueAdapterForFilterTest.java index 19585cbab08..39d5571e8a6 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DeprecatedIssueAdapterForFilterTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DeprecatedIssueAdapterForFilterTest.java @@ -19,8 +19,12 @@ */ package org.sonar.scanner.issue; +import java.io.IOException; import java.util.Date; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.issue.Issue; import org.sonar.api.rule.RuleKey; @@ -35,13 +39,16 @@ import static org.mockito.Mockito.when; public class DeprecatedIssueAdapterForFilterTest { + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + private static final String PROJECT_KEY = "foo"; private static final Date ANALYSIS_DATE = new Date(); private static final String COMPONENT_KEY = "foo:src/Foo.java"; @Test - public void improve_coverage() { - DefaultInputModule module = new DefaultInputModule(PROJECT_KEY); + public void improve_coverage() throws IOException { + DefaultInputModule module = new DefaultInputModule(ProjectDefinition.create().setKey(PROJECT_KEY).setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); ProjectAnalysisInfo projectAnalysisInfo = mock(ProjectAnalysisInfo.class); when(projectAnalysisInfo.analysisDate()).thenReturn(ANALYSIS_DATE); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuableFactoryTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuableFactoryTest.java index 27084d321a6..e5cd4fc19ef 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuableFactoryTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuableFactoryTest.java @@ -19,7 +19,11 @@ */ package org.sonar.scanner.issue; +import java.io.IOException; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.issue.Issuable; @@ -30,7 +34,8 @@ import static org.mockito.Mockito.mock; public class IssuableFactoryTest { - ModuleIssues moduleIssues = mock(ModuleIssues.class); + @Rule + public TemporaryFolder temp = new TemporaryFolder(); @Test public void file_should_be_issuable() { @@ -42,9 +47,10 @@ public class IssuableFactoryTest { } @Test - public void project_should_be_issuable() { + public void project_should_be_issuable() throws IOException { IssuableFactory factory = new IssuableFactory(mock(DefaultSensorContext.class)); - Issuable issuable = factory.loadPerspective(Issuable.class, new DefaultInputModule("foo")); + Issuable issuable = factory.loadPerspective(Issuable.class, + new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()))); assertThat(issuable).isNotNull(); assertThat(issuable.issues()).isEmpty(); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/SourceHashHolderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/SourceHashHolderTest.java index dde76bf6722..3f4b49ad007 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/SourceHashHolderTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/tracking/SourceHashHolderTest.java @@ -19,17 +19,9 @@ */ package org.sonar.scanner.issue.tracking; -import static org.apache.commons.codec.digest.DigestUtils.md5Hex; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.util.Collections; - import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; @@ -42,6 +34,12 @@ import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.fs.internal.DefaultInputModule; +import static org.apache.commons.codec.digest.DigestUtils.md5Hex; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + public class SourceHashHolderTest { @Rule @@ -57,7 +55,7 @@ public class SourceHashHolderTest { @Before public void setUp() throws Exception { - def = mock(ProjectDefinition.class); + def = ProjectDefinition.create().setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()); lastSnapshots = mock(ServerLineHashesLoader.class); file = mock(DefaultInputFile.class); ioFile = temp.newFile(); @@ -86,7 +84,7 @@ public class SourceHashHolderTest { public void should_lazy_load_reference_hashes_when_status_changed() throws Exception { final String source = "source"; FileUtils.write(ioFile, source, StandardCharsets.UTF_8); - when(def.getKeyWithBranch()).thenReturn("foo"); + def.setKey("foo"); when(file.relativePath()).thenReturn("src/Foo.java"); String key = "foo:src/Foo.java"; when(file.status()).thenReturn(InputFile.Status.CHANGED); @@ -103,8 +101,8 @@ public class SourceHashHolderTest { public void should_lazy_load_reference_hashes_when_status_changed_on_branch() throws Exception { final String source = "source"; FileUtils.write(ioFile, source, StandardCharsets.UTF_8); - when(def.getKeyWithBranch()).thenReturn("foo:myBranch"); - when(def.properties()).thenReturn(Collections.singletonMap(CoreProperties.PROJECT_BRANCH_PROPERTY, "myBranch")); + def.setKey("foo"); + def.setProperty(CoreProperties.PROJECT_BRANCH_PROPERTY, "myBranch"); when(file.relativePath()).thenReturn("src/Foo.java"); String key = "foo:myBranch:src/Foo.java"; when(file.status()).thenReturn(InputFile.Status.CHANGED); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/PostJobsExecutorTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/PostJobsExecutorTest.java index 488d9694763..d3e87cdc613 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/PostJobsExecutorTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/PostJobsExecutorTest.java @@ -19,11 +19,15 @@ */ package org.sonar.scanner.phases; +import java.io.IOException; import java.util.Arrays; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.PostJob; import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.resources.Project; import org.sonar.scanner.bootstrap.ScannerExtensionDictionnary; @@ -36,16 +40,20 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class PostJobsExecutorTest { - PostJobsExecutor executor; + @Rule + public TemporaryFolder temp = new TemporaryFolder(); - DefaultInputModule module = new DefaultInputModule("project"); - ScannerExtensionDictionnary selector = mock(ScannerExtensionDictionnary.class); - PostJob job1 = mock(PostJob.class); - PostJob job2 = mock(PostJob.class); - SensorContext context = mock(SensorContext.class); + private PostJobsExecutor executor; + + private DefaultInputModule module; + private ScannerExtensionDictionnary selector = mock(ScannerExtensionDictionnary.class); + private PostJob job1 = mock(PostJob.class); + private PostJob job2 = mock(PostJob.class); + private SensorContext context = mock(SensorContext.class); @Before - public void setUp() { + public void setUp() throws IOException { + module = new DefaultInputModule(ProjectDefinition.create().setKey("project").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); executor = new PostJobsExecutor(selector, module, mock(EventBus.class)); } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/SensorsExecutorTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/SensorsExecutorTest.java index dcea19af285..2a68b02aa16 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/SensorsExecutorTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/SensorsExecutorTest.java @@ -19,15 +19,8 @@ */ package org.sonar.scanner.phases; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.io.IOException; import java.util.Collections; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -43,6 +36,12 @@ import org.sonar.scanner.bootstrap.ScannerExtensionDictionnary; import org.sonar.scanner.events.EventBus; import org.sonar.scanner.sensor.SensorStrategy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class SensorsExecutorTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -86,8 +85,8 @@ public class SensorsExecutorTest { when(selector.selectSensors(any(DefaultInputModule.class), eq(false))).thenReturn(Collections.singleton(perModuleSensor)); when(selector.selectSensors(any(DefaultInputModule.class), eq(true))).thenReturn(Collections.singleton(globalSensor)); - ProjectDefinition childDef = ProjectDefinition.create().setKey("sub").setBaseDir(temp.newFolder()); - ProjectDefinition rootDef = ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()); + ProjectDefinition childDef = ProjectDefinition.create().setKey("sub").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()); + ProjectDefinition rootDef = ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()); DefaultInputModule rootModule = TestInputFileBuilder.newDefaultInputModule(rootDef); DefaultInputModule subModule = TestInputFileBuilder.newDefaultInputModule(childDef); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/profiling/PhasesSumUpTimeProfilerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/profiling/PhasesSumUpTimeProfilerTest.java index b2853116007..a07f07a27c9 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/profiling/PhasesSumUpTimeProfilerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/profiling/PhasesSumUpTimeProfilerTest.java @@ -20,6 +20,7 @@ package org.sonar.scanner.profiling; import com.google.common.collect.Maps; +import java.io.IOException; import java.util.List; import java.util.Map; import org.junit.Before; @@ -67,7 +68,7 @@ public class PhasesSumUpTimeProfilerTest { } @Test - public void testSimpleProject() throws InterruptedException { + public void testSimpleProject() throws Exception { final Project project = mockProject("my:project", true); @@ -80,7 +81,7 @@ public class PhasesSumUpTimeProfilerTest { } @Test - public void testMultimoduleProject() throws InterruptedException { + public void testMultimoduleProject() throws Exception { final Project project = mockProject("project root", true); final Project moduleA = mockProject("moduleA", false); final Project moduleB = mockProject("moduleB", false); @@ -132,8 +133,8 @@ public class PhasesSumUpTimeProfilerTest { } } - private Project mockProject(String name, boolean isRoot) { - return new Project(new DefaultInputModule(ProjectDefinition.create().setName(name).setKey(name))); + private Project mockProject(String name, boolean isRoot) throws IOException { + return new Project(new DefaultInputModule(ProjectDefinition.create().setName(name).setKey(name).setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()))); } private void fakeAnalysis(PhasesSumUpTimeProfiler profiler, final Project module) { diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/AnalysisContextReportPublisherTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/AnalysisContextReportPublisherTest.java index 77fc6206b24..68a39bf1f1f 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/AnalysisContextReportPublisherTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/AnalysisContextReportPublisherTest.java @@ -99,7 +99,7 @@ public class AnalysisContextReportPublisherTest { ScannerReportWriter writer = new ScannerReportWriter(temp.newFolder()); publisher.init(writer); - publisher.dumpModuleSettings(new DefaultInputModule("foo")); + publisher.dumpModuleSettings(new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()))); assertThat(writer.getFileStructure().analysisLog()).doesNotExist(); } @@ -126,7 +126,7 @@ public class AnalysisContextReportPublisherTest { when(projectRepos.moduleExists("foo")).thenReturn(true); when(projectRepos.settings("foo")).thenReturn(ImmutableMap.of(COM_FOO, "bar", SONAR_SKIP, "true")); - publisher.dumpModuleSettings(new DefaultInputModule("foo")); + publisher.dumpModuleSettings(new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()))); String content = FileUtils.readFileToString(writer.getFileStructure().analysisLog()); assertThat(content).doesNotContain(COM_FOO); @@ -148,6 +148,8 @@ public class AnalysisContextReportPublisherTest { assertThat(content).doesNotContain(SONAR_SKIP); publisher.dumpModuleSettings(new DefaultInputModule(ProjectDefinition.create() + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()) .setProperty("sonar.projectKey", "foo") .setProperty(COM_FOO, "bar") .setProperty(SONAR_SKIP, "true"))); @@ -174,6 +176,8 @@ public class AnalysisContextReportPublisherTest { assertThat(content).containsSequence(BIZ, FOO); publisher.dumpModuleSettings(new DefaultInputModule(ProjectDefinition.create() + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()) .setProperty("sonar.projectKey", "foo") .setProperty("env." + FOO, "BAR"))); @@ -191,6 +195,8 @@ public class AnalysisContextReportPublisherTest { assertThat(writer.getFileStructure().analysisLog()).exists(); publisher.dumpModuleSettings(new DefaultInputModule(ProjectDefinition.create() + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()) .setProperty("sonar.projectKey", "foo") .setProperty("sonar.projectKey", "foo") .setProperty("sonar.login", "my_token") @@ -226,10 +232,14 @@ public class AnalysisContextReportPublisherTest { publisher.init(writer); DefaultInputModule module = new DefaultInputModule(ProjectDefinition.create() + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()) .setProperty("sonar.projectKey", "foo") .setProperty(SONAR_SKIP, "true")); DefaultInputModule parent = new DefaultInputModule(ProjectDefinition.create() + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()) .setProperty("sonar.projectKey", "parent") .setProperty(SONAR_SKIP, "true")); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ComponentsPublisherTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ComponentsPublisherTest.java index 2f1a13d1d94..9170a07fbac 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ComponentsPublisherTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ComponentsPublisherTest.java @@ -77,13 +77,17 @@ public class ComponentsPublisherTest { .setKey("foo") .setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, "1.0") .setName("Root project") - .setDescription("Root description"); + .setDescription("Root description") + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()); DefaultInputModule root = new DefaultInputModule(rootDef, 1); ProjectDefinition module1Def = ProjectDefinition.create() .setKey("module1") .setName("Module1") - .setDescription("Module description"); + .setDescription("Module description") + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()); rootDef.addSubProject(module1Def); DefaultInputModule module1 = new DefaultInputModule(module1Def, 2); @@ -137,7 +141,7 @@ public class ComponentsPublisherTest { } @Test - public void should_skip_dir_without_published_files() { + public void should_skip_dir_without_published_files() throws IOException { ProjectAnalysisInfo projectAnalysisInfo = mock(ProjectAnalysisInfo.class); when(projectAnalysisInfo.analysisDate()).thenReturn(DateUtils.parseDate("2012-12-12")); @@ -145,7 +149,9 @@ public class ComponentsPublisherTest { .setKey("foo") .setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, "1.0") .setName("Root project") - .setDescription("Root description"); + .setDescription("Root description") + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()); DefaultInputModule root = new DefaultInputModule(rootDef, 1); moduleHierarchy = mock(InputModuleHierarchy.class); @@ -196,12 +202,16 @@ public class ComponentsPublisherTest { ProjectDefinition rootDef = ProjectDefinition.create() .setKey("foo") - .setDescription("Root description"); + .setDescription("Root description") + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()); DefaultInputModule root = new DefaultInputModule(rootDef, 1); ProjectDefinition module1Def = ProjectDefinition.create() .setKey("module1") - .setDescription("Module description"); + .setDescription("Module description") + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()); rootDef.addSubProject(module1Def); DefaultInputModule module1 = new DefaultInputModule(module1Def, 2); @@ -261,14 +271,18 @@ public class ComponentsPublisherTest { .setProperty(CoreProperties.PROJECT_BRANCH_PROPERTY, "my_branch") .setName("Root project") .setProperty(CoreProperties.LINKS_HOME_PAGE, "http://home") - .setDescription("Root description"); + .setDescription("Root description") + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()); DefaultInputModule root = new DefaultInputModule(rootDef, 1); ProjectDefinition module1Def = ProjectDefinition.create() .setKey("module1") .setName("Module1") .setProperty(CoreProperties.LINKS_CI, "http://ci") - .setDescription("Module description"); + .setDescription("Module description") + .setBaseDir(temp.newFolder()) + .setWorkDir(temp.newFolder()); rootDef.addSubProject(module1Def); DefaultInputModule module1 = new DefaultInputModule(module1Def, 2); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/MetadataPublisherTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/MetadataPublisherTest.java index 3d3dddfe821..b804fd08df2 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/MetadataPublisherTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/MetadataPublisherTest.java @@ -19,15 +19,9 @@ */ package org.sonar.scanner.report; -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.entry; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.io.File; +import java.io.IOException; import java.util.Date; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -46,6 +40,12 @@ import org.sonar.scanner.protocol.output.ScannerReportWriter; import org.sonar.scanner.rule.ModuleQProfiles; import org.sonar.scanner.rule.QProfile; +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class MetadataPublisherTest { @Rule @@ -60,7 +60,7 @@ public class MetadataPublisherTest { private InputModuleHierarchy inputModuleHierarchy; @Before - public void prepare() { + public void prepare() throws IOException { projectAnalysisInfo = mock(ProjectAnalysisInfo.class); cpdSettings = mock(CpdSettings.class); when(projectAnalysisInfo.analysisDate()).thenReturn(new Date(1234567L)); @@ -69,8 +69,8 @@ public class MetadataPublisherTest { createPublisher(ProjectDefinition.create().setKey("foo")); } - private void createPublisher(ProjectDefinition def) { - rootModule = new DefaultInputModule(def, TestInputFileBuilder.nextBatchId()); + private void createPublisher(ProjectDefinition def) throws IOException { + rootModule = new DefaultInputModule(def.setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()), TestInputFileBuilder.nextBatchId()); inputModuleHierarchy = mock(InputModuleHierarchy.class); when(inputModuleHierarchy.root()).thenReturn(rootModule); underTest = new MetadataPublisher(projectAnalysisInfo, inputModuleHierarchy, settings.asConfig(), qProfiles, cpdSettings); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ReportPublisherTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ReportPublisherTest.java index e4d6c615339..2a2651e162f 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ReportPublisherTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/ReportPublisherTest.java @@ -79,9 +79,9 @@ public class ReportPublisherTest { AnalysisContextReportPublisher contextPublisher = mock(AnalysisContextReportPublisher.class); @Before - public void setUp() { + public void setUp() throws IOException { wsClient = mock(ScannerWsClient.class, Mockito.RETURNS_DEEP_STUBS); - root = new DefaultInputModule(ProjectDefinition.create().setKey("struts").setWorkDir(temp.getRoot())); + root = new DefaultInputModule(ProjectDefinition.create().setKey("struts").setBaseDir(temp.newFolder()).setWorkDir(temp.getRoot())); when(moduleHierarchy.root()).thenReturn(root); when(server.getPublicRootUrl()).thenReturn("https://localhost"); when(server.getVersion()).thenReturn("6.4"); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/DefaultComponentTreeTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/DefaultComponentTreeTest.java index e60b3303d40..562c7d58395 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/DefaultComponentTreeTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/DefaultComponentTreeTest.java @@ -19,14 +19,22 @@ */ package org.sonar.scanner.scan; +import java.io.IOException; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.internal.DefaultInputComponent; import org.sonar.api.batch.fs.internal.DefaultInputModule; import static org.assertj.core.api.Assertions.assertThat; public class DefaultComponentTreeTest { + + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + private DefaultComponentTree tree; @Before @@ -35,12 +43,12 @@ public class DefaultComponentTreeTest { } @Test - public void test() { - DefaultInputComponent root = new DefaultInputModule("root"); - DefaultInputComponent mod1 = new DefaultInputModule("mod1"); - DefaultInputComponent mod2 = new DefaultInputModule("mod2"); - DefaultInputComponent mod3 = new DefaultInputModule("mod3"); - DefaultInputComponent mod4 = new DefaultInputModule("mod4"); + public void test() throws IOException { + DefaultInputComponent root = new DefaultInputModule(ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); + DefaultInputComponent mod1 = new DefaultInputModule(ProjectDefinition.create().setKey("mod1").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); + DefaultInputComponent mod2 = new DefaultInputModule(ProjectDefinition.create().setKey("mod2").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); + DefaultInputComponent mod3 = new DefaultInputModule(ProjectDefinition.create().setKey("mod3").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); + DefaultInputComponent mod4 = new DefaultInputModule(ProjectDefinition.create().setKey("mod4").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); tree.index(mod1, root); tree.index(mod2, mod1); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/DefaultInputModuleHierarchyTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/DefaultInputModuleHierarchyTest.java index 977fdc6a67c..d9e5650dc9d 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/DefaultInputModuleHierarchyTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/DefaultInputModuleHierarchyTest.java @@ -19,24 +19,31 @@ */ package org.sonar.scanner.scan; -import static org.assertj.core.api.Assertions.assertThat; - +import java.io.IOException; import java.util.HashMap; import java.util.Map; - +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.internal.DefaultInputModule; +import static org.assertj.core.api.Assertions.assertThat; + public class DefaultInputModuleHierarchyTest { + + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + private DefaultInputModuleHierarchy moduleHierarchy; @Test - public void test() { - DefaultInputModule root = new DefaultInputModule("root"); - DefaultInputModule mod1 = new DefaultInputModule("mod1"); - DefaultInputModule mod2 = new DefaultInputModule("mod2"); - DefaultInputModule mod3 = new DefaultInputModule("mod3"); - DefaultInputModule mod4 = new DefaultInputModule("mod4"); + public void test() throws IOException { + DefaultInputModule root = new DefaultInputModule(ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); + DefaultInputModule mod1 = new DefaultInputModule(ProjectDefinition.create().setKey("mod1").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); + DefaultInputModule mod2 = new DefaultInputModule(ProjectDefinition.create().setKey("mod2").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); + DefaultInputModule mod3 = new DefaultInputModule(ProjectDefinition.create().setKey("mod3").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); + DefaultInputModule mod4 = new DefaultInputModule(ProjectDefinition.create().setKey("mod4").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); Map<DefaultInputModule, DefaultInputModule> parents = new HashMap<>(); @@ -60,8 +67,8 @@ public class DefaultInputModuleHierarchyTest { } @Test - public void testOnlyRoot() { - DefaultInputModule root = new DefaultInputModule("root"); + public void testOnlyRoot() throws IOException { + DefaultInputModule root = new DefaultInputModule(ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); moduleHierarchy = new DefaultInputModuleHierarchy(root); assertThat(moduleHierarchy.children(root)).isEmpty(); @@ -70,9 +77,9 @@ public class DefaultInputModuleHierarchyTest { } @Test - public void testParentChild() { - DefaultInputModule root = new DefaultInputModule("root"); - DefaultInputModule mod1 = new DefaultInputModule("mod1"); + public void testParentChild() throws IOException { + DefaultInputModule root = new DefaultInputModule(ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); + DefaultInputModule mod1 = new DefaultInputModule(ProjectDefinition.create().setKey("mod1").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); moduleHierarchy = new DefaultInputModuleHierarchy(root, mod1); assertThat(moduleHierarchy.children(root)).containsOnly(mod1); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectLockTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectLockTest.java index af46b5edd7b..b27f6b7aa1d 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectLockTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectLockTest.java @@ -19,14 +19,9 @@ */ package org.sonar.scanner.scan; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.io.File; import java.nio.file.Files; import java.nio.file.Path; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -36,6 +31,10 @@ import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.home.cache.DirectoryLock; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class ProjectLockTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @@ -53,7 +52,7 @@ public class ProjectLockTest { InputModuleHierarchy hierarchy = mock(InputModuleHierarchy.class); DefaultInputModule root = mock(DefaultInputModule.class); when(hierarchy.root()).thenReturn(root); - when(root.getWorkDir()).thenReturn(file); + when(root.getWorkDir()).thenReturn(file.toPath()); return new ProjectLock(hierarchy); } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/WorkDirectoryCleanerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/WorkDirectoryCleanerTest.java index aa824ab9abc..82886823190 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/WorkDirectoryCleanerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/WorkDirectoryCleanerTest.java @@ -19,13 +19,8 @@ */ package org.sonar.scanner.scan; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.io.File; import java.io.IOException; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -34,6 +29,10 @@ import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.home.cache.DirectoryLock; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class WorkDirectoryCleanerTest { private WorkDirectoryCleaner cleaner; @Rule @@ -54,7 +53,7 @@ public class WorkDirectoryCleanerTest { InputModuleHierarchy hierarchy = mock(InputModuleHierarchy.class); DefaultInputModule root = mock(DefaultInputModule.class); when(hierarchy.root()).thenReturn(root); - when(root.getWorkDir()).thenReturn(temp.getRoot()); + when(root.getWorkDir()).thenReturn(temp.getRoot().toPath()); assertThat(temp.getRoot().list().length).isGreaterThan(1); cleaner = new WorkDirectoryCleaner(hierarchy); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/InputComponentStoreTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/InputComponentStoreTest.java index 9a82a623f55..38e480e8b7d 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/InputComponentStoreTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/InputComponentStoreTest.java @@ -51,9 +51,9 @@ public class InputComponentStoreTest { File rootBaseDir = temp.newFolder(); ProjectDefinition moduleDef = ProjectDefinition.create() - .setKey(subModuleKey).setBaseDir(rootBaseDir); + .setKey(subModuleKey).setBaseDir(rootBaseDir).setWorkDir(temp.newFolder()); ProjectDefinition rootDef = ProjectDefinition.create() - .setKey(rootModuleKey).setBaseDir(rootBaseDir).addSubProject(moduleDef); + .setKey(rootModuleKey).setBaseDir(rootBaseDir).setWorkDir(temp.newFolder()).addSubProject(moduleDef); DefaultInputModule rootModule = TestInputFileBuilder.newDefaultInputModule(rootDef); DefaultInputModule subModule = TestInputFileBuilder.newDefaultInputModule(moduleDef); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/InputFileBuilderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/InputFileBuilderTest.java index bf8091f5853..d6b5ac30075 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/InputFileBuilderTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/InputFileBuilderTest.java @@ -31,37 +31,41 @@ import org.sonar.api.batch.fs.InputFile.Type; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.config.internal.MapSettings; -import org.sonar.api.scan.filesystem.PathResolver; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class InputFileBuilderTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private Path baseDir; + private Path workDir; private InputFileBuilder builder; @Before public void setUp() throws IOException { baseDir = temp.newFolder().toPath(); + workDir = temp.newFolder().toPath(); DefaultInputModule module = new DefaultInputModule(ProjectDefinition.create() - .setKey("module1") - .setBaseDir(baseDir.toFile()), 0); + .setBaseDir(baseDir.toFile()) + .setWorkDir(workDir.toFile()) + .setKey("module1"), 0); - PathResolver pathResolver = new PathResolver(); LanguageDetection langDetection = mock(LanguageDetection.class); MetadataGenerator metadataGenerator = mock(MetadataGenerator.class); BatchIdGenerator idGenerator = new BatchIdGenerator(); MapSettings settings = new MapSettings(); - builder = new InputFileBuilder(module, pathResolver, langDetection, metadataGenerator, idGenerator, settings.asConfig()); + ModuleFileSystemInitializer moduleFileSystemInitializer = mock(ModuleFileSystemInitializer.class); + when(moduleFileSystemInitializer.defaultEncoding()).thenReturn(StandardCharsets.UTF_8); + builder = new InputFileBuilder(module, langDetection, metadataGenerator, idGenerator, settings.asConfig(), moduleFileSystemInitializer); } @Test public void testBuild() { Path filePath = baseDir.resolve("src/File1.xoo"); - DefaultInputFile inputFile = builder.create(filePath, Type.MAIN, StandardCharsets.UTF_8); + DefaultInputFile inputFile = builder.create(filePath, Type.MAIN); assertThat(inputFile.moduleKey()).isEqualTo("module1"); assertThat(inputFile.absolutePath()).isEqualTo(filePath.toString().replaceAll("\\\\", "/")); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorProviderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorProviderTest.java index c9c7312fab5..5ebded1daec 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorProviderTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorProviderTest.java @@ -19,8 +19,12 @@ */ package org.sonar.scanner.scan.filesystem; +import java.io.IOException; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; +import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.FileMetadata; import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer; @@ -31,12 +35,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class MetadataGeneratorProviderTest { + + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + @Test - public void create_builder() { + public void create_builder() throws IOException { StatusDetectionFactory statusDetectionFactory = mock(StatusDetectionFactory.class, Mockito.RETURNS_MOCKS); IssueExclusionsLoader issueExclusionsLoader = new IssueExclusionsLoader(mock(IssueExclusionPatternInitializer.class), mock(PatternMatcher.class)); MetadataGeneratorProvider factory = new MetadataGeneratorProvider(); - assertThat(factory.provide(new DefaultInputModule("module"), statusDetectionFactory, new FileMetadata(), issueExclusionsLoader)).isNotNull(); + assertThat(factory.provide(new DefaultInputModule(ProjectDefinition.create().setKey("module").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())), + statusDetectionFactory, new FileMetadata(), issueExclusionsLoader)).isNotNull(); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorTest.java index b9a9723e0eb..27fa5362f54 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorTest.java @@ -31,6 +31,7 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.fs.internal.DefaultInputModule; @@ -59,11 +60,12 @@ public class MetadataGeneratorTest { private MetadataGenerator generator; @Before - public void setUp() { + public void setUp() throws IOException { MockitoAnnotations.initMocks(this); metadata = new FileMetadata(); IssueExclusionsLoader issueExclusionsLoader = new IssueExclusionsLoader(mock(IssueExclusionPatternInitializer.class), mock(PatternMatcher.class)); - generator = new MetadataGenerator(new DefaultInputModule("module"), statusDetection, metadata, issueExclusionsLoader); + generator = new MetadataGenerator(new DefaultInputModule(ProjectDefinition.create().setKey("module").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())), + statusDetection, metadata, issueExclusionsLoader); } @Test diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializerTest.java index 454223ad846..0d915fb747f 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializerTest.java @@ -19,27 +19,28 @@ */ package org.sonar.scanner.scan.filesystem; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - import java.io.File; import java.io.IOException; - +import java.nio.file.Path; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.bootstrap.ProjectDefinition; -import org.sonar.api.scan.filesystem.PathResolver; -import org.sonar.api.utils.TempFolder; +import org.sonar.api.batch.fs.internal.DefaultInputModule; +import org.sonar.api.utils.log.LogTester; +import org.sonar.api.utils.log.LoggerLevel; + +import static org.assertj.core.api.Assertions.assertThat; public class ModuleFileSystemInitializerTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - PathResolver pathResolver = new PathResolver(); + @Rule + public LogTester logTester = new LogTester(); @Test public void test_default_directories() throws Exception { @@ -47,10 +48,10 @@ public class ModuleFileSystemInitializerTest { File workDir = temp.newFolder("work"); ProjectDefinition module = ProjectDefinition.create().setBaseDir(baseDir).setWorkDir(workDir); - ModuleFileSystemInitializer initializer = new ModuleFileSystemInitializer(module, mock(TempFolder.class), pathResolver); + ModuleFileSystemInitializer initializer = new ModuleFileSystemInitializer(new DefaultInputModule(module), module); - assertThat(initializer.baseDir().getCanonicalPath()).isEqualTo(baseDir.getCanonicalPath()); - assertThat(initializer.workingDir().getCanonicalPath()).isEqualTo(workDir.getCanonicalPath()); + assertThat(logTester.logs(LoggerLevel.INFO)).contains("Base dir: " + baseDir.toPath().toAbsolutePath().toString()); + assertThat(logTester.logs(LoggerLevel.INFO)).contains("Working dir: " + workDir.toPath().toAbsolutePath().toString()); assertThat(initializer.sources()).isEmpty(); assertThat(initializer.tests()).isEmpty(); } @@ -58,6 +59,7 @@ public class ModuleFileSystemInitializerTest { @Test public void should_init_directories() throws IOException { File baseDir = temp.newFolder("base"); + File workDir = temp.newFolder("work"); File sourceDir = new File(baseDir, "src/main/java"); FileUtils.forceMkdir(sourceDir); File testDir = new File(baseDir, "src/test/java"); @@ -67,12 +69,12 @@ public class ModuleFileSystemInitializerTest { ProjectDefinition project = ProjectDefinition.create() .setBaseDir(baseDir) + .setWorkDir(workDir) .addSources("src/main/java", "src/main/unknown") .addTests("src/test/java", "src/test/unknown"); - ModuleFileSystemInitializer initializer = new ModuleFileSystemInitializer(project, mock(TempFolder.class), pathResolver); + ModuleFileSystemInitializer initializer = new ModuleFileSystemInitializer(new DefaultInputModule(project), project); - assertThat(initializer.baseDir().getCanonicalPath()).isEqualTo(baseDir.getCanonicalPath()); assertThat(initializer.sources()).hasSize(1); assertThat(path(initializer.sources().get(0))).endsWith("src/main/java"); assertThat(initializer.tests()).hasSize(1); @@ -82,6 +84,7 @@ public class ModuleFileSystemInitializerTest { @Test public void supportFilenamesWithComma() throws IOException { File baseDir = temp.newFolder("base"); + File workDir = temp.newFolder("work"); File sourceFile = new File(baseDir, "my,File.cs"); sourceFile.createNewFile(); File testFile = new File(baseDir, "my,TestFile.cs"); @@ -89,20 +92,20 @@ public class ModuleFileSystemInitializerTest { ProjectDefinition project = ProjectDefinition.create() .setBaseDir(baseDir) + .setWorkDir(workDir) .addSources("\"my,File.cs\"") .addTests("\"my,TestFile.cs\""); - ModuleFileSystemInitializer initializer = new ModuleFileSystemInitializer(project, mock(TempFolder.class), pathResolver); + ModuleFileSystemInitializer initializer = new ModuleFileSystemInitializer(new DefaultInputModule(project), project); - assertThat(initializer.baseDir().getCanonicalPath()).isEqualTo(baseDir.getCanonicalPath()); assertThat(initializer.sources()).hasSize(1); - assertThat(initializer.sources().get(0)).isEqualTo(sourceFile); + assertThat(initializer.sources().get(0)).isEqualTo(sourceFile.toPath()); assertThat(initializer.tests()).hasSize(1); - assertThat(initializer.tests().get(0)).isEqualTo(testFile); + assertThat(initializer.tests().get(0)).isEqualTo(testFile.toPath()); } - private String path(File f) throws IOException { - return FilenameUtils.separatorsToUnix(f.getCanonicalPath()); + private String path(Path f) throws IOException { + return FilenameUtils.separatorsToUnix(f.toString()); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/report/JSONReportTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/report/JSONReportTest.java index 42d4c443c72..65af751088f 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/report/JSONReportTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/report/JSONReportTest.java @@ -19,12 +19,6 @@ */ package org.sonar.scanner.scan.report; -import static net.javacrumbs.jsonunit.assertj.JsonAssert.assertThatJson; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - import java.io.File; import java.io.IOException; import java.io.StringWriter; @@ -32,7 +26,6 @@ import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collections; import java.util.TimeZone; - import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Rule; @@ -58,6 +51,12 @@ import org.sonar.scanner.issue.tracking.TrackedIssue; import org.sonar.scanner.scan.DefaultComponentTree; import org.sonar.scanner.scan.filesystem.InputComponentStore; +import static net.javacrumbs.jsonunit.assertj.JsonAssert.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + public class JSONReportTest { private SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); @@ -82,13 +81,13 @@ public class JSONReportTest { when(server.getVersion()).thenReturn("3.6"); DefaultComponentTree inputComponentTree = new DefaultComponentTree(); - ProjectDefinition def = ProjectDefinition.create().setBaseDir(projectBaseDir).setKey("struts"); + ProjectDefinition def = ProjectDefinition.create().setBaseDir(projectBaseDir).setWorkDir(temp.newFolder()).setKey("struts"); DefaultInputModule rootModule = new DefaultInputModule(def, 1); InputComponentStore inputComponentStore = new InputComponentStore(new PathResolver(), rootModule); - DefaultInputModule moduleA = new DefaultInputModule("struts-core"); + DefaultInputModule moduleA = new DefaultInputModule(ProjectDefinition.create().setKey("struts-core").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); inputComponentTree.index(moduleA, rootModule); - DefaultInputModule moduleB = new DefaultInputModule("struts-ui"); + DefaultInputModule moduleB = new DefaultInputModule(ProjectDefinition.create().setKey("struts-ui").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); inputComponentTree.index(moduleB, rootModule); DefaultInputDir inputDir = new DefaultInputDir("struts", "src/main/java/org/apache/struts", TestInputFileBuilder.nextBatchId()) @@ -163,7 +162,7 @@ public class JSONReportTest { @Test public void should_not_export_by_default() throws IOException { File workDir = temp.newFolder("sonar"); - fs.setWorkDir(workDir); + fs.setWorkDir(workDir.toPath()); jsonReport.execute(); @@ -173,7 +172,7 @@ public class JSONReportTest { @Test public void should_export_issues_to_file() throws IOException { File workDir = temp.newFolder("sonar"); - fs.setWorkDir(workDir); + fs.setWorkDir(workDir.toPath()); when(issueCache.all()).thenReturn(Collections.<TrackedIssue>emptyList()); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/sensor/DefaultSensorStorageTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/sensor/DefaultSensorStorageTest.java index 2c375606ae9..11101d722ef 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/sensor/DefaultSensorStorageTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/sensor/DefaultSensorStorageTest.java @@ -20,6 +20,7 @@ package org.sonar.scanner.sensor; import com.google.common.collect.ImmutableMap; +import java.io.IOException; import java.util.Map; import org.junit.Before; import org.junit.Rule; @@ -27,6 +28,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentCaptor; +import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; @@ -114,9 +116,9 @@ public class DefaultSensorStorageTest { } @Test - public void shouldSaveProjectMeasureToSensorContext() { + public void shouldSaveProjectMeasureToSensorContext() throws IOException { String projectKey = "myProject"; - DefaultInputModule module = new DefaultInputModule(projectKey); + DefaultInputModule module = new DefaultInputModule(ProjectDefinition.create().setKey(projectKey).setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); ArgumentCaptor<DefaultMeasure> argumentCaptor = ArgumentCaptor.forClass(DefaultMeasure.class); when(measureCache.put(eq(module.key()), eq(CoreMetrics.NCLOC_KEY), argumentCaptor.capture())).thenReturn(null); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/HighlightableBuilderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/HighlightableBuilderTest.java index dea24cd4571..c22963136d8 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/HighlightableBuilderTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/HighlightableBuilderTest.java @@ -19,8 +19,12 @@ */ package org.sonar.scanner.source; +import java.io.IOException; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.AnalysisMode; +import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.batch.sensor.internal.SensorStorage; @@ -31,6 +35,9 @@ import static org.mockito.Mockito.mock; public class HighlightableBuilderTest { + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + @Test public void should_load_default_perspective() { HighlightableBuilder builder = new HighlightableBuilder(mock(SensorStorage.class), mock(AnalysisMode.class)); @@ -40,9 +47,10 @@ public class HighlightableBuilderTest { } @Test - public void project_should_not_be_highlightable() { + public void project_should_not_be_highlightable() throws IOException { HighlightableBuilder builder = new HighlightableBuilder(mock(SensorStorage.class), mock(AnalysisMode.class)); - Highlightable perspective = builder.loadPerspective(Highlightable.class, new DefaultInputModule("struts")); + Highlightable perspective = builder.loadPerspective(Highlightable.class, + new DefaultInputModule(ProjectDefinition.create().setKey("struts").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()))); assertThat(perspective).isNull(); } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/SymbolizableBuilderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/SymbolizableBuilderTest.java index e6531257a2a..0b202db2085 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/SymbolizableBuilderTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/SymbolizableBuilderTest.java @@ -19,8 +19,12 @@ */ package org.sonar.scanner.source; +import java.io.IOException; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.AnalysisMode; +import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.component.Perspective; @@ -32,6 +36,9 @@ import static org.mockito.Mockito.mock; public class SymbolizableBuilderTest { + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + @Test public void should_load_perspective() { SymbolizableBuilder perspectiveBuilder = new SymbolizableBuilder(mock(DefaultSensorStorage.class), mock(AnalysisMode.class)); @@ -41,9 +48,10 @@ public class SymbolizableBuilderTest { } @Test - public void project_should_not_be_highlightable() { + public void project_should_not_be_highlightable() throws IOException { SymbolizableBuilder builder = new SymbolizableBuilder(mock(DefaultSensorStorage.class), mock(AnalysisMode.class)); - Perspective perspective = builder.loadPerspective(Symbolizable.class, new DefaultInputModule("struts")); + Perspective perspective = builder.loadPerspective(Symbolizable.class, + new DefaultInputModule(ProjectDefinition.create().setKey("struts").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()))); assertThat(perspective).isNull(); } |