Unnamed: 0
int64
0
305k
body
stringlengths
7
52.9k
name
stringlengths
1
185
1,600
void (Collection<String> paths) { if (paths.isEmpty()) return; final String[] buffer = new String[paths.size()]; int i = 0; for (final String o : paths) { buffer[i++] = o; } Arrays.sort(buffer); logLine("Cleaning output files:"); for (final String o : buffer) { logLine(o); } logLine("End of files"); }
logDeletedFiles
1,601
boolean () { return LOG.isDebugEnabled(); }
isEnabled
1,602
void (final String message) { LOG.debug(message); }
logLine
1,603
ProjectBuilderLogger () { return myProjectLogger; }
getProjectBuilderLogger
1,604
boolean (File root, Set<? extends File> excluded, Set<? super File> notUnderExcludedCache) { File parent = root; List<File> parents = new ArrayList<>(); while (parent != null) { if (notUnderExcludedCache.contains(parent)) { return false; } if (excluded.contains(parent)) { return true; } parents.add(parent); parent = parent.getParentFile(); } notUnderExcludedCache.addAll(parents); return false; }
isUnderExcluded
1,605
boolean (File file) { return determineFileLocation(file, myTopLevelContentRoots, myExcludedRoots) == FileLocation.EXCLUDED; }
isExcluded
1,606
boolean (File file, JpsModule module) { return determineFileLocation(file, myModuleToContentMap.get(module), myModuleToExcludesMap.get(module)) == FileLocation.EXCLUDED; }
isExcludedFromModule
1,607
boolean (File file) { return determineFileLocation(file, myTopLevelContentRoots, myExcludedRoots) == FileLocation.IN_CONTENT; }
isInContent
1,608
FileLocation (File file, Collection<File> roots, Collection<File> excluded) { if (roots.isEmpty() && excluded.isEmpty()) { return FileLocation.NOT_IN_PROJECT; // optimization } File current = file; while (current != null) { if (excluded.contains(current)) { return FileLocation.EXCLUDED; } FileTypeAssocTable<Boolean> table = myExcludeFromContentRootTables.get(current); if (table != null && isExcludedByPattern(file, current, table)) { return FileLocation.EXCLUDED; } if (roots.contains(current)) { return FileLocation.IN_CONTENT; } current = FileUtilRt.getParentFile(current); } return FileLocation.NOT_IN_PROJECT; }
determineFileLocation
1,609
boolean (File file, File root, FileTypeAssocTable<Boolean> table) { File current = file; //noinspection FileEqualsUsage it's ok to compare files by 'equals' here be because these files are produced by the same 'getParentFile' calls while (current != null && !current.equals(root)) { if (table.findAssociatedFileType(current.getName()) != null) { return true; } current = FileUtilRt.getParentFile(current); } return false; }
isExcludedByPattern
1,610
Collection<File> (JpsModule module) { return myModuleToExcludesMap.get(module); }
getModuleExcludes
1,611
FileFilter (@NotNull JpsModule module) { List<File> contentRoots = myModuleToContentMap.get(module); if (contentRoots == null || contentRoots.isEmpty() || myExcludeFromContentRootTables.isEmpty()) return FileFilters.EVERYTHING; return file -> determineFileLocation(file, contentRoots, Collections.emptyList()) == FileLocation.IN_CONTENT; }
getModuleFileFilterHonorExclusionPatterns
1,612
boolean (String fileName) { return myIgnoredPatterns.isIgnored(fileName); }
isIgnored
1,613
int () { int threadsCount = Runtime.getRuntime().availableProcessors() - 1; LOG.info("Executor service will be configured with " + threadsCount + " threads"); return threadsCount; }
getThreadPoolSize
1,614
void (@NotNull File dir, boolean asynchronously) { if (!asynchronously) { FileUtil.delete(dir); return; } LOG.info("Deleting asynchronously... " + dir.getPath()); try { File temp = getEmptyTempDir(); Path moved = Files.move(dir.toPath(), temp.toPath()); EXECUTOR_SERVICE.execute(() -> delete(moved)); } catch (IOException e) { LOG.warn("Unable to move directory: " + e.getMessage()); FileUtil.delete(dir); } }
delete
1,615
void () { LOG.info("Running clean-up asynchronously..."); Path pluginTemp = Path.of(PathManager.getPluginTempPath()); try (Stream<Path> stream = Files.list(pluginTemp)) { List<Path> files = stream.filter(file -> file.getFileName().toString().startsWith(getPrefix())).collect(Collectors.toList()); if (!files.isEmpty()) { EXECUTOR_SERVICE.execute(() -> files.forEach(JpsCachesLoaderUtil::delete)); } } catch (IOException e) { LOG.warn("Unable to run clean-up task: " + e.getMessage()); } }
runCleanUpAsynchronously
1,616
void (@NotNull Path dir) { if (SystemInfo.isUnix) { File empty = getEmptyTempDir(); if (empty.mkdir()) { try { // https://unix.stackexchange.com/a/79656/47504 List<String> command = new ArrayList<>(); command.add("rsync"); command.add("-a"); command.add("--delete"); command.add(empty.getPath() + "/"); command.add(dir + "/"); ProcessBuilder builder = new ProcessBuilder(command); Process process = builder.start(); process.waitFor(); int exitCode = process.exitValue(); LOG.info("rsync exited with " + exitCode); } catch (IOException | InterruptedException e) { LOG.warn("rsync failed: " + e.getMessage()); } finally { FileUtil.delete(empty); } } } FileUtil.delete(dir.toFile()); }
delete
1,617
File () { File pluginTemp = new File(PathManager.getPluginTempPath()); String prefix = getPrefix() + UUID.randomUUID(); return FileUtil.findSequentNonexistentFile(pluginTemp, prefix, ""); }
getEmptyTempDir
1,618
String () { return LOADER_TMP_FOLDER_NAME + "-"; }
getPrefix
1,619
LoaderStatus (@Nullable Object loadResults) { if (!(loadResults instanceof File)) return LoaderStatus.FAILED; LOG.info("Start extraction of JPS caches"); File zipFile = (File)loadResults; long fileSize = zipFile.length(); File tmpFolder = new File(myBuildCacheFolder.getParentFile(), "tmp"); try { // Start extracting after download myContext.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.text.extracting.downloaded.results")); myContext.checkCanceled(); long start = System.currentTimeMillis(); AtomicInteger extractItemsCount = new AtomicInteger(); new Decompressor.Zip(zipFile).postProcessor(path -> { extractItemsCount.incrementAndGet(); myContext.checkCanceled(); if (extractItemsCount.get() == 130) { int expectedDownloads = myContext.getTotalExpectedDownloads(); myContext.getNettyClient().sendDescriptionStatusMessage(JpsBuildBundle.message("progress.details.extracting.project.caches"), expectedDownloads); extractItemsCount.set(0); } }).extract(tmpFolder.toPath()); JpsCacheLoadingSystemStats.setDecompressionTimeMs(fileSize, System.currentTimeMillis() - start); long deletionStart = System.currentTimeMillis(); FileUtil.delete(zipFile); JpsCacheLoadingSystemStats.setDeletionTimeMs(fileSize, System.currentTimeMillis() - deletionStart); LOG.info("Unzip compilation caches took: " + (System.currentTimeMillis() - start)); myTmpCacheFolder = tmpFolder; return LoaderStatus.COMPLETE; } catch (ProcessCanceledException | IOException e) { if (e instanceof IOException) LOG.warn("Failed unzip downloaded compilation caches", e); FileUtil.delete(zipFile); FileUtil.delete(tmpFolder); } return LoaderStatus.FAILED; }
extract
1,620
void () { if (myTmpCacheFolder != null && myTmpCacheFolder.exists()) { FileUtil.delete(myTmpCacheFolder); LOG.debug("JPS cache loader rolled back"); } }
rollback
1,621
void () { if (myTmpCacheFolder == null) { LOG.warn("Nothing to apply, download results are empty"); return; } File newTimestampFolder = new File(myTmpCacheFolder, TIMESTAMPS_FOLDER_NAME); if (newTimestampFolder.exists()) FileUtil.delete(newTimestampFolder); myContext.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.text.applying.jps.caches")); if (myBuildCacheFolder != null) { myContext.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.details.applying.downloaded.caches")); // Copy timestamp old folder to new cache dir File timestamps = new File(myBuildCacheFolder, TIMESTAMPS_FOLDER_NAME); if (timestamps.exists()) { try { newTimestampFolder.mkdirs(); FileUtil.copyDir(timestamps, newTimestampFolder); } catch (IOException e) { LOG.warn("Couldn't copy timestamps from old JPS cache", e); } } // Create new empty fsStateFile File fsStateFile = new File(myTmpCacheFolder, FS_STATE_FILE); fsStateFile.delete(); try { fsStateFile.createNewFile(); } catch (IOException e) { LOG.warn("Couldn't create new empty " + FS_STATE_FILE + " file", e); } // Remove old cache dir JpsCachesLoaderUtil.delete(myBuildCacheFolder, isCleanupAsynchronously); myTmpCacheFolder.renameTo(myBuildCacheFolder); //subTaskIndicator.finished(); LOG.debug("JPS cache downloads finished"); } }
apply
1,622
void (@NotNull JpsLoaderContext context) { myContext = context; }
setContext
1,623
void (@NotNull BuildRunner buildRunner, boolean isForceUpdate, @NotNull List<CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope> scopes, @NotNull Runnable beforeDownload) { if (!canRunNewLoading()) return; if (isCleanupAsynchronously) JpsCachesLoaderUtil.runCleanUpAsynchronously(); if (isForceCachesDownload || isDownloadQuickerThanLocalBuild(buildRunner, myCommitsCountBetweenCompilation, scopes)) { LOG.info("Before download task execution..."); beforeDownload.run(); // Drop JPS metadata to force plugin for downloading all compilation outputs myNettyClient.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.text.fetching.cache.for.commit", myCommitHash)); if (isForceUpdate) { myMetadataLoader.dropCurrentProjectMetadata(); File outDir = new File(myBuildOutDir); if (outDir.exists()) { LOG.info("Start removing old caches before downloading"); myNettyClient.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.text.removing.old.caches")); JpsCachesLoaderUtil.delete(outDir, isCleanupAsynchronously); } LOG.info("Compilation output folder empty"); } startLoadingForCommit(myCommitHash); } else { String message = JpsBuildBundle.message("progress.text.local.build.is.quicker"); LOG.warn(message); myNettyClient.sendDescriptionStatusMessage(message); } hasRunningTask.set(false); }
load
1,624
void (@NotNull ProjectDescriptor projectDescriptor) { if (isForceCachesDownload) return; if (!hasRunningTask.get() && isCacheDownloaded) { BuildTargetsState targetsState = projectDescriptor.getTargetsState(); myOriginalBuildStatistic.getBuildTargetTypeStatistic().forEach((buildTargetType, originalBuildTime) -> { targetsState.setAverageBuildTime(buildTargetType, originalBuildTime); LOG.info("Saving old build statistic for " + buildTargetType.getTypeId() + " with value " + originalBuildTime); }); Long originalBuildStatisticProjectRebuildTime = myOriginalBuildStatistic.getProjectRebuildTime(); targetsState.setLastSuccessfulRebuildDuration(originalBuildStatisticProjectRebuildTime); LOG.info("Saving old project rebuild time " + originalBuildStatisticProjectRebuildTime); } }
updateBuildStatistic
1,625
void (@NotNull CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status status, @NotNull Channel channel, @NotNull UUID sessionId) { if (status == CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.CANCELED || status == CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.ERRORS || status == CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.UP_TO_DATE) return; LOG.info("Saving latest project built commit"); JpsNettyClient.saveLatestBuiltCommit(channel, sessionId); }
saveLatestBuiltCommitId
1,626
boolean (BuildRunner buildRunner, int commitsCountBetweenCompilation, List<CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope> scopes) { SystemOpsStatistic systemOpsStatistic = JpsServerConnectionUtil.measureConnectionSpeed(myNettyClient); if (systemOpsStatistic == null) { LOG.info("Connection speed is too small to download caches"); return false; } Pair<Long, Integer> buildTimeAndProjectModulesCount = estimateProjectBuildTime(buildRunner, scopes); int projectModulesCount; long approximateBuildTime; if (buildTimeAndProjectModulesCount != null) { approximateBuildTime = buildTimeAndProjectModulesCount.first; projectModulesCount = buildTimeAndProjectModulesCount.second; } else { LOG.info("Rebuild or unexpected behaviour at build time calculation. Local build will be executed"); return false; } if (approximateBuildTime == 0 && commitsCountBetweenCompilation > COMMITS_COUNT_THRESHOLD) { LOG.info("Can't calculate approximate project build time, but there are " + commitsCountBetweenCompilation + " not compiled " + "commits and it seems that it will be faster to download caches."); return true; } if (approximateBuildTime == 0) { LOG.info("Can't calculate approximate project build time"); return false; } long approximateDownloadTime = calculateApproximateDownloadTimeMs(systemOpsStatistic, projectModulesCount); if (approximateDownloadTime == 0) { LOG.info("Can't calculate approximate download time"); return false; } return approximateDownloadTime < approximateBuildTime; }
isDownloadQuickerThanLocalBuild
1,627
long (SystemOpsStatistic systemOpsStatistic, int projectModulesCount) { double magicCoefficient = 1.3; long decompressionSpeed; if (JpsCacheLoadingSystemStats.getDecompressionSpeedBytesPesSec() > 0) { decompressionSpeed = JpsCacheLoadingSystemStats.getDecompressionSpeedBytesPesSec(); LOG.info("Using previously saved statistic about decompression speed: " + StringUtil.formatFileSize(decompressionSpeed) + "/s"); } else { decompressionSpeed = systemOpsStatistic.getDecompressionSpeedBytesPesSec(); } long deletionSpeed; if (JpsCacheLoadingSystemStats.getDeletionSpeedBytesPerSec() > 0) { deletionSpeed = JpsCacheLoadingSystemStats.getDeletionSpeedBytesPerSec(); LOG.info("Using previously saved statistic about deletion speed: " + StringUtil.formatFileSize(deletionSpeed) + "/s"); } else { deletionSpeed = systemOpsStatistic.getDeletionSpeedBytesPerSec(); } int approximateSizeToDelete = projectModulesCount * PROJECT_MODULE_SIZE_DISK_BYTES; int approximateDownloadSize = projectModulesCount * PROJECT_MODULE_DOWNLOAD_SIZE_BYTES + AVERAGE_CACHE_SIZE_BYTES; long expectedDownloadTimeSec = approximateDownloadSize / systemOpsStatistic.getConnectionSpeedBytesPerSec(); long expectedDecompressionTimeSec = approximateDownloadSize / decompressionSpeed; long expectedDeleteTimeSec = approximateSizeToDelete / deletionSpeed; long expectedTimeOfWorkMs = ((long)(expectedDeleteTimeSec * magicCoefficient) + expectedDownloadTimeSec + expectedDecompressionTimeSec) * 1000; LOG.info("Expected download size: " + StringUtil.formatFileSize(approximateDownloadSize) + ". Expected download time: " + expectedDownloadTimeSec + "sec. " + "Expected decompression time: " + expectedDecompressionTimeSec + "sec. " + "Expected size to delete: " + StringUtil.formatFileSize(approximateDownloadSize) + ". Expected delete time: " + expectedDeleteTimeSec + "sec. " + "Total time of work: " + StringUtil.formatDuration(expectedTimeOfWorkMs)); if (expectedDownloadTimeSec >= myMaxDownloadDuration) { LOG.info("Downloading can consume more than 10 mins, connection speed is too small for caches usages"); return 0; } return expectedTimeOfWorkMs; }
calculateApproximateDownloadTimeMs
1,628
void (@NotNull String commitId) { long startTime = System.nanoTime(); // Loading metadata for commit Map<String, Map<String, BuildTargetState>> commitSourcesState = myMetadataLoader.loadMetadataForCommit(myNettyClient, commitId); if (commitSourcesState == null) { LOG.warn("Couldn't load metadata for commit: " + commitId); return; } // Calculate downloads Map<String, Map<String, BuildTargetState>> currentSourcesState = myMetadataLoader.loadCurrentProjectMetadata(); int totalDownloads = getLoaders().stream().mapToInt(loader -> loader.calculateDownloads(commitSourcesState, currentSourcesState)).sum(); try { // Computation with loaders results. If at least one of them failed rollback all job initLoaders(commitId, totalDownloads, commitSourcesState, currentSourcesState).thenAccept(loaderStatus -> { LOG.info("Loading finished with " + loaderStatus + " status"); try { CompletableFuture.allOf(getLoaders().stream() .map(loader -> applyChanges(loaderStatus, loader)) .toArray(CompletableFuture[]::new)) .thenRun(() -> saveStateAndNotify(loaderStatus, commitId, startTime)) .get(); } catch (InterruptedException | ExecutionException e) { LOG.warn("Unexpected exception rollback all progress", e); onFail(); getLoaders().forEach(loader -> loader.rollback()); myNettyClient.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.text.rolling.back.downloaded.caches")); } }).handle((result, ex) -> handleExceptions(result, ex)).get(); } catch (InterruptedException | ExecutionException e) { LOG.warn("Couldn't fetch jps compilation caches", e); onFail(); } }
startLoadingForCommit
1,629
CompletableFuture<Void> (LoaderStatus loaderStatus, JpsOutputLoader<?> loader) { if (loaderStatus == LoaderStatus.FAILED) { myNettyClient.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.text.rolling.back")); return CompletableFuture.runAsync(() -> loader.rollback(), INSTANCE); } return CompletableFuture.runAsync(() -> loader.apply(), INSTANCE); }
applyChanges
1,630
void (LoaderStatus loaderStatus, String commitId, long startTime) { if (loaderStatus == LoaderStatus.FAILED) { onFail(); return; } // Statistic should be available if cache downloaded successfully myNettyClient.sendDownloadStatisticMessage(commitId, JpsCacheLoadingSystemStats.getDecompressionSpeedBytesPesSec(), JpsCacheLoadingSystemStats.getDeletionSpeedBytesPerSec()); isCacheDownloaded = true; LOG.info("Loading finished"); }
saveStateAndNotify
1,631
Void (Void result, Throwable ex) { if (ex != null) { Throwable cause = ex.getCause(); if (cause instanceof ProcessCanceledException) { LOG.info("Jps caches download canceled"); } else { LOG.warn("Couldn't fetch jps compilation caches", ex); onFail(); } getLoaders().forEach(loader -> loader.rollback()); myNettyClient.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.text.rolling.back.downloaded.caches")); } return result; }
handleExceptions
1,632
LoaderStatus (LoaderStatus firstStatus, LoaderStatus secondStatus) { if (firstStatus == LoaderStatus.FAILED || secondStatus == LoaderStatus.FAILED) return LoaderStatus.FAILED; return LoaderStatus.COMPLETE; }
combine
1,633
void () { }
onFail
1,634
int (@NotNull Map<String, Map<String, BuildTargetState>> commitSourcesState, @Nullable Map<String, Map<String, BuildTargetState>> currentSourcesState) { return calculateAffectedModules(currentSourcesState, commitSourcesState, true).size(); }
calculateDownloads
1,635
List<OutputLoadResult> () { myOldModulesPaths = null; myTmpFolderToModuleName = null; myContext.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.text.calculating.affected.modules")); List<AffectedModule> affectedModules = calculateAffectedModules(myContext.getCurrentSourcesState(), myContext.getCommitSourcesState(), true); myContext.checkCanceled(); if (affectedModules.size() > 0) { long start = System.currentTimeMillis(); List<OutputLoadResult> loadResults = myClient.downloadCompiledModules(myContext, affectedModules); LOG.info("Download of compilation outputs took: " + (System.currentTimeMillis() - start)); return loadResults; } return Collections.emptyList(); }
load
1,636
LoaderStatus (@Nullable Object loadResults) { if (!(loadResults instanceof List)) return LoaderStatus.FAILED; LOG.info("Start extraction of compilation outputs"); //noinspection unchecked List<OutputLoadResult> outputLoadResults = (List<OutputLoadResult>)loadResults; Map<File, String> result = new ConcurrentHashMap<>(); try { // Extracting results long start = System.currentTimeMillis(); myContext.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.text.extracting.downloaded.results")); List<Future<?>> futureList = ContainerUtil.map(outputLoadResults, loadResult -> EXECUTOR_SERVICE.submit(new UnzipOutputTask(result, loadResult, myContext))); for (Future<?> future : futureList) { future.get(); } myTmpFolderToModuleName = result; LOG.info("Unzip compilation output took: " + (System.currentTimeMillis() - start)); return LoaderStatus.COMPLETE; } catch (ProcessCanceledException | InterruptedException | ExecutionException e) { if (!(e.getCause() instanceof ProcessCanceledException)) LOG.warn("Failed unzip downloaded compilation outputs", e); outputLoadResults.forEach(loadResult -> FileUtil.delete(loadResult.getZipFile())); result.forEach((key, value) -> FileUtil.delete(key)); } return LoaderStatus.FAILED; }
extract
1,637
void () { if (myTmpFolderToModuleName == null) return; myTmpFolderToModuleName.forEach((tmpFolder, __) -> { if (tmpFolder.isDirectory() && tmpFolder.exists()) FileUtil.delete(tmpFolder); }); LOG.info("JPS cache loader rolled back"); }
rollback
1,638
void () { long start = System.currentTimeMillis(); if (myOldModulesPaths != null) { LOG.info("Removing old compilation outputs " + myOldModulesPaths.size() + " counts"); myOldModulesPaths.forEach(file -> { if (file.exists()) FileUtil.delete(file); }); } if (myTmpFolderToModuleName == null) { LOG.debug("Nothing to apply, download results are empty"); return; } myContext.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.text.applying.jps.caches")); ContainerUtil.map(myTmpFolderToModuleName.entrySet(), entry -> EXECUTOR_SERVICE.submit(() -> { String moduleName = entry.getValue(); File tmpModuleFolder = entry.getKey(); myContext.sendDescriptionStatusMessage(JpsBuildBundle.message("progress.details.applying.changes.for.module", moduleName)); File currentModuleBuildDir = new File(tmpModuleFolder.getParentFile(), moduleName); FileUtil.delete(currentModuleBuildDir); try { FileUtil.rename(tmpModuleFolder, currentModuleBuildDir); LOG.debug("Module: " + moduleName + " was replaced successfully"); } catch (IOException e) { LOG.warn("Couldn't replace compilation output for module: " + moduleName, e); } })) .forEach(future -> { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOG.info("Couldn't apply compilation output", e); } }); LOG.info("Applying compilation output took: " + (System.currentTimeMillis() - start)); }
apply
1,639
void (@NotNull JpsLoaderContext context) { myContext = context; }
setContext
1,640
List<AffectedModule> (@Nullable Map<String, Map<String, BuildTargetState>> currentModulesState, @NotNull Map<String, Map<String, BuildTargetState>> commitModulesState, boolean checkExistance) { long start = System.currentTimeMillis(); List<AffectedModule> affectedModules = new ArrayList<>(); Map<String, String> oldModulesMap = new HashMap<>(); myOldModulesPaths = new ArrayList<>(); if (currentModulesState == null) { commitModulesState.forEach((type, map) -> { map.forEach((name, state) -> { affectedModules.add(new AffectedModule(type, name, state.getHash(), getBuildDirRelativeFile(state.getRelativePath()))); }); }); LOG.warn("Project doesn't contain metadata, force to download " + affectedModules.size() + " modules."); List<AffectedModule> result = mergeAffectedModules(affectedModules, commitModulesState); long total = System.currentTimeMillis() - start; LOG.info("Compilation output affected for the " + result.size() + " modules. Computation took " + total + "ms"); return result; } // Add new build types Set<String> newBuildTypes = new HashSet<>(commitModulesState.keySet()); newBuildTypes.removeAll(currentModulesState.keySet()); newBuildTypes.forEach(type -> { commitModulesState.get(type).forEach((name, state) -> { affectedModules.add(new AffectedModule(type, name, state.getHash(), getBuildDirRelativeFile(state.getRelativePath()))); }); }); // Calculate old paths for remove Set<String> oldBuildTypes = new HashSet<>(currentModulesState.keySet()); oldBuildTypes.removeAll(commitModulesState.keySet()); oldBuildTypes.forEach(type -> { currentModulesState.get(type).forEach((name, state) -> { oldModulesMap.put(name, state.getRelativePath()); }); }); commitModulesState.forEach((type, map) -> { Map<String, BuildTargetState> currentTypeState = currentModulesState.get(type); // New build type already added above if (currentTypeState == null) return; // Add new build modules Set<String> newBuildModules = new HashSet<>(map.keySet()); newBuildModules.removeAll(currentTypeState.keySet()); newBuildModules.forEach(name -> { BuildTargetState state = map.get(name); affectedModules.add(new AffectedModule(type, name, state.getHash(), getBuildDirRelativeFile(state.getRelativePath()))); }); // Calculate old modules paths for remove Set<String> oldBuildModules = new HashSet<>(currentTypeState.keySet()); oldBuildModules.removeAll(map.keySet()); oldBuildModules.forEach(name -> { BuildTargetState state = currentTypeState.get(name); oldModulesMap.put(name, state.getRelativePath()); }); // In another case compare modules inside the same build type map.forEach((name, state) -> { BuildTargetState currentTargetState = currentTypeState.get(name); if (currentTargetState == null || !state.equals(currentTargetState)) { affectedModules.add(new AffectedModule(type, name, state.getHash(), getBuildDirRelativeFile(state.getRelativePath()))); return; } File outFile = getBuildDirRelativeFile(state.getRelativePath()); if (checkExistance && (!outFile.exists() || ArrayUtil.isEmpty(outFile.listFiles()))) { affectedModules.add(new AffectedModule(type, name, state.getHash(), outFile)); } }); }); // Check that old modules not exist in other build types myOldModulesPaths = oldModulesMap.entrySet().stream().filter(entry -> { for (Map.Entry<String, Map<String, BuildTargetState>> commitEntry : commitModulesState.entrySet()) { BuildTargetState targetState = commitEntry.getValue().get(entry.getKey()); if (targetState != null && targetState.getRelativePath().equals(entry.getValue())) return false; } return true; }).map(entry -> getBuildDirRelativeFile(entry.getValue())) .collect(Collectors.toList()); List<AffectedModule> result = mergeAffectedModules(affectedModules, commitModulesState); long total = System.currentTimeMillis() - start; LOG.info("Compilation output affected for the " + result.size() + " modules. Computation took " + total + "ms"); return result; }
calculateAffectedModules
1,641
List<AffectedModule> (List<AffectedModule> affectedModules, @NotNull Map<String, Map<String, BuildTargetState>> commitModulesState) { Set<AffectedModule> result = new HashSet<>(); affectedModules.forEach(affectedModule -> { if (affectedModule.getType().equals(JAVA_PRODUCTION)) { BuildTargetState targetState = commitModulesState.get(RESOURCES_PRODUCTION).get(affectedModule.getName()); if (targetState == null) { result.add(affectedModule); return; } String hash = calculateStringHash(affectedModule.getHash() + targetState.getHash()); result.add(new AffectedModule(PRODUCTION, affectedModule.getName(), hash, affectedModule.getOutPath())); } else if (affectedModule.getType().equals(RESOURCES_PRODUCTION)) { BuildTargetState targetState = commitModulesState.get(JAVA_PRODUCTION).get(affectedModule.getName()); if (targetState == null) { result.add(affectedModule); return; } String hash = calculateStringHash(targetState.getHash() + affectedModule.getHash()); result.add(new AffectedModule(PRODUCTION, affectedModule.getName(), hash, affectedModule.getOutPath())); } else if (affectedModule.getType().equals(JAVA_TEST)) { BuildTargetState targetState = commitModulesState.get(RESOURCES_TEST).get(affectedModule.getName()); if (targetState == null) { result.add(affectedModule); return; } String hash = calculateStringHash(affectedModule.getHash() + targetState.getHash()); result.add(new AffectedModule(TEST, affectedModule.getName(), hash, affectedModule.getOutPath())); } else if (affectedModule.getType().equals(RESOURCES_TEST)) { BuildTargetState targetState = commitModulesState.get(JAVA_TEST).get(affectedModule.getName()); if (targetState == null) { result.add(affectedModule); return; } String hash = calculateStringHash(targetState.getHash() + affectedModule.getHash()); result.add(new AffectedModule(TEST, affectedModule.getName(), hash, affectedModule.getOutPath())); } else { result.add(affectedModule); } }); return new ArrayList<>(result); }
mergeAffectedModules
1,642
File (String buildDirRelativePath) { return new File(buildDirRelativePath.replace("$BUILD_DIR$", myBuildDirPath)); }
getBuildDirRelativeFile
1,643
String (String content) { return String.valueOf(Xxh3.hash(content)); }
calculateStringHash
1,644
void () { AffectedModule affectedModule = loadResult.getModule(); File outPath = affectedModule.getOutPath(); try { context.checkCanceled(); int expectedDownloads = context.getTotalExpectedDownloads(); context.getNettyClient().sendDescriptionStatusMessage(JpsBuildBundle.message("progress.details.extracting.compilation.outputs.for.module", affectedModule.getName()), expectedDownloads); LOG.debug("Downloaded JPS compiled module from: " + loadResult.getDownloadUrl()); File tmpFolder = new File(outPath.getParent(), outPath.getName() + "_tmp"); File zipFile = loadResult.getZipFile(); ZipUtil.extract(zipFile, tmpFolder, null); FileUtil.delete(zipFile); result.put(tmpFolder, affectedModule.getName()); //subTaskIndicator.finished(); } catch (IOException e) { LOG.warn("Couldn't extract download result for module: " + affectedModule.getName(), e); } }
run
1,645
long () { return decompressionSpeedBytesPesSec; }
getDecompressionSpeedBytesPesSec
1,646
void (long fileSize, long duration) { decompressionSpeedBytesPesSec = fileSize / duration * 1000; }
setDecompressionTimeMs
1,647
void (long decompressionSpeed) { if (decompressionSpeed > 0) decompressionSpeedBytesPesSec = decompressionSpeed; }
setDecompressionSpeed
1,648
long () { return deletionSpeedBytesPerSec; }
getDeletionSpeedBytesPerSec
1,649
void (long fileSize, long duration) { deletionSpeedBytesPerSec = fileSize / duration * 1000; }
setDeletionTimeMs
1,650
void (long deletionSpeed) { if (deletionSpeed > 0) deletionSpeedBytesPerSec = deletionSpeed; }
setDeletionSpeed
1,651
Long () { return myProjectRebuildTime; }
getProjectRebuildTime
1,652
long () { return deletionSpeedBytesPerSec; }
getDeletionSpeedBytesPerSec
1,653
long () { return connectionSpeedBytesPerSec; }
getConnectionSpeedBytesPerSec
1,654
long () { return decompressionSpeedBytesPesSec; }
getDecompressionSpeedBytesPesSec
1,655
File () { return zipFile; }
getZipFile
1,656
String () { return downloadUrl; }
getDownloadUrl
1,657
AffectedModule () { return module; }
getModule
1,658
String () { return hash; }
getHash
1,659
String () { return relativePath; }
getRelativePath
1,660
boolean (Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BuildTargetState state = (BuildTargetState)o; if (!Objects.equals(hash, state.hash)) return false; if (!Objects.equals(relativePath, state.relativePath)) return false; return true; }
equals
1,661
int () { int result = hash != null ? hash.hashCode() : 0; result = 31 * result + (relativePath != null ? relativePath.hashCode() : 0); return result; }
hashCode
1,662
String () { return type; }
getType
1,663
String () { return name; }
getName
1,664
String () { return hash; }
getHash
1,665
File () { return outPath; }
getOutPath
1,666
boolean (Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AffectedModule module = (AffectedModule)o; if (type != null ? !type.equals(module.type) : module.type != null) return false; if (name != null ? !name.equals(module.name) : module.name != null) return false; if (hash != null ? !hash.equals(module.hash) : module.hash != null) return false; if (outPath != null ? !outPath.equals(module.outPath) : module.outPath != null) return false; return true; }
equals
1,667
int () { int result = type != null ? type.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (hash != null ? hash.hashCode() : 0); result = 31 * result + (outPath != null ? outPath.hashCode() : 0); return result; }
hashCode
1,668
String () { return commitId; }
getCommitId
1,669
void (@NotNull String message) { nettyClient.sendDescriptionStatusMessage(message); }
sendDescriptionStatusMessage
1,670
JpsNettyClient () { return nettyClient; }
getNettyClient
1,671
int () { return totalExpectedDownloads; }
getTotalExpectedDownloads
1,672
JpsLoaderContext (int totalExpectedDownloads, @NotNull CanceledStatus canceledStatus, @NotNull String commitId, @NotNull JpsNettyClient nettyClient, @NotNull Map<String, Map<String, BuildTargetState>> commitSourcesState, @Nullable Map<String, Map<String, BuildTargetState>> currentSourcesState) { return new JpsLoaderContext(totalExpectedDownloads, canceledStatus, commitId, nettyClient, commitSourcesState, currentSourcesState); }
createNewContext
1,673
String () { return myDownloadUrl; }
getDownloadUrl
1,674
String () { return myFileName + myFileExtension; }
getPresentableFileName
1,675
String () { return myDownloadUrl; }
getPresentableDownloadUrl
1,676
String () { return generateFileName(Conditions.alwaysTrue()); }
getDefaultFileName
1,677
String (@NotNull Condition<? super String> validator) { return UniqueNameGenerator.generateUniqueName("", myFileName, myFileExtension, "_", "", validator); }
generateFileName
1,678
boolean (Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DownloadableFileUrl that = (DownloadableFileUrl)o; return myDownloadUrl.equals(that.myDownloadUrl); }
equals
1,679
int () { return myDownloadUrl.hashCode(); }
hashCode
1,680
void (@NotNull Map<String, String> requestHeaders) { JpsServerAuthUtil.requestHeaders = requestHeaders; }
setRequestHeaders
1,681
JpsServerClient (@NotNull String serverUrl) { return new JpsServerClientImpl(serverUrl); }
getServerClient
1,682
void (@NotNull String message) { myChannel.writeAndFlush(CmdlineProtoUtil.toMessage(mySessionId, CmdlineProtoUtil.createCacheDownloadMessage(message))); }
sendDescriptionStatusMessage
1,683
void (@NotNull String message, int expectedDownloads) { int currentDownloads = currentDownloadsCount.incrementAndGet(); if (expectedDownloads == 0) { myChannel.writeAndFlush(CmdlineProtoUtil.toMessage(mySessionId, CmdlineProtoUtil.createCacheDownloadMessage(message))); } else { int doubleExpectedDownloads = expectedDownloads * 2 + 1000; myChannel.writeAndFlush(CmdlineProtoUtil.toMessage(mySessionId, CmdlineProtoUtil.createCacheDownloadMessageWithProgress(message, (float)currentDownloads / doubleExpectedDownloads))); } }
sendDescriptionStatusMessage
1,684
void (@NotNull String latestDownloadCommit, long decompressionTimeBytesPesSec, long deletionTimeBytesPerSec) { myChannel.writeAndFlush(CmdlineProtoUtil.toMessage(mySessionId, CmdlineProtoUtil.createSaveDownloadStatisticMessage(latestDownloadCommit, decompressionTimeBytesPesSec, deletionTimeBytesPerSec))); }
sendDownloadStatisticMessage
1,685
void (@NotNull Channel channel, @NotNull UUID sessionId) { channel.writeAndFlush(CmdlineProtoUtil.toMessage(sessionId, CmdlineProtoUtil.createSaveLatestBuiltCommitMessage())); }
saveLatestBuiltCommit
1,686
String (@NotNull String fileName) { byte[] decodedBytes = Base64.getDecoder().decode("aHR0cHM6Ly9kMWxjNWs5bGVyZzZrbS5jbG91ZGZyb250Lm5ldA=="); return new String(decodedBytes, StandardCharsets.UTF_8) + "/speed-test/" + fileName; }
calculateURL
1,687
boolean () { try { URL url = new URL("https://www.google.com/"); URLConnection connection = url.openConnection(); connection.setConnectTimeout(1000); connection.connect(); return true; } catch (Exception e) { LOG.info("Internet connection is not available"); return false; } }
checkInternetConnectionAvailable
1,688
String (long fileSize) { int rank = (int)((Math.log10(fileSize) + 0.0000021714778384307465) / 3); // (3 - Math.log10(999.995)) double value = fileSize / Math.pow(1000, rank); String[] units = {"Bit", "Kbit", "Mbit", "Gbit"}; return new DecimalFormat("0.##").format(value) + units[rank] + "/s"; }
formatInternetSpeed
1,689
List<OutputLoadResult> (@NotNull JpsLoaderContext context, @NotNull List<AffectedModule> affectedModules) { File targetDir = new File(PathManager.getPluginTempPath(), JpsCachesLoaderUtil.LOADER_TMP_FOLDER_NAME); if (targetDir.exists()) FileUtil.delete(targetDir); targetDir.mkdirs(); Map<String, AffectedModule> urlToModuleNameMap = affectedModules.stream().collect(Collectors.toMap( module -> myServerUrl + "/" + module.getType() + "/" + module.getName() + "/" + module.getHash(), module -> module)); List<DownloadableFileUrl> descriptions = ContainerUtil.map(urlToModuleNameMap.entrySet(), entry -> new DownloadableFileUrl(entry.getKey(), entry.getValue().getOutPath().getName() + ".zip")); JpsCachesDownloader downloader = new JpsCachesDownloader(descriptions, context.getNettyClient(), context); List<File> downloadedFiles = new ArrayList<>(); try { // Downloading process List<Pair<File, DownloadableFileUrl>> download = downloader.download(targetDir); downloadedFiles = ContainerUtil.map(download, pair -> pair.first); return ContainerUtil.map(download, pair -> { String downloadUrl = pair.second.getDownloadUrl(); return new OutputLoadResult(pair.first, downloadUrl, urlToModuleNameMap.get(downloadUrl)); }); } catch (ProcessCanceledException | IOException e) { //noinspection InstanceofCatchParameter if (e instanceof IOException) LOG.warn("Failed to download JPS compilation outputs", e); if (targetDir.exists()) FileUtil.delete(targetDir); downloadedFiles.forEach(zipFile -> FileUtil.delete(zipFile)); return null; } }
downloadCompiledModules
1,690
void () { try { get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } catch (CancellationException ignored) { } }
waitFor
1,691
boolean (long timeout, TimeUnit unit) { try { get(timeout, unit); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } catch (TimeoutException | CancellationException ignored) { } return isDone(); }
waitFor
1,692
boolean (boolean mayInterruptIfRunning) { return myFuture.cancel(mayInterruptIfRunning); }
cancel
1,693
boolean () { return myFuture.isCancelled(); }
isCancelled
1,694
boolean () { return myFuture.isDone(); }
isDone
1,695
Method () { try { return ReflectionUtil.getDeclaredMethod(ResourceBundle.class, "setParent", ResourceBundle.class); } catch (Throwable e) { return null; } }
getSetParentMethod
1,696
ResourceBundle ( @NotNull @NonNls String pathToBundle, @NotNull ClassLoader loader, @NotNull ResourceBundle.Control control ) { final ResourceBundle base = super.findBundle(pathToBundle, loader, control); final ClassLoader languageBundleLoader = ourLangBundleLoader; if (languageBundleLoader != null) { ResourceBundle languageBundle = super.findBundle(pathToBundle, languageBundleLoader, control); try { if (SET_PARENT != null) { SET_PARENT.invoke(languageBundle, base); } return languageBundle; } catch (Throwable e) { LOG.warn(e); } } return base; }
findBundle
1,697
UUID () { return myRequestID; }
getRequestID
1,698
T () { return myHandler; }
getMessageHandler
1,699
List<TargetTypeBuildScope> (final boolean forceBuild) { return Arrays.asList( createAllModulesProductionScope(forceBuild), createAllTargetsScope(JavaModuleBuildTargetType.TEST, forceBuild) ); }
createAllModulesScopes