From 4b764044aaf65d9518cc3b9c222e0c593628565b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=B3r=C3=A1nt=20Pint=C3=A9r?= Date: Mon, 8 Feb 2021 21:36:07 +0100 Subject: [PATCH 1/3] Add Spotless --- buildSrc/build.gradle.kts | 6 ++++++ .../src/main/kotlin/profiler.java-library.gradle.kts | 9 +++++++++ 2 files changed, 15 insertions(+) diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 3d7a9541..3cb75e28 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -5,3 +5,9 @@ plugins { repositories { jcenter() } + +dependencies { + implementation("com.diffplug.spotless:spotless-plugin-gradle:5.9.0") { + exclude(group = "org.codehaus.groovy", module = "groovy-xml") + } +} diff --git a/buildSrc/src/main/kotlin/profiler.java-library.gradle.kts b/buildSrc/src/main/kotlin/profiler.java-library.gradle.kts index 8ae7be78..fa0d6163 100644 --- a/buildSrc/src/main/kotlin/profiler.java-library.gradle.kts +++ b/buildSrc/src/main/kotlin/profiler.java-library.gradle.kts @@ -1,5 +1,6 @@ plugins { id("java-library") + id("com.diffplug.spotless") } repositories { @@ -15,6 +16,14 @@ java { } } +spotless { + java { + googleJavaFormat("1.8").aosp() + importOrder("", "javax", "java", "\\#") + removeUnusedImports() + } +} + project.extensions.create("versions") abstract class Versions { From 51b9fb24c9639934011e2bdfd03c3b44f86ad0aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=B3r=C3=A1nt=20Pint=C3=A9r?= Date: Mon, 8 Feb 2021 22:10:36 +0100 Subject: [PATCH 2/3] Apply Spotless changes to Java source code --- .../AdhocGradleScenarioDefinition.java | 46 +- .../profiler/AndroidStudioSyncAction.java | 7 +- .../gradle/profiler/ArgumentsSplitter.java | 5 +- .../profiler/BazelScenarioDefinition.java | 28 +- .../gradle/profiler/BazelScenarioInvoker.java | 8 +- .../profiler/BenchmarkResultCollector.java | 7 +- .../profiler/BuckScenarioDefinition.java | 30 +- .../gradle/profiler/BuckScenarioInvoker.java | 18 +- .../java/org/gradle/profiler/BuildAction.java | 60 ++- .../org/gradle/profiler/BuildInvoker.java | 39 +- .../org/gradle/profiler/BuildMutator.java | 41 +- .../profiler/BuildScenarioResultImpl.java | 3 +- .../java/org/gradle/profiler/BuildStep.java | 3 +- .../org/gradle/profiler/BuildStepAction.java | 26 +- .../profiler/BuildToolCommandLineInvoker.java | 31 +- ...uildToolCommandLineScenarioDefinition.java | 27 +- .../profiler/BuildUnderTestInvoker.java | 74 ++-- .../org/gradle/profiler/CliGradleClient.java | 60 ++- .../java/org/gradle/profiler/CommandExec.java | 122 ++++-- .../gradle/profiler/CommandLineParser.java | 185 +++++--- .../profiler/CompositeBuildMutator.java | 104 ++--- .../gradle/profiler/CompositeProfiler.java | 79 ++-- .../profiler/CompositeProfilerFactory.java | 5 +- .../java/org/gradle/profiler/ConfigUtil.java | 108 ++--- ...DefaultGradleBuildConfigurationReader.java | 56 ++- .../profiler/DefaultScenarioContext.java | 8 +- .../gradle/profiler/GeneratedInitScript.java | 4 +- .../profiler/GradleBuildConfiguration.java | 11 +- .../GradleBuildConfigurationReader.java | 5 +- .../profiler/GradleBuildInvocationResult.java | 62 +-- .../gradle/profiler/GradleBuildInvoker.java | 24 +- .../org/gradle/profiler/GradleClient.java | 3 +- .../org/gradle/profiler/GradleClientSpec.java | 132 +++--- .../gradle/profiler/GradleDaemonReuse.java | 3 +- .../org/gradle/profiler/GradleInvoker.java | 17 +- .../profiler/GradleInvokerBuildAction.java | 3 +- .../profiler/GradleScenarioDefinition.java | 60 ++- .../profiler/GradleScenarioInvoker.java | 101 +++-- .../profiler/InstrumentingProfiler.java | 98 +++-- .../gradle/profiler/InvocationSettings.java | 101 +++-- .../gradle/profiler/JvmArgsCalculator.java | 3 +- .../java/org/gradle/profiler/Logging.java | 13 +- src/main/java/org/gradle/profiler/Main.java | 69 ++- .../profiler/MavenScenarioDefinition.java | 28 +- .../gradle/profiler/MavenScenarioInvoker.java | 8 +- .../org/gradle/profiler/OperatingSystem.java | 3 +- src/main/java/org/gradle/profiler/Phase.java | 17 +- .../java/org/gradle/profiler/Profiler.java | 38 +- .../gradle/profiler/ProfilerController.java | 49 +-- .../org/gradle/profiler/ProfilerFactory.java | 58 +-- .../profiler/RecordingBuildStepAction.java | 14 +- .../org/gradle/profiler/ScenarioContext.java | 6 +- .../gradle/profiler/ScenarioDefinition.java | 41 +- .../org/gradle/profiler/ScenarioInvoker.java | 35 +- .../org/gradle/profiler/ScenarioLoader.java | 410 ++++++++++++------ .../org/gradle/profiler/ScenarioSettings.java | 3 +- .../profiler/StopDaemonAfterAction.java | 5 +- .../profiler/ToolingApiGradleClient.java | 66 +-- .../java/org/gradle/profiler/Version.java | 4 +- .../profiler/asyncprofiler/AsyncProfiler.java | 5 +- .../asyncprofiler/AsyncProfilerConfig.java | 9 +- .../AsyncProfilerController.java | 103 +++-- .../asyncprofiler/AsyncProfilerDownload.java | 61 ++- .../asyncprofiler/AsyncProfilerFactory.java | 87 ++-- ...ProfilerHeapAllocationProfilerFactory.java | 13 +- .../AsyncProfilerJvmArgsCalculator.java | 29 +- .../BuildOperationInstrumentation.java | 50 ++- .../profiler/buildops/BuildOperationUtil.java | 4 +- .../buildscan/BuildScanInitScript.java | 5 +- .../profiler/buildscan/BuildScanProfiler.java | 35 +- .../buildscan/BuildScanProfilerFactory.java | 4 +- .../buildscan/GradleEnterpriseInitScript.java | 10 +- .../ChromeTraceInstrumentation.java | 7 +- .../chrometrace/ChromeTraceProfiler.java | 3 +- .../flamegraph/FlameGraphSanitizer.java | 88 ++-- .../profiler/flamegraph/FlameGraphTool.java | 8 +- .../profiler/heapdump/HeapDumpProfiler.java | 10 +- .../instrument/GradleInstrumentation.java | 36 +- .../instrument/PidInstrumentation.java | 5 +- .../org/gradle/profiler/jfr/JFRControl.java | 3 +- .../profiler/jfr/JFRJvmArgsCalculator.java | 16 +- .../org/gradle/profiler/jfr/JcmdRunner.java | 6 +- .../profiler/jfr/JfrFlameGraphGenerator.java | 87 ++-- .../org/gradle/profiler/jfr/JfrProfiler.java | 12 +- .../profiler/jfr/JfrProfilerFactory.java | 13 +- .../profiler/jfr/JfrToStacksConverter.java | 106 +++-- .../gradle/profiler/jprofiler/JProfiler.java | 2 +- .../profiler/jprofiler/JProfilerConfig.java | 10 +- .../JProfilerConfigFileTransformer.java | 29 +- .../jprofiler/JProfilerController.java | 30 +- .../jprofiler/JProfilerJvmArgsCalculator.java | 21 +- .../profiler/jprofiler/JProfilerProfiler.java | 11 +- .../jprofiler/JProfilerProfilerFactory.java | 76 +++- ...uildMutatorWithoutOptionsConfigurator.java | 6 +- .../AbstractCacheCleanupMutator.java | 11 +- .../mutations/AbstractCleanupMutator.java | 24 +- .../mutations/AbstractFileChangeMutator.java | 3 +- .../mutations/AbstractGitMutator.java | 18 +- ...plyAbiChangeToKotlinSourceFileMutator.java | 4 +- ...ApplyChangeToAndroidLayoutFileMutator.java | 37 +- ...plyChangeToAndroidManifestFileMutator.java | 11 +- ...plyChangeToAndroidResourceFileMutator.java | 7 +- .../ApplyChangeToNativeSourceFileMutator.java | 7 +- ...lyNonAbiChangeToJavaSourceFileMutator.java | 12 +- ...NonAbiChangeToKotlinSourceFileMutator.java | 10 +- ...lueChangeToAndroidResourceFileMutator.java | 3 +- .../mutations/BuildMutatorConfigurator.java | 3 +- .../ClearArtifactTransformCacheMutator.java | 7 +- .../mutations/ClearBuildCacheMutator.java | 12 +- .../ClearConfigurationCacheStateMutator.java | 7 +- .../mutations/ClearGradleUserHomeMutator.java | 25 +- .../mutations/ClearJarsCacheMutator.java | 7 +- .../mutations/ClearProjectCacheMutator.java | 7 +- .../FileChangeMutatorConfigurator.java | 98 +++-- .../mutations/GitCheckoutMutator.java | 117 ++--- .../profiler/mutations/GitRevertMutator.java | 77 ++-- .../mutations/ShowBuildCacheSizeMutator.java | 78 ++-- .../profiler/report/AbstractGenerator.java | 4 +- .../profiler/report/BuildScenarioResult.java | 8 +- .../gradle/profiler/report/CsvGenerator.java | 33 +- .../gradle/profiler/report/HtmlGenerator.java | 56 ++- .../profiler/report/JsonResultWriter.java | 83 ++-- .../result/BuildInvocationResult.java | 23 +- .../profiler/studio/LaunchConfiguration.java | 15 +- .../studio/LauncherConfigurationParser.java | 28 +- .../profiler/studio/StudioGradleClient.java | 42 +- .../org/gradle/profiler/yourkit/YourKit.java | 15 +- .../yourkit/YourKitJvmArgsCalculator.java | 29 +- .../profiler/yourkit/YourKitProfiler.java | 11 +- .../yourkit/YourKitProfilerController.java | 18 +- .../trace/buildops/BuildOperationTrace.java | 107 +++-- .../pid/AbstractPidCollectorBuildService.java | 27 +- .../org/gradle/trace/pid/PidCollector.java | 9 +- .../pid/PidCollectorJava8BuildService.java | 14 +- .../gradle/trace/AsynchronousTraceWriter.java | 34 +- .../java/org/gradle/trace/CountEvent.java | 10 +- .../java/org/gradle/trace/DurationEvent.java | 18 +- .../org/gradle/trace/GradleTracingPlugin.java | 9 +- .../java/org/gradle/trace/TraceEvent.java | 3 +- .../java/org/gradle/trace/TraceResult.java | 5 +- .../BuildOperationListenerAdapter.java | 28 +- ...ildOperationListenerInvocationHandler.java | 40 +- ...Gradle33BuildOperationListenerAdapter.java | 11 +- ...ildOperationListenerInvocationHandler.java | 20 +- ...Gradle35BuildOperationListenerAdapter.java | 21 +- ...Gradle40BuildOperationListenerAdapter.java | 23 +- ...ildOperationListenerInvocationHandler.java | 21 +- ...Gradle47BuildOperationListenerAdapter.java | 10 +- ...ildOperationListenerInvocationHandler.java | 16 +- ...ildOperationListenerInvocationHandler.java | 11 +- .../gradle/trace/monitoring/GCMonitoring.java | 76 ++-- .../trace/monitoring/SystemMonitoring.java | 38 +- .../org/gradle/trace/stream/AsyncWriter.java | 13 +- .../profiler/client/protocol/Client.java | 4 +- .../profiler/client/protocol/Message.java | 3 +- .../profiler/client/protocol/Serializer.java | 37 +- .../profiler/client/protocol/Server.java | 19 +- .../org/gradle/trace/heapdump/HeapDump.java | 34 +- .../studio/instrumented/Interceptor.java | 18 +- .../gradle/profiler/studio/agent/Agent.java | 154 ++++--- 160 files changed, 3388 insertions(+), 2069 deletions(-) diff --git a/src/main/java/org/gradle/profiler/AdhocGradleScenarioDefinition.java b/src/main/java/org/gradle/profiler/AdhocGradleScenarioDefinition.java index 47115ccc..c51af218 100644 --- a/src/main/java/org/gradle/profiler/AdhocGradleScenarioDefinition.java +++ b/src/main/java/org/gradle/profiler/AdhocGradleScenarioDefinition.java @@ -7,31 +7,29 @@ public class AdhocGradleScenarioDefinition extends GradleScenarioDefinition { public AdhocGradleScenarioDefinition( - GradleBuildConfiguration version, - GradleBuildInvoker invoker, - BuildAction buildAction, - Map systemProperties, - int warmUpCount, - int buildCount, - File outputDir, - List measuredBuildOperations - ) { + GradleBuildConfiguration version, + GradleBuildInvoker invoker, + BuildAction buildAction, + Map systemProperties, + int warmUpCount, + int buildCount, + File outputDir, + List measuredBuildOperations) { super( - "default", - null, - invoker, - version, - buildAction, - BuildAction.NO_OP, - Collections.emptyList(), - systemProperties, - Collections.emptyList(), - warmUpCount, - buildCount, - outputDir, - Collections.emptyList(), - measuredBuildOperations - ); + "default", + null, + invoker, + version, + buildAction, + BuildAction.NO_OP, + Collections.emptyList(), + systemProperties, + Collections.emptyList(), + warmUpCount, + buildCount, + outputDir, + Collections.emptyList(), + measuredBuildOperations); } @Override diff --git a/src/main/java/org/gradle/profiler/AndroidStudioSyncAction.java b/src/main/java/org/gradle/profiler/AndroidStudioSyncAction.java index e784a31c..4579d9a5 100644 --- a/src/main/java/org/gradle/profiler/AndroidStudioSyncAction.java +++ b/src/main/java/org/gradle/profiler/AndroidStudioSyncAction.java @@ -5,12 +5,9 @@ import java.time.Duration; import java.util.List; -/** - * A mock-up of Android studio sync. - */ +/** A mock-up of Android studio sync. */ public class AndroidStudioSyncAction implements BuildAction { - public AndroidStudioSyncAction() { - } + public AndroidStudioSyncAction() {} @Override public String getShortDisplayName() { diff --git a/src/main/java/org/gradle/profiler/ArgumentsSplitter.java b/src/main/java/org/gradle/profiler/ArgumentsSplitter.java index a75b0dfe..7cac3a26 100644 --- a/src/main/java/org/gradle/profiler/ArgumentsSplitter.java +++ b/src/main/java/org/gradle/profiler/ArgumentsSplitter.java @@ -6,8 +6,9 @@ public class ArgumentsSplitter { /** - * Splits the arguments string (for example, a program command line) into a collection. - * Only supports space-delimited and/or quoted command line arguments. This currently does not handle escaping characters such as quotes. + * Splits the arguments string (for example, a program command line) into a collection. Only + * supports space-delimited and/or quoted command line arguments. This currently does not handle + * escaping characters such as quotes. * * @param arguments the arguments, for example command line args. * @return separate command line arguments. diff --git a/src/main/java/org/gradle/profiler/BazelScenarioDefinition.java b/src/main/java/org/gradle/profiler/BazelScenarioDefinition.java index 713c10b4..f01e3947 100644 --- a/src/main/java/org/gradle/profiler/BazelScenarioDefinition.java +++ b/src/main/java/org/gradle/profiler/BazelScenarioDefinition.java @@ -1,21 +1,29 @@ package org.gradle.profiler; import javax.annotation.Nullable; + import java.io.File; import java.util.List; public class BazelScenarioDefinition extends BuildToolCommandLineScenarioDefinition { public BazelScenarioDefinition( - String scenarioName, - @Nullable String title, - List targets, - List buildMutators, - int warmUpCount, - int buildCount, - File outputDir, - @Nullable File bazelHome - ) { - super(scenarioName, title, targets, buildMutators, warmUpCount, buildCount, outputDir, bazelHome); + String scenarioName, + @Nullable String title, + List targets, + List buildMutators, + int warmUpCount, + int buildCount, + File outputDir, + @Nullable File bazelHome) { + super( + scenarioName, + title, + targets, + buildMutators, + warmUpCount, + buildCount, + outputDir, + bazelHome); } @Override diff --git a/src/main/java/org/gradle/profiler/BazelScenarioInvoker.java b/src/main/java/org/gradle/profiler/BazelScenarioInvoker.java index 4651d040..b66826ff 100644 --- a/src/main/java/org/gradle/profiler/BazelScenarioInvoker.java +++ b/src/main/java/org/gradle/profiler/BazelScenarioInvoker.java @@ -6,9 +6,13 @@ import java.util.List; import java.util.function.Consumer; -public class BazelScenarioInvoker extends BuildToolCommandLineInvoker { +public class BazelScenarioInvoker + extends BuildToolCommandLineInvoker { @Override - void doRun(BazelScenarioDefinition scenario, InvocationSettings settings, Consumer resultConsumer) { + void doRun( + BazelScenarioDefinition scenario, + InvocationSettings settings, + Consumer resultConsumer) { List targets = scenario.getTargets(); List commandLine = new ArrayList<>(); diff --git a/src/main/java/org/gradle/profiler/BenchmarkResultCollector.java b/src/main/java/org/gradle/profiler/BenchmarkResultCollector.java index f7b6727b..44598926 100644 --- a/src/main/java/org/gradle/profiler/BenchmarkResultCollector.java +++ b/src/main/java/org/gradle/profiler/BenchmarkResultCollector.java @@ -20,7 +20,8 @@ public BenchmarkResultCollector(AbstractGenerator... generators) { this.generators = Arrays.asList(generators); } - public Consumer scenario(S scenario, List> samples) { + public Consumer scenario( + S scenario, List> samples) { BuildScenarioResultImpl buildScenario = new BuildScenarioResultImpl<>(scenario, samples); allBuilds.add(buildScenario); return buildScenario; @@ -32,9 +33,7 @@ public void write(InvocationSettings settings) throws IOException { } } - /** - * Summarize the results for the user. - */ + /** Summarize the results for the user. */ public void summarizeResults(Consumer consumer) { for (AbstractGenerator generator : generators) { generator.summarizeResults(consumer); diff --git a/src/main/java/org/gradle/profiler/BuckScenarioDefinition.java b/src/main/java/org/gradle/profiler/BuckScenarioDefinition.java index 44ff708e..9ddb8153 100644 --- a/src/main/java/org/gradle/profiler/BuckScenarioDefinition.java +++ b/src/main/java/org/gradle/profiler/BuckScenarioDefinition.java @@ -1,6 +1,7 @@ package org.gradle.profiler; import javax.annotation.Nullable; + import java.io.File; import java.io.PrintStream; import java.util.List; @@ -9,17 +10,24 @@ public class BuckScenarioDefinition extends BuildToolCommandLineScenarioDefiniti private final String type; public BuckScenarioDefinition( - String scenarioName, - @Nullable String title, - List targets, - String type, - List buildMutators, - int warmUpCount, - int buildCount, - File outputDir, - @Nullable File buckHome - ) { - super(scenarioName, title, targets, buildMutators, warmUpCount, buildCount, outputDir, buckHome); + String scenarioName, + @Nullable String title, + List targets, + String type, + List buildMutators, + int warmUpCount, + int buildCount, + File outputDir, + @Nullable File buckHome) { + super( + scenarioName, + title, + targets, + buildMutators, + warmUpCount, + buildCount, + outputDir, + buckHome); this.type = type; } diff --git a/src/main/java/org/gradle/profiler/BuckScenarioInvoker.java b/src/main/java/org/gradle/profiler/BuckScenarioInvoker.java index 3259cc2b..7033f4e2 100644 --- a/src/main/java/org/gradle/profiler/BuckScenarioInvoker.java +++ b/src/main/java/org/gradle/profiler/BuckScenarioInvoker.java @@ -8,9 +8,13 @@ import java.util.function.Consumer; import java.util.stream.Collectors; -public class BuckScenarioInvoker extends BuildToolCommandLineInvoker { +public class BuckScenarioInvoker + extends BuildToolCommandLineInvoker { @Override - void doRun(BuckScenarioDefinition scenario, InvocationSettings settings, Consumer resultConsumer) { + void doRun( + BuckScenarioDefinition scenario, + InvocationSettings settings, + Consumer resultConsumer) { String buckwExe = settings.getProjectDir() + "/buckw"; List targets = new ArrayList<>(scenario.getTargets()); if (scenario.getType() != null) { @@ -22,8 +26,14 @@ void doRun(BuckScenarioDefinition scenario, InvocationSettings settings, Consume commandLine.add("--type"); commandLine.add(scenario.getType()); } - String output = new CommandExec().inDir(settings.getProjectDir()).runAndCollectOutput(commandLine); - targets.addAll(Arrays.stream(output.split("\\n")).filter(s -> s.matches("//\\w+.*")).collect(Collectors.toList())); + String output = + new CommandExec() + .inDir(settings.getProjectDir()) + .runAndCollectOutput(commandLine); + targets.addAll( + Arrays.stream(output.split("\\n")) + .filter(s -> s.matches("//\\w+.*")) + .collect(Collectors.toList())); } Logging.detailed().println("* Buck targets: " + targets); diff --git a/src/main/java/org/gradle/profiler/BuildAction.java b/src/main/java/org/gradle/profiler/BuildAction.java index 2cb25db2..a0b196c2 100644 --- a/src/main/java/org/gradle/profiler/BuildAction.java +++ b/src/main/java/org/gradle/profiler/BuildAction.java @@ -3,46 +3,40 @@ import java.time.Duration; import java.util.List; -/** - * Runs some particular action against a Gradle build. - */ +/** Runs some particular action against a Gradle build. */ public interface BuildAction { - BuildAction NO_OP = new BuildAction() { - @Override - public boolean isDoesSomething() { - return false; - } - - @Override - public String getDisplayName() { - return "do nothing"; - } - - @Override - public String getShortDisplayName() { - return "nothing"; - } - - @Override - public Duration run(GradleClient gradleClient, List gradleArgs, List jvmArgs) { - return Duration.ZERO; - } - }; + BuildAction NO_OP = + new BuildAction() { + @Override + public boolean isDoesSomething() { + return false; + } + + @Override + public String getDisplayName() { + return "do nothing"; + } + + @Override + public String getShortDisplayName() { + return "nothing"; + } + + @Override + public Duration run( + GradleClient gradleClient, List gradleArgs, List jvmArgs) { + return Duration.ZERO; + } + }; boolean isDoesSomething(); - /** - * A human consumable display name for this action. - */ + /** A human consumable display name for this action. */ String getDisplayName(); - /** - * A human consumable display name for this action. - */ + /** A human consumable display name for this action. */ String getShortDisplayName(); - /** - * Runs the work of this action and returns the result. - */ + /** Runs the work of this action and returns the result. */ Duration run(GradleClient gradleClient, List gradleArgs, List jvmArgs); } diff --git a/src/main/java/org/gradle/profiler/BuildInvoker.java b/src/main/java/org/gradle/profiler/BuildInvoker.java index 138e26cf..dd01cb82 100644 --- a/src/main/java/org/gradle/profiler/BuildInvoker.java +++ b/src/main/java/org/gradle/profiler/BuildInvoker.java @@ -1,24 +1,27 @@ package org.gradle.profiler; public class BuildInvoker { - public static final BuildInvoker Bazel = new BuildInvoker() { - @Override - public String toString() { - return "Bazel"; - } - }; - public static final BuildInvoker Buck = new BuildInvoker() { - @Override - public String toString() { - return "Buck"; - } - }; - public static final BuildInvoker Maven = new BuildInvoker() { - @Override - public String toString() { - return "Maven"; - } - }; + public static final BuildInvoker Bazel = + new BuildInvoker() { + @Override + public String toString() { + return "Bazel"; + } + }; + public static final BuildInvoker Buck = + new BuildInvoker() { + @Override + public String toString() { + return "Buck"; + } + }; + public static final BuildInvoker Maven = + new BuildInvoker() { + @Override + public String toString() { + return "Maven"; + } + }; public int benchmarkWarmUps() { return 6; diff --git a/src/main/java/org/gradle/profiler/BuildMutator.java b/src/main/java/org/gradle/profiler/BuildMutator.java index ccd1cea1..059a9099 100644 --- a/src/main/java/org/gradle/profiler/BuildMutator.java +++ b/src/main/java/org/gradle/profiler/BuildMutator.java @@ -1,45 +1,32 @@ package org.gradle.profiler; public interface BuildMutator { - /** - * Validates if the mutator works with the given invoker. - */ + /** Validates if the mutator works with the given invoker. */ default void validate(BuildInvoker invoker) {} - /** - * Runs before the first iteration of the scenario. - */ + /** Runs before the first iteration of the scenario. */ default void beforeScenario(ScenarioContext context) {} - /** - * Runs before each iteration if cleanup tasks are declared. - */ + /** Runs before each iteration if cleanup tasks are declared. */ default void beforeCleanup(BuildContext context) {} - /** - * Runs after each iteration of cleanup has finished. - */ + /** Runs after each iteration of cleanup has finished. */ default void afterCleanup(BuildContext context, Throwable error) {} - /** - * Runs before starting an iteration of the build, after any potential cleanup has finished. - */ + /** Runs before starting an iteration of the build, after any potential cleanup has finished. */ default void beforeBuild(BuildContext context) {} - /** - * Runs after each iteration of the build has finished. - */ + /** Runs after each iteration of the build has finished. */ default void afterBuild(BuildContext context, Throwable error) {} - /** - * Runs after the last iteration of the scenario has finished. - */ + /** Runs after the last iteration of the scenario has finished. */ default void afterScenario(ScenarioContext context) {} - BuildMutator NOOP = new BuildMutator() { - @Override - public String toString() { - return "none"; - } - }; + BuildMutator NOOP = + new BuildMutator() { + @Override + public String toString() { + return "none"; + } + }; } diff --git a/src/main/java/org/gradle/profiler/BuildScenarioResultImpl.java b/src/main/java/org/gradle/profiler/BuildScenarioResultImpl.java index 8c14a6ca..37d41ae1 100644 --- a/src/main/java/org/gradle/profiler/BuildScenarioResultImpl.java +++ b/src/main/java/org/gradle/profiler/BuildScenarioResultImpl.java @@ -10,7 +10,8 @@ import java.util.List; import java.util.function.Consumer; -public class BuildScenarioResultImpl implements BuildScenarioResult, Consumer { +public class BuildScenarioResultImpl + implements BuildScenarioResult, Consumer { private final ScenarioDefinition scenario; private final List> samples; private final List results = new ArrayList<>(); diff --git a/src/main/java/org/gradle/profiler/BuildStep.java b/src/main/java/org/gradle/profiler/BuildStep.java index 75ce8d27..0844b036 100644 --- a/src/main/java/org/gradle/profiler/BuildStep.java +++ b/src/main/java/org/gradle/profiler/BuildStep.java @@ -1,5 +1,6 @@ package org.gradle.profiler; public enum BuildStep { - CLEANUP, BUILD + CLEANUP, + BUILD } diff --git a/src/main/java/org/gradle/profiler/BuildStepAction.java b/src/main/java/org/gradle/profiler/BuildStepAction.java index f2e61b06..751b92af 100644 --- a/src/main/java/org/gradle/profiler/BuildStepAction.java +++ b/src/main/java/org/gradle/profiler/BuildStepAction.java @@ -3,22 +3,22 @@ import org.gradle.profiler.result.BuildInvocationResult; public interface BuildStepAction { - BuildStepAction NO_OP = new BuildStepAction() { - @Override - public boolean isDoesSomething() { - return false; - } + BuildStepAction NO_OP = + new BuildStepAction() { + @Override + public boolean isDoesSomething() { + return false; + } - @Override - public GradleBuildInvocationResult run(BuildContext buildContext, BuildStep buildStep) { - return null; - } - }; + @Override + public GradleBuildInvocationResult run( + BuildContext buildContext, BuildStep buildStep) { + return null; + } + }; boolean isDoesSomething(); - /** - * Runs a single build step. - */ + /** Runs a single build step. */ T run(BuildContext buildContext, BuildStep buildStep); } diff --git a/src/main/java/org/gradle/profiler/BuildToolCommandLineInvoker.java b/src/main/java/org/gradle/profiler/BuildToolCommandLineInvoker.java index 21b109f6..2ed63e0c 100644 --- a/src/main/java/org/gradle/profiler/BuildToolCommandLineInvoker.java +++ b/src/main/java/org/gradle/profiler/BuildToolCommandLineInvoker.java @@ -11,8 +11,14 @@ import static org.gradle.profiler.Phase.MEASURE; import static org.gradle.profiler.Phase.WARM_UP; -public abstract class BuildToolCommandLineInvoker extends ScenarioInvoker { - void doRun(T scenario, InvocationSettings settings, Consumer resultConsumer, List commandLine) { +public abstract class BuildToolCommandLineInvoker< + T extends BuildToolCommandLineScenarioDefinition, R extends BuildInvocationResult> + extends ScenarioInvoker { + void doRun( + T scenario, + InvocationSettings settings, + Consumer resultConsumer, + List commandLine) { ScenarioContext scenarioContext = ScenarioContext.from(settings, scenario); BuildMutator mutator = new CompositeBuildMutator(scenario.getBuildMutators()); @@ -20,21 +26,30 @@ void doRun(T scenario, InvocationSettings settings, Consumer measureCommandLineExecution(List commandLine, File workingDir, File buildLog) { + /** Returns a {@link Supplier} that returns the result of the given command. */ + private BuildStepAction measureCommandLineExecution( + List commandLine, File workingDir, File buildLog) { return new BuildStepAction() { @Override public boolean isDoesSomething() { diff --git a/src/main/java/org/gradle/profiler/BuildToolCommandLineScenarioDefinition.java b/src/main/java/org/gradle/profiler/BuildToolCommandLineScenarioDefinition.java index 39a04afc..03282769 100644 --- a/src/main/java/org/gradle/profiler/BuildToolCommandLineScenarioDefinition.java +++ b/src/main/java/org/gradle/profiler/BuildToolCommandLineScenarioDefinition.java @@ -1,6 +1,7 @@ package org.gradle.profiler; import javax.annotation.Nullable; + import java.io.File; import java.io.PrintStream; import java.util.List; @@ -10,15 +11,14 @@ public abstract class BuildToolCommandLineScenarioDefinition extends ScenarioDef private final File toolHome; public BuildToolCommandLineScenarioDefinition( - String name, - @Nullable String title, - List targets, - List buildMutators, - int warmUpCount, - int buildCount, - File outputDir, - @Nullable File toolHome - ) { + String name, + @Nullable String title, + List targets, + List buildMutators, + int warmUpCount, + int buildCount, + File outputDir, + @Nullable File toolHome) { super(name, title, buildMutators, warmUpCount, buildCount, outputDir); this.targets = targets; this.toolHome = toolHome; @@ -34,8 +34,13 @@ protected void printDetail(PrintStream out) { } public String getExecutablePath() { - String toolHomePath = getToolHome() == null ? System.getenv(getToolHomeEnvName()) : getToolHome().getAbsolutePath(); - return toolHomePath == null ? getExecutableName() : toolHomePath + "/bin/" + getExecutableName(); + String toolHomePath = + getToolHome() == null + ? System.getenv(getToolHomeEnvName()) + : getToolHome().getAbsolutePath(); + return toolHomePath == null + ? getExecutableName() + : toolHomePath + "/bin/" + getExecutableName(); } @Override diff --git a/src/main/java/org/gradle/profiler/BuildUnderTestInvoker.java b/src/main/java/org/gradle/profiler/BuildUnderTestInvoker.java index cc5a6d19..792a03f9 100644 --- a/src/main/java/org/gradle/profiler/BuildUnderTestInvoker.java +++ b/src/main/java/org/gradle/profiler/BuildUnderTestInvoker.java @@ -10,9 +10,7 @@ import java.util.Map; import java.util.Optional; -/** - * Runs a single invocation of a Gradle build and collects the result. - */ +/** Runs a single invocation of a Gradle build and collects the result. */ public class BuildUnderTestInvoker { private final List jvmArgs; private final List gradleArgs; @@ -21,7 +19,12 @@ public class BuildUnderTestInvoker { private final BuildOperationInstrumentation buildOperationInstrumentation; private final Map previousGcTimes = new HashMap<>(); - public BuildUnderTestInvoker(List jvmArgs, List gradleArgs, GradleClient gradleClient, PidInstrumentation pidInstrumentation, BuildOperationInstrumentation buildOperationInstrumentation) { + public BuildUnderTestInvoker( + List jvmArgs, + List gradleArgs, + GradleClient gradleClient, + PidInstrumentation pidInstrumentation, + BuildOperationInstrumentation buildOperationInstrumentation) { this.jvmArgs = jvmArgs; this.gradleArgs = gradleArgs; this.gradleClient = gradleClient; @@ -61,28 +64,44 @@ public GradleBuildInvocationResult run(BuildContext buildContext, BuildStep buil String pid = pidInstrumentation.getPidForLastBuild(); Logging.detailed().printf("Used daemon with pid %s%n", pid); - Optional garbageCollectionTime = buildOperationInstrumentation.getTotalGarbageCollectionTime() - .map(currentTotal -> { - Duration previousTotal = previousGcTimes.getOrDefault(pid, Duration.ZERO); - previousGcTimes.put(pid, currentTotal); - return currentTotal.minus(previousTotal); - }); - Optional timeToTaskExecution = buildOperationInstrumentation.getTimeToTaskExecution(); - - Map cumulativeBuildOperationTimes = buildOperationInstrumentation.getCumulativeBuildOperationTimes(); - cumulativeBuildOperationTimes.forEach((opName, duration) -> { - Logging.detailed().printf("Cumulative build operation time %s ms for %s%n", duration.toMillis(), opName); - }); - garbageCollectionTime.ifPresent(duration -> Logging.detailed().printf("Total GC time: %d ms%n", duration.toMillis())); - timeToTaskExecution.ifPresent(duration -> Logging.detailed().printf("Time to task execution %d ms%n", duration.toMillis())); + Optional garbageCollectionTime = + buildOperationInstrumentation + .getTotalGarbageCollectionTime() + .map( + currentTotal -> { + Duration previousTotal = + previousGcTimes.getOrDefault(pid, Duration.ZERO); + previousGcTimes.put(pid, currentTotal); + return currentTotal.minus(previousTotal); + }); + Optional timeToTaskExecution = + buildOperationInstrumentation.getTimeToTaskExecution(); + + Map cumulativeBuildOperationTimes = + buildOperationInstrumentation.getCumulativeBuildOperationTimes(); + cumulativeBuildOperationTimes.forEach( + (opName, duration) -> { + Logging.detailed() + .printf( + "Cumulative build operation time %s ms for %s%n", + duration.toMillis(), opName); + }); + garbageCollectionTime.ifPresent( + duration -> + Logging.detailed() + .printf("Total GC time: %d ms%n", duration.toMillis())); + timeToTaskExecution.ifPresent( + duration -> + Logging.detailed() + .printf("Time to task execution %d ms%n", duration.toMillis())); return new GradleBuildInvocationResult( - buildContext, - executionTime, - garbageCollectionTime.orElse(null), - timeToTaskExecution.orElse(null), - cumulativeBuildOperationTimes, - pid); + buildContext, + executionTime, + garbageCollectionTime.orElse(null), + timeToTaskExecution.orElse(null), + cumulativeBuildOperationTimes, + pid); } } @@ -101,6 +120,11 @@ public BuildUnderTestInvoker withGradleArgs(List gradleArgs) { } private BuildUnderTestInvoker copy(List jvmArgs, List gradleArgs) { - return new BuildUnderTestInvoker(jvmArgs, gradleArgs, gradleClient, pidInstrumentation, buildOperationInstrumentation); + return new BuildUnderTestInvoker( + jvmArgs, + gradleArgs, + gradleClient, + pidInstrumentation, + buildOperationInstrumentation); } } diff --git a/src/main/java/org/gradle/profiler/CliGradleClient.java b/src/main/java/org/gradle/profiler/CliGradleClient.java index 70af6013..65acf776 100644 --- a/src/main/java/org/gradle/profiler/CliGradleClient.java +++ b/src/main/java/org/gradle/profiler/CliGradleClient.java @@ -16,11 +16,12 @@ public class CliGradleClient implements GradleInvoker, GradleClient { private final boolean daemon; private final File buildLog; - public CliGradleClient(GradleBuildConfiguration gradleBuildConfiguration, - File javaHome, - File projectDir, - boolean daemon, - File buildLog) { + public CliGradleClient( + GradleBuildConfiguration gradleBuildConfiguration, + File javaHome, + File projectDir, + boolean daemon, + File buildLog) { this.gradleBuildConfiguration = gradleBuildConfiguration; this.javaHome = javaHome; this.projectDir = projectDir; @@ -29,17 +30,27 @@ public CliGradleClient(GradleBuildConfiguration gradleBuildConfiguration, } @Override - public void close() { - } + public void close() {} @Override - public void loadToolingModel(List tasks, List gradleArgs, List jvmArgs, Class toolingModel) { - throw new UnsupportedOperationException("Cannot fetch a tooling API model using the Gradle CLI."); + public void loadToolingModel( + List tasks, + List gradleArgs, + List jvmArgs, + Class toolingModel) { + throw new UnsupportedOperationException( + "Cannot fetch a tooling API model using the Gradle CLI."); } @Override - public T runToolingAction(List tasks, List gradleArgs, List jvmArgs, BuildAction action, Consumer> configureAction) { - throw new UnsupportedOperationException("Cannot run a tooling API action using the Gradle CLI."); + public T runToolingAction( + List tasks, + List gradleArgs, + List jvmArgs, + BuildAction action, + Consumer> configureAction) { + throw new UnsupportedOperationException( + "Cannot run a tooling API action using the Gradle CLI."); } @Override @@ -58,10 +69,12 @@ public void runTasks(List tasks, List gradleArgs, List j ProcessBuilder builder = new ProcessBuilder(commandLine); builder.directory(projectDir); if (daemon) { - String orgGradleJvmArgs = jvmArgs.isEmpty() - ? "" - : " \"-Dorg.gradle.jvmargs=" + gradleOpts + "\""; - builder.environment().put("GRADLE_OPTS", "-Xmx128m -Xms128m -XX:+HeapDumpOnOutOfMemoryError" + orgGradleJvmArgs); + String orgGradleJvmArgs = + jvmArgs.isEmpty() ? "" : " \"-Dorg.gradle.jvmargs=" + gradleOpts + "\""; + builder.environment() + .put( + "GRADLE_OPTS", + "-Xmx128m -Xms128m -XX:+HeapDumpOnOutOfMemoryError" + orgGradleJvmArgs); } else { Logging.detailed().println("GRADLE_OPTS: " + gradleOpts); builder.environment().put("GRADLE_OPTS", gradleOpts); @@ -86,12 +99,15 @@ public void runTasks(List tasks, List gradleArgs, List j private static String quoteJvmArguments(boolean forSystemProperty, List jvmArgs) { char quotes = forSystemProperty ? '\'' : '"'; return jvmArgs.stream() - .peek(arg -> { - if (arg.contains("\"") || arg.contains("'")) { - throw new IllegalArgumentException("jvmArgs must not contain quotes, but this argument does: " + arg); - } - }) - .map(arg -> quotes + arg + quotes) - .collect(Collectors.joining(" ")); + .peek( + arg -> { + if (arg.contains("\"") || arg.contains("'")) { + throw new IllegalArgumentException( + "jvmArgs must not contain quotes, but this argument does: " + + arg); + } + }) + .map(arg -> quotes + arg + quotes) + .collect(Collectors.joining(" ")); } } diff --git a/src/main/java/org/gradle/profiler/CommandExec.java b/src/main/java/org/gradle/profiler/CommandExec.java index 0161c752..3c04cb07 100644 --- a/src/main/java/org/gradle/profiler/CommandExec.java +++ b/src/main/java/org/gradle/profiler/CommandExec.java @@ -1,6 +1,7 @@ package org.gradle.profiler; import javax.annotation.Nullable; + import java.io.*; import java.lang.reflect.Field; import java.util.Collection; @@ -49,7 +50,8 @@ public String runAndCollectOutput(List commandLine) { public String runAndCollectOutput(String... commandLine) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { - start(new ProcessBuilder(commandLine), outputStream, outputStream::toString, null).waitForSuccess(); + start(new ProcessBuilder(commandLine), outputStream, outputStream::toString, null) + .waitForSuccess(); } catch (RuntimeException e) { System.out.print(new String(outputStream.toByteArray())); throw e; @@ -63,7 +65,12 @@ public void runAndCollectOutput(File outputFile, Collection commandLine) public void runAndCollectOutput(File outputFile, String... commandLine) { OutputStream outputStream = createFileOutputStream(outputFile); - start(new ProcessBuilder(commandLine), outputStream, () -> "See build log " + outputFile + " for details", null).waitForSuccess(); + start( + new ProcessBuilder(commandLine), + outputStream, + () -> "See build log " + outputFile + " for details", + null) + .waitForSuccess(); } private OutputStream createFileOutputStream(File outputFile) { @@ -76,7 +83,12 @@ private OutputStream createFileOutputStream(File outputFile) { public void runAndCollectOutput(File outputFile, ProcessBuilder processBuilder) { OutputStream outputStream = createFileOutputStream(outputFile); - start(processBuilder, outputStream, () -> "See build log " + outputFile + " for details", null).waitForSuccess(); + start( + processBuilder, + outputStream, + () -> "See build log " + outputFile + " for details", + null) + .waitForSuccess(); } public void run(ProcessBuilder processBuilder) { @@ -89,7 +101,11 @@ public RunHandle start(ProcessBuilder processBuilder) { return start(processBuilder, new TeeOutputStream(outputStream, baos), baos::toString, null); } - private RunHandle start(ProcessBuilder processBuilder, OutputStream outputStream, Supplier diagnosticOutput, @Nullable InputStream inputStream) { + private RunHandle start( + ProcessBuilder processBuilder, + OutputStream outputStream, + Supplier diagnosticOutput, + @Nullable InputStream inputStream) { if (directory != null) { processBuilder.directory(directory); } @@ -101,53 +117,61 @@ private RunHandle start(ProcessBuilder processBuilder, OutputStream outputStream processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); ExecutorService executor = Executors.newFixedThreadPool(3); - executor.execute(() -> { - byte[] buffer = new byte[4096]; - while (true) { - if (readStream(process.getInputStream(), outputStream, command, buffer)) { - break; - } - } - }); - executor.execute(() -> { - byte[] buffer = new byte[4096]; - while (true) { - if (readStream(process.getErrorStream(), outputStream, command, buffer)) { - break; - } - } - }); - if (inputStream != null) { - executor.execute(() -> { - byte[] buffer = new byte[4096]; - OutputStream output = process.getOutputStream(); - while (true) { - try { - int read = inputStream.read(buffer); - output.write(buffer); - if (read == -1) { - output.flush(); - output.close(); + executor.execute( + () -> { + byte[] buffer = new byte[4096]; + while (true) { + if (readStream( + process.getInputStream(), outputStream, command, buffer)) { break; } - } catch (IOException e) { - throw new RuntimeException("Could not write input", e); } - } - }); + }); + executor.execute( + () -> { + byte[] buffer = new byte[4096]; + while (true) { + if (readStream( + process.getErrorStream(), outputStream, command, buffer)) { + break; + } + } + }); + if (inputStream != null) { + executor.execute( + () -> { + byte[] buffer = new byte[4096]; + OutputStream output = process.getOutputStream(); + while (true) { + try { + int read = inputStream.read(buffer); + output.write(buffer); + if (read == -1) { + output.flush(); + output.close(); + break; + } + } catch (IOException e) { + throw new RuntimeException("Could not write input", e); + } + } + }); } return new RunHandle(processBuilder, process, diagnosticOutput, executor); } catch (IOException e) { - throw new RuntimeException(commandErrorMessage(processBuilder, diagnosticOutput.get()), e); + throw new RuntimeException( + commandErrorMessage(processBuilder, diagnosticOutput.get()), e); } } - private boolean readStream(InputStream inputStream, OutputStream outputStream, String command, byte[] buffer) { + private boolean readStream( + InputStream inputStream, OutputStream outputStream, String command, byte[] buffer) { int nread; try { nread = inputStream.read(buffer); } catch (IOException e) { - throw new RuntimeException("Could not read input from child process for command '" + command + "'", e); + throw new RuntimeException( + "Could not read input from child process for command '" + command + "'", e); } if (nread < 0) { return true; @@ -155,18 +179,22 @@ private boolean readStream(InputStream inputStream, OutputStream outputStream, S try { outputStream.write(buffer, 0, nread); } catch (IOException e) { - throw new RuntimeException("Could not write output from child process for command '" + command + "'", e); + throw new RuntimeException( + "Could not write output from child process for command '" + command + "'", e); } finally { try { outputStream.flush(); } catch (IOException e) { - throw new RuntimeException("Could not write output from child process for command '" + command + "'", e); + throw new RuntimeException( + "Could not write output from child process for command '" + command + "'", + e); } } return false; } - private static String commandErrorMessage(ProcessBuilder processBuilder, String diagnosticOutput) { + private static String commandErrorMessage( + ProcessBuilder processBuilder, String diagnosticOutput) { String message = "Could not run command " + String.join(" ", processBuilder.command()); if (!diagnosticOutput.isEmpty()) { message += "\nOutput:\n======\n" + diagnosticOutput + "======"; @@ -180,7 +208,11 @@ public class RunHandle { private final Supplier diagnosticOutput; private final ExecutorService executor; - RunHandle(ProcessBuilder processBuilder, Process process, Supplier diagnosticOutput, ExecutorService executor) { + RunHandle( + ProcessBuilder processBuilder, + Process process, + Supplier diagnosticOutput, + ExecutorService executor) { this.processBuilder = processBuilder; this.process = process; this.diagnosticOutput = diagnosticOutput; @@ -198,10 +230,12 @@ public void waitForSuccess() { shutdownExecutor(); } if (failure != null) { - throw new RuntimeException(commandErrorMessage(processBuilder, diagnosticOutput.get()), failure); + throw new RuntimeException( + commandErrorMessage(processBuilder, diagnosticOutput.get()), failure); } if (result != 0) { - throw new RuntimeException(commandErrorMessage(processBuilder, diagnosticOutput.get())); + throw new RuntimeException( + commandErrorMessage(processBuilder, diagnosticOutput.get())); } } diff --git a/src/main/java/org/gradle/profiler/CommandLineParser.java b/src/main/java/org/gradle/profiler/CommandLineParser.java index 14438385..ce1e96e1 100644 --- a/src/main/java/org/gradle/profiler/CommandLineParser.java +++ b/src/main/java/org/gradle/profiler/CommandLineParser.java @@ -10,6 +10,7 @@ import org.gradle.profiler.report.CsvGenerator.Format; import javax.annotation.Nullable; + import java.io.File; import java.io.IOException; import java.util.Arrays; @@ -20,61 +21,101 @@ import java.util.stream.Stream; class CommandLineParser { - public static class SettingsNotAvailableException extends RuntimeException { - } + public static class SettingsNotAvailableException extends RuntimeException {} - /** - * Returns null on parse failure. - */ + /** Returns null on parse failure. */ @Nullable - public InvocationSettings parseSettings(String[] args) throws IOException, SettingsNotAvailableException { + public InvocationSettings parseSettings(String[] args) + throws IOException, SettingsNotAvailableException { OptionParser parser = new OptionParser(); - AbstractOptionSpec helpOption = parser.acceptsAll(Arrays.asList("h", "help"), "Show this usage information") - .forHelp(); - AbstractOptionSpec versionOption = parser.acceptsAll(Arrays.asList("v", "version"), "Display version information"); + AbstractOptionSpec helpOption = + parser.acceptsAll(Arrays.asList("h", "help"), "Show this usage information") + .forHelp(); + AbstractOptionSpec versionOption = + parser.acceptsAll(Arrays.asList("v", "version"), "Display version information"); parser.nonOptions("The scenarios or task names to run"); - ArgumentAcceptingOptionSpec projectOption = parser.accepts("project-dir", "The directory containing the build to run") - .withRequiredArg().ofType(File.class).defaultsTo(new File(".").getCanonicalFile()); - ArgumentAcceptingOptionSpec gradleVersionOption = parser.accepts("gradle-version", "Gradle version or installation to use to run build") - .withRequiredArg(); - ArgumentAcceptingOptionSpec gradleUserHomeOption = parser.accepts("gradle-user-home", "The Gradle user home to use") - .withRequiredArg() - .ofType(File.class) - .defaultsTo(new File("gradle-user-home")); - ArgumentAcceptingOptionSpec studioHomeOption = parser.accepts("studio-install-dir", "The Studio installation to use").withRequiredArg().ofType(File.class); - ArgumentAcceptingOptionSpec scenarioFileOption = parser.accepts("scenario-file", "Scenario definition file to use").withRequiredArg().ofType(File.class); - ArgumentAcceptingOptionSpec sysPropOption = parser.accepts("D", "Defines a system property").withRequiredArg(); - ArgumentAcceptingOptionSpec outputDirOption = parser.accepts("output-dir", "Directory to write results to").withRequiredArg() - .ofType(File.class).defaultsTo(findOutputDir()); - ArgumentAcceptingOptionSpec warmupsOption = parser.accepts("warmups", "Number of warm-up build to run for each scenario").withRequiredArg().ofType(Integer.class); - ArgumentAcceptingOptionSpec iterationsOption = parser.accepts("iterations", "Number of builds to run for each scenario").withRequiredArg().ofType(Integer.class); - ArgumentAcceptingOptionSpec profilerOption = parser.accepts("profile", - "Collect profiling information using profiler (" + String.join(", ", ProfilerFactory.getAvailableProfilers()) + ")") - .withRequiredArg() - .defaultsTo("jfr"); + ArgumentAcceptingOptionSpec projectOption = + parser.accepts("project-dir", "The directory containing the build to run") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File(".").getCanonicalFile()); + ArgumentAcceptingOptionSpec gradleVersionOption = + parser.accepts( + "gradle-version", + "Gradle version or installation to use to run build") + .withRequiredArg(); + ArgumentAcceptingOptionSpec gradleUserHomeOption = + parser.accepts("gradle-user-home", "The Gradle user home to use") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File("gradle-user-home")); + ArgumentAcceptingOptionSpec studioHomeOption = + parser.accepts("studio-install-dir", "The Studio installation to use") + .withRequiredArg() + .ofType(File.class); + ArgumentAcceptingOptionSpec scenarioFileOption = + parser.accepts("scenario-file", "Scenario definition file to use") + .withRequiredArg() + .ofType(File.class); + ArgumentAcceptingOptionSpec sysPropOption = + parser.accepts("D", "Defines a system property").withRequiredArg(); + ArgumentAcceptingOptionSpec outputDirOption = + parser.accepts("output-dir", "Directory to write results to") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(findOutputDir()); + ArgumentAcceptingOptionSpec warmupsOption = + parser.accepts("warmups", "Number of warm-up build to run for each scenario") + .withRequiredArg() + .ofType(Integer.class); + ArgumentAcceptingOptionSpec iterationsOption = + parser.accepts("iterations", "Number of builds to run for each scenario") + .withRequiredArg() + .ofType(Integer.class); + ArgumentAcceptingOptionSpec profilerOption = + parser.accepts( + "profile", + "Collect profiling information using profiler (" + + String.join(", ", ProfilerFactory.getAvailableProfilers()) + + ")") + .withRequiredArg() + .defaultsTo("jfr"); ProfilerFactory.configureParser(parser); - OptionSpecBuilder benchmarkOption = parser.accepts("benchmark", "Collect benchmark metrics"); - ArgumentAcceptingOptionSpec benchmarkBuildOperation = parser.accepts( - "measure-build-op", - "Collect benchmark metrics for build operation" - ).withRequiredArg(); - OptionSpecBuilder noDaemonOption = parser.accepts("no-daemon", "Do not use the Gradle daemon"); - OptionSpecBuilder coldDaemonOption = parser.accepts("cold-daemon", "Use a cold Gradle daemon"); - OptionSpecBuilder cliOption = parser.accepts("cli", "Uses the command-line client to connect to the daemon"); - OptionSpecBuilder measureGarbageCollectionOption = parser.accepts("measure-gc", "Measure the GC time during each invocation"); - OptionSpecBuilder measureConfigTimeOption = parser.accepts("measure-config-time", "Include a breakdown of configuration time in benchmark results"); + OptionSpecBuilder benchmarkOption = + parser.accepts("benchmark", "Collect benchmark metrics"); + ArgumentAcceptingOptionSpec benchmarkBuildOperation = + parser.accepts("measure-build-op", "Collect benchmark metrics for build operation") + .withRequiredArg(); + OptionSpecBuilder noDaemonOption = + parser.accepts("no-daemon", "Do not use the Gradle daemon"); + OptionSpecBuilder coldDaemonOption = + parser.accepts("cold-daemon", "Use a cold Gradle daemon"); + OptionSpecBuilder cliOption = + parser.accepts("cli", "Uses the command-line client to connect to the daemon"); + OptionSpecBuilder measureGarbageCollectionOption = + parser.accepts("measure-gc", "Measure the GC time during each invocation"); + OptionSpecBuilder measureConfigTimeOption = + parser.accepts( + "measure-config-time", + "Include a breakdown of configuration time in benchmark results"); OptionSpecBuilder dryRunOption = parser.accepts("dry-run", "Verify configuration"); OptionSpecBuilder bazelOption = parser.accepts("bazel", "Benchmark scenarios using Bazel"); OptionSpecBuilder buckOption = parser.accepts("buck", "Benchmark scenarios using buck"); OptionSpecBuilder mavenOption = parser.accepts("maven", "Benchmark scenarios using Maven"); - ArgumentAcceptingOptionSpec csvFormatOption = parser.accepts("csv-format", - "The CSV format produced (" + Stream.of(Format.values()).map(Format::toString).collect(Collectors.joining(", ")) + ")") - .withRequiredArg() - .defaultsTo("wide"); - ArgumentAcceptingOptionSpec benchmarkTitleOption = parser.accepts("title", - "Title to show on benchmark report") - .withOptionalArg() - .ofType(String.class); + ArgumentAcceptingOptionSpec csvFormatOption = + parser.accepts( + "csv-format", + "The CSV format produced (" + + Stream.of(Format.values()) + .map(Format::toString) + .collect(Collectors.joining(", ")) + + ")") + .withRequiredArg() + .defaultsTo("wide"); + ArgumentAcceptingOptionSpec benchmarkTitleOption = + parser.accepts("title", "Title to show on benchmark report") + .withOptionalArg() + .ofType(String.class); OptionSet parsedOptions; try { @@ -114,7 +155,10 @@ public InvocationSettings parseSettings(String[] args) throws IOException, Setti boolean measureConfig = parsedOptions.has(measureConfigTimeOption); List benchmarkedBuildOperations = parsedOptions.valuesOf(benchmarkBuildOperation); - List targetNames = parsedOptions.nonOptionArguments().stream().map(Object::toString).collect(Collectors.toList()); + List targetNames = + parsedOptions.nonOptionArguments().stream() + .map(Object::toString) + .collect(Collectors.toList()); List gradleVersions = parsedOptions.valuesOf(gradleVersionOption); File scenarioFile = parsedOptions.valueOf(scenarioFileOption); File studioInstallDir = parsedOptions.valueOf(studioHomeOption); @@ -151,30 +195,31 @@ public InvocationSettings parseSettings(String[] args) throws IOException, Setti sysProperties.put(value.substring(0, sep), value.substring(sep + 1)); } } - CsvGenerator.Format csvFormat = CsvGenerator.Format.parse(parsedOptions.valueOf(csvFormatOption)); + CsvGenerator.Format csvFormat = + CsvGenerator.Format.parse(parsedOptions.valueOf(csvFormatOption)); String benchmarkTitle = parsedOptions.valueOf(benchmarkTitleOption); return new InvocationSettings.InvocationSettingsBuilder() - .setProjectDir(projectDir) - .setProfiler(profiler) - .setBenchmark(benchmark) - .setOutputDir(outputDir) - .setInvoker(invoker) - .setDryRun(dryRun) - .setScenarioFile(scenarioFile) - .setVersions(gradleVersions) - .setTargets(targetNames) - .setSysProperties(sysProperties) - .setGradleUserHome(gradleUserHome) - .setStudioInstallDir(studioInstallDir) - .setWarmupCount(warmups) - .setIterations(iterations) - .setMeasureGarbageCollection(measureGarbageCollection) - .setMeasureConfigTime(measureConfig) - .setMeasuredBuildOperations(benchmarkedBuildOperations) - .setCsvFormat(csvFormat) - .setBenchmarkTitle(benchmarkTitle) - .build(); + .setProjectDir(projectDir) + .setProfiler(profiler) + .setBenchmark(benchmark) + .setOutputDir(outputDir) + .setInvoker(invoker) + .setDryRun(dryRun) + .setScenarioFile(scenarioFile) + .setVersions(gradleVersions) + .setTargets(targetNames) + .setSysProperties(sysProperties) + .setGradleUserHome(gradleUserHome) + .setStudioInstallDir(studioInstallDir) + .setWarmupCount(warmups) + .setIterations(iterations) + .setMeasureGarbageCollection(measureGarbageCollection) + .setMeasureConfigTime(measureConfig) + .setMeasuredBuildOperations(benchmarkedBuildOperations) + .setCsvFormat(csvFormat) + .setBenchmarkTitle(benchmarkTitle) + .build(); } private File findOutputDir() { @@ -202,6 +247,8 @@ private void showHelp(OptionParser parser) throws IOException { } private void showVersion() { - System.out.printf("Gradle Profiler version %s%n", CommandLineParser.class.getPackage().getImplementationVersion()); + System.out.printf( + "Gradle Profiler version %s%n", + CommandLineParser.class.getPackage().getImplementationVersion()); } } diff --git a/src/main/java/org/gradle/profiler/CompositeBuildMutator.java b/src/main/java/org/gradle/profiler/CompositeBuildMutator.java index a4e34a73..3fa78d01 100644 --- a/src/main/java/org/gradle/profiler/CompositeBuildMutator.java +++ b/src/main/java/org/gradle/profiler/CompositeBuildMutator.java @@ -4,56 +4,56 @@ import java.util.stream.Collectors; public class CompositeBuildMutator implements BuildMutator { - private final List mutators; - - public CompositeBuildMutator(List mutators) { - this.mutators = mutators; - } - - @Override - public void beforeScenario(ScenarioContext context) { - for (BuildMutator mutator : mutators) { - mutator.beforeScenario(context); - } - } - - @Override - public void beforeCleanup(BuildContext context) { - for (BuildMutator mutator : mutators) { - mutator.beforeCleanup(context); - } - } - - @Override - public void afterCleanup(BuildContext context, Throwable error) { - for (BuildMutator mutator : mutators) { - mutator.afterCleanup(context, error); - } - } - - @Override - public void beforeBuild(BuildContext context) { - for (BuildMutator mutator : mutators) { - mutator.beforeBuild(context); - } - } - - @Override - public void afterBuild(BuildContext context, Throwable error) { - for (BuildMutator mutator : mutators) { - mutator.afterBuild(context, error); - } - } - - @Override - public void afterScenario(ScenarioContext context) { - for (BuildMutator mutator : mutators) { - mutator.afterScenario(context); - } - } - - @Override - public String toString() { - return mutators.stream().map(Object::toString).collect(Collectors.joining(", ")); - } + private final List mutators; + + public CompositeBuildMutator(List mutators) { + this.mutators = mutators; + } + + @Override + public void beforeScenario(ScenarioContext context) { + for (BuildMutator mutator : mutators) { + mutator.beforeScenario(context); + } + } + + @Override + public void beforeCleanup(BuildContext context) { + for (BuildMutator mutator : mutators) { + mutator.beforeCleanup(context); + } + } + + @Override + public void afterCleanup(BuildContext context, Throwable error) { + for (BuildMutator mutator : mutators) { + mutator.afterCleanup(context, error); + } + } + + @Override + public void beforeBuild(BuildContext context) { + for (BuildMutator mutator : mutators) { + mutator.beforeBuild(context); + } + } + + @Override + public void afterBuild(BuildContext context, Throwable error) { + for (BuildMutator mutator : mutators) { + mutator.afterBuild(context, error); + } + } + + @Override + public void afterScenario(ScenarioContext context) { + for (BuildMutator mutator : mutators) { + mutator.afterScenario(context); + } + } + + @Override + public String toString() { + return mutators.stream().map(Object::toString).collect(Collectors.joining(", ")); + } } diff --git a/src/main/java/org/gradle/profiler/CompositeProfiler.java b/src/main/java/org/gradle/profiler/CompositeProfiler.java index 1167a47e..d3e2bfc3 100644 --- a/src/main/java/org/gradle/profiler/CompositeProfiler.java +++ b/src/main/java/org/gradle/profiler/CompositeProfiler.java @@ -34,10 +34,12 @@ public void summarizeResultFile(File resultFile, Consumer consumer) { @Override public ProfilerController newController(final String pid, final ScenarioSettings settings) { - List controllers = delegates.stream() - .map((Profiler prof) -> prof.newController(pid, - settingsFor(prof, settings))) - .collect(Collectors.toList()); + List controllers = + delegates.stream() + .map( + (Profiler prof) -> + prof.newController(pid, settingsFor(prof, settings))) + .collect(Collectors.toList()); return new ProfilerController() { @Override public void startSession() throws IOException, InterruptedException { @@ -69,38 +71,49 @@ public void stopSession() throws IOException, InterruptedException { }; } - private ScenarioSettings settingsFor(final Profiler prof, final ScenarioSettings scenarioSettings) { + private ScenarioSettings settingsFor( + final Profiler prof, final ScenarioSettings scenarioSettings) { InvocationSettings settings = scenarioSettings.getInvocationSettings(); - InvocationSettings newSettings = new InvocationSettings.InvocationSettingsBuilder() - .setProjectDir(settings.getProjectDir()) - .setProfiler(prof) - .setBenchmark(settings.isBenchmark()) - .setOutputDir(settings.getOutputDir()) - .setInvoker(settings.getInvoker()) - .setDryRun(settings.isDryRun()) - .setScenarioFile(settings.getScenarioFile()) - .setVersions(settings.getVersions()) - .setTargets(settings.getTargets()) - .setSysProperties(settings.getSystemProperties()) - .setGradleUserHome(settings.getGradleUserHome()) - .setWarmupCount(settings.getWarmUpCount()) - .setIterations(settings.getBuildCount()) - .setMeasureGarbageCollection(settings.isMeasureGarbageCollection()) - .setMeasureConfigTime(settings.isMeasureConfigTime()) - .setMeasuredBuildOperations(settings.getMeasuredBuildOperations()) - .setCsvFormat(settings.getCsvFormat()) - .build(); + InvocationSettings newSettings = + new InvocationSettings.InvocationSettingsBuilder() + .setProjectDir(settings.getProjectDir()) + .setProfiler(prof) + .setBenchmark(settings.isBenchmark()) + .setOutputDir(settings.getOutputDir()) + .setInvoker(settings.getInvoker()) + .setDryRun(settings.isDryRun()) + .setScenarioFile(settings.getScenarioFile()) + .setVersions(settings.getVersions()) + .setTargets(settings.getTargets()) + .setSysProperties(settings.getSystemProperties()) + .setGradleUserHome(settings.getGradleUserHome()) + .setWarmupCount(settings.getWarmUpCount()) + .setIterations(settings.getBuildCount()) + .setMeasureGarbageCollection(settings.isMeasureGarbageCollection()) + .setMeasureConfigTime(settings.isMeasureConfigTime()) + .setMeasuredBuildOperations(settings.getMeasuredBuildOperations()) + .setCsvFormat(settings.getCsvFormat()) + .build(); return new ScenarioSettings(newSettings, scenarioSettings.getScenario()); } @Override public JvmArgsCalculator newJvmArgsCalculator(final ScenarioSettings settings) { - return jvmArgs -> delegates.forEach(prof -> prof.newJvmArgsCalculator(settingsFor(prof, settings)).calculateJvmArgs(jvmArgs)); + return jvmArgs -> + delegates.forEach( + prof -> + prof.newJvmArgsCalculator(settingsFor(prof, settings)) + .calculateJvmArgs(jvmArgs)); } @Override public JvmArgsCalculator newInstrumentedBuildsJvmArgsCalculator(ScenarioSettings settings) { - return jvmArgs -> delegates.forEach(prof -> prof.newInstrumentedBuildsJvmArgsCalculator(settingsFor(prof, settings)).calculateJvmArgs(jvmArgs)); + return jvmArgs -> + delegates.forEach( + prof -> + prof.newInstrumentedBuildsJvmArgsCalculator( + settingsFor(prof, settings)) + .calculateJvmArgs(jvmArgs)); } @Override @@ -108,17 +121,25 @@ public GradleArgsCalculator newGradleArgsCalculator(ScenarioSettings settings) { return new GradleArgsCalculator() { @Override public void calculateGradleArgs(List gradleArgs) { - delegates.forEach(prof -> prof.newGradleArgsCalculator(settingsFor(prof, settings)).calculateGradleArgs(gradleArgs)); + delegates.forEach( + prof -> + prof.newGradleArgsCalculator(settingsFor(prof, settings)) + .calculateGradleArgs(gradleArgs)); } }; } @Override - public GradleArgsCalculator newInstrumentedBuildsGradleArgsCalculator(ScenarioSettings settings) { + public GradleArgsCalculator newInstrumentedBuildsGradleArgsCalculator( + ScenarioSettings settings) { return new GradleArgsCalculator() { @Override public void calculateGradleArgs(List gradleArgs) { - delegates.forEach(prof -> prof.newInstrumentedBuildsGradleArgsCalculator(settingsFor(prof, settings)).calculateGradleArgs(gradleArgs)); + delegates.forEach( + prof -> + prof.newInstrumentedBuildsGradleArgsCalculator( + settingsFor(prof, settings)) + .calculateGradleArgs(gradleArgs)); } }; } diff --git a/src/main/java/org/gradle/profiler/CompositeProfilerFactory.java b/src/main/java/org/gradle/profiler/CompositeProfilerFactory.java index 8c4d6c13..4ef3b544 100644 --- a/src/main/java/org/gradle/profiler/CompositeProfilerFactory.java +++ b/src/main/java/org/gradle/profiler/CompositeProfilerFactory.java @@ -20,7 +20,10 @@ public String toString() { @Override public Profiler createFromOptions(OptionSet parsedOptions) { - return new CompositeProfiler(delegates.stream().map(profiler -> profiler.createFromOptions(parsedOptions)).collect(Collectors.toList())); + return new CompositeProfiler( + delegates.stream() + .map(profiler -> profiler.createFromOptions(parsedOptions)) + .collect(Collectors.toList())); } @Override diff --git a/src/main/java/org/gradle/profiler/ConfigUtil.java b/src/main/java/org/gradle/profiler/ConfigUtil.java index 79648910..624391a4 100644 --- a/src/main/java/org/gradle/profiler/ConfigUtil.java +++ b/src/main/java/org/gradle/profiler/ConfigUtil.java @@ -11,66 +11,68 @@ public class ConfigUtil { - public static Map map(Config config, String key, Map defaultValues) { - if (config.hasPath(key)) { - Map props = new LinkedHashMap<>(); - for (Map.Entry entry : config.getObject(key).entrySet()) { - props.put(entry.getKey(), entry.getValue().unwrapped().toString()); - } - return props; - } else { - return defaultValues; - } - } + public static Map map( + Config config, String key, Map defaultValues) { + if (config.hasPath(key)) { + Map props = new LinkedHashMap<>(); + for (Map.Entry entry : config.getObject(key).entrySet()) { + props.put(entry.getKey(), entry.getValue().unwrapped().toString()); + } + return props; + } else { + return defaultValues; + } + } - public static Integer optionalInteger(Config config, String key) { - if (config.hasPath(key)) { - return Integer.valueOf(config.getString(key)); - } else { - return null; - } - } + public static Integer optionalInteger(Config config, String key) { + if (config.hasPath(key)) { + return Integer.valueOf(config.getString(key)); + } else { + return null; + } + } - public static > T enumValue(Config config, String key, Class type, T defaultValue) { - if (config.hasPath(key)) { - return config.getEnum(type, key); - } else { - return defaultValue; - } - } + public static > T enumValue( + Config config, String key, Class type, T defaultValue) { + if (config.hasPath(key)) { + return config.getEnum(type, key); + } else { + return defaultValue; + } + } - public static String string(Config config, String key) { - if (config.hasPath(key)) { - return config.getString(key); - } else { + public static String string(Config config, String key) { + if (config.hasPath(key)) { + return config.getString(key); + } else { throw new IllegalArgumentException("Key '" + key + "' is missing."); - } - } + } + } - public static String string(Config config, String key, String defaultValue) { - if (config.hasPath(key)) { - return config.getString(key); - } else { - return defaultValue; - } - } + public static String string(Config config, String key, String defaultValue) { + if (config.hasPath(key)) { + return config.getString(key); + } else { + return defaultValue; + } + } - public static List strings(Config config, String key) { - return strings(config, key, Collections.emptyList()); - } + public static List strings(Config config, String key) { + return strings(config, key, Collections.emptyList()); + } - public static List strings(Config config, String key, List defaults) { - if (config.hasPath(key)) { - Object value = config.getAnyRef(key); - if (value instanceof List) { - List list = (List) value; - return list.stream().map(Object::toString).collect(Collectors.toList()); - } else if (value.toString().length() > 0) { - return Collections.singletonList(value.toString()); - } - } - return defaults; - } + public static List strings(Config config, String key, List defaults) { + if (config.hasPath(key)) { + Object value = config.getAnyRef(key); + if (value instanceof List) { + List list = (List) value; + return list.stream().map(Object::toString).collect(Collectors.toList()); + } else if (value.toString().length() > 0) { + return Collections.singletonList(value.toString()); + } + } + return defaults; + } public static boolean bool(Config config, String key, boolean defaultValue) { if (config.hasPath(key)) { diff --git a/src/main/java/org/gradle/profiler/DefaultGradleBuildConfigurationReader.java b/src/main/java/org/gradle/profiler/DefaultGradleBuildConfigurationReader.java index d4af6fcc..ad66283f 100644 --- a/src/main/java/org/gradle/profiler/DefaultGradleBuildConfigurationReader.java +++ b/src/main/java/org/gradle/profiler/DefaultGradleBuildConfigurationReader.java @@ -30,7 +30,8 @@ public class DefaultGradleBuildConfigurationReader implements GradleBuildConfigu private final Map versions = new HashMap<>(); private GradleBuildConfiguration defaultVersion; - public DefaultGradleBuildConfigurationReader(File projectDir, File gradleUserHome, DaemonControl daemonControl) throws IOException { + public DefaultGradleBuildConfigurationReader( + File projectDir, File gradleUserHome, DaemonControl daemonControl) throws IOException { this.projectDir = projectDir; this.gradleUserHome = gradleUserHome; this.daemonControl = daemonControl; @@ -44,14 +45,15 @@ public DefaultGradleBuildConfigurationReader(File projectDir, File gradleUserHom private void generateInitScript() throws IOException { try (PrintWriter writer = new PrintWriter(new FileWriter(initScript))) { writer.println( - "rootProject {\n" + - " afterEvaluate {\n" + - " def detailsFile = new File(new URI('" + buildDetails.toURI() + "'))\n" + - " detailsFile.text = \"${gradle.gradleHomeDir}\\n\"\n" + - " detailsFile << plugins.hasPlugin('com.gradle.build-scan') << '\\n'\n" + - " }\n" + - "}\n" - ); + "rootProject {\n" + + " afterEvaluate {\n" + + " def detailsFile = new File(new URI('" + + buildDetails.toURI() + + "'))\n" + + " detailsFile.text = \"${gradle.gradleHomeDir}\\n\"\n" + + " detailsFile << plugins.hasPlugin('com.gradle.build-scan') << '\\n'\n" + + " }\n" + + "}\n"); } } @@ -77,9 +79,14 @@ private GradleBuildConfiguration doResolveVersion(String versionString) { return probe(connector().useGradleVersion(versionString)); } } catch (IOException e) { - throw new RuntimeException("Could not locate Gradle distribution for requested version '" + versionString + "'.", e); + throw new RuntimeException( + "Could not locate Gradle distribution for requested version '" + + versionString + + "'.", + e); } - throw new IllegalArgumentException("Unrecognized Gradle version '" + versionString + "' specified."); + throw new IllegalArgumentException( + "Unrecognized Gradle version '" + versionString + "' specified."); } @Override @@ -92,7 +99,8 @@ public GradleBuildConfiguration readConfiguration() { } private GradleConnector connector() { - return GradleConnector.newConnector().useGradleUserHomeDir(gradleUserHome.getAbsoluteFile()); + return GradleConnector.newConnector() + .useGradleUserHomeDir(gradleUserHome.getAbsoluteFile()); } private List readBuildDetails() { @@ -107,18 +115,22 @@ private GradleBuildConfiguration probe(GradleConnector connector) { GradleBuildConfiguration version; try (ProjectConnection connection = connector.forProjectDirectory(projectDir).connect()) { BuildEnvironment buildEnvironment = connection.getModel(BuildEnvironment.class); - new ToolingApiGradleClient(connection).runTasks(ImmutableList.of("help"), ImmutableList.of("-I", initScript.getAbsolutePath()), ImmutableList.of()); + new ToolingApiGradleClient(connection) + .runTasks( + ImmutableList.of("help"), + ImmutableList.of("-I", initScript.getAbsolutePath()), + ImmutableList.of()); List buildDetails = readBuildDetails(); JavaEnvironment javaEnvironment = buildEnvironment.getJava(); List allJvmArgs = new ArrayList<>(javaEnvironment.getJvmArguments()); allJvmArgs.addAll(readSystemPropertiesFromGradleProperties()); - version = new GradleBuildConfiguration( - GradleVersion.version(buildEnvironment.getGradle().getGradleVersion()), - new File(buildDetails.get(0)), - javaEnvironment.getJavaHome(), - allJvmArgs, - Boolean.valueOf(buildDetails.get(1)) - ); + version = + new GradleBuildConfiguration( + GradleVersion.version(buildEnvironment.getGradle().getGradleVersion()), + new File(buildDetails.get(0)), + javaEnvironment.getJavaHome(), + allJvmArgs, + Boolean.valueOf(buildDetails.get(1))); } daemonControl.stop(version); return version; @@ -132,7 +144,9 @@ private List readSystemPropertiesFromGradleProperties() { if (jvmArgs == null) { return Collections.emptyList(); } - return ArgumentsSplitter.split(jvmArgs).stream().filter(arg -> arg.startsWith("-D")).collect(Collectors.toList()); + return ArgumentsSplitter.split(jvmArgs).stream() + .filter(arg -> arg.startsWith("-D")) + .collect(Collectors.toList()); } private String getJvmArgsProperty(File scope) { diff --git a/src/main/java/org/gradle/profiler/DefaultScenarioContext.java b/src/main/java/org/gradle/profiler/DefaultScenarioContext.java index 7c0e810c..bca15cce 100644 --- a/src/main/java/org/gradle/profiler/DefaultScenarioContext.java +++ b/src/main/java/org/gradle/profiler/DefaultScenarioContext.java @@ -18,7 +18,8 @@ public DefaultScenarioContext(UUID invocationId, String scenarioName) { @Override public String getUniqueScenarioId() { - return String.format("_%s_%s", invocationId.toString().replaceAll("-", "_"), mangleName(scenarioName)); + return String.format( + "_%s_%s", invocationId.toString().replaceAll("-", "_"), mangleName(scenarioName)); } @Override @@ -27,11 +28,12 @@ public BuildContext withBuild(Phase phase, int count) { } /** - * This is to ensure that the scenario ID is a valid Java identifier part, and it is also (reasonably) unique. + * This is to ensure that the scenario ID is a valid Java identifier part, and it is also + * (reasonably) unique. */ private static String mangleName(String scenarioName) { StringBuilder name = new StringBuilder(); - for (char ch :scenarioName.toCharArray()){ + for (char ch : scenarioName.toCharArray()) { name.append(Character.isJavaIdentifierPart(ch) ? ch : '_'); } name.append('_'); diff --git a/src/main/java/org/gradle/profiler/GeneratedInitScript.java b/src/main/java/org/gradle/profiler/GeneratedInitScript.java index 1cb8d874..790e30be 100644 --- a/src/main/java/org/gradle/profiler/GeneratedInitScript.java +++ b/src/main/java/org/gradle/profiler/GeneratedInitScript.java @@ -27,7 +27,9 @@ public abstract class GeneratedInitScript implements GradleArgsCalculator { public GeneratedInitScript() { try { - initScript = File.createTempFile("gradleProfiler" + getClass().getSimpleName(), ".gradle").getCanonicalFile(); + initScript = + File.createTempFile("gradleProfiler" + getClass().getSimpleName(), ".gradle") + .getCanonicalFile(); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/src/main/java/org/gradle/profiler/GradleBuildConfiguration.java b/src/main/java/org/gradle/profiler/GradleBuildConfiguration.java index 1f8255ad..8f26e54c 100644 --- a/src/main/java/org/gradle/profiler/GradleBuildConfiguration.java +++ b/src/main/java/org/gradle/profiler/GradleBuildConfiguration.java @@ -14,7 +14,12 @@ public class GradleBuildConfiguration { private final List jvmArguments; private final boolean usesScanPlugin; - public GradleBuildConfiguration(GradleVersion gradleVersion, File gradleHome, File javaHome, List jvmArguments, boolean usesScanPlugin) { + public GradleBuildConfiguration( + GradleVersion gradleVersion, + File gradleHome, + File javaHome, + List jvmArguments, + boolean usesScanPlugin) { this.gradleVersion = gradleVersion; this.gradleHome = gradleHome; this.javaHome = javaHome; @@ -59,9 +64,7 @@ public void runGradle(String... arguments) { } public void addGradleCommand(List commandLine) { - String gradleScriptName = OperatingSystem.isWindows() - ? "gradle.bat" - : "gradle"; + String gradleScriptName = OperatingSystem.isWindows() ? "gradle.bat" : "gradle"; commandLine.add(new File(gradleHome, "bin/" + gradleScriptName).getAbsolutePath()); } } diff --git a/src/main/java/org/gradle/profiler/GradleBuildConfigurationReader.java b/src/main/java/org/gradle/profiler/GradleBuildConfigurationReader.java index 8292612b..a8ad1a12 100644 --- a/src/main/java/org/gradle/profiler/GradleBuildConfigurationReader.java +++ b/src/main/java/org/gradle/profiler/GradleBuildConfigurationReader.java @@ -1,6 +1,7 @@ package org.gradle.profiler; public interface GradleBuildConfigurationReader { - GradleBuildConfiguration readConfiguration(); - GradleBuildConfiguration readConfiguration(String gradleVersion); + GradleBuildConfiguration readConfiguration(); + + GradleBuildConfiguration readConfiguration(String gradleVersion); } diff --git a/src/main/java/org/gradle/profiler/GradleBuildInvocationResult.java b/src/main/java/org/gradle/profiler/GradleBuildInvocationResult.java index 83ccce29..8ee6cd17 100644 --- a/src/main/java/org/gradle/profiler/GradleBuildInvocationResult.java +++ b/src/main/java/org/gradle/profiler/GradleBuildInvocationResult.java @@ -4,6 +4,7 @@ import org.gradle.profiler.result.Sample; import javax.annotation.Nullable; + import java.time.Duration; import java.util.Map; @@ -15,31 +16,34 @@ public class GradleBuildInvocationResult extends BuildInvocationResult { private final Map cumulativeBuildOperationTimes; private final String daemonPid; - public static final Sample GARBAGE_COLLECTION_TIME = new Sample() { - @Override - public String getName() { - return "garbage collection time"; - } + public static final Sample GARBAGE_COLLECTION_TIME = + new Sample() { + @Override + public String getName() { + return "garbage collection time"; + } - @Override - public Duration extractFrom(GradleBuildInvocationResult result) { - return result.garbageCollectionTime; - } - }; + @Override + public Duration extractFrom(GradleBuildInvocationResult result) { + return result.garbageCollectionTime; + } + }; - public static final Sample TIME_TO_TASK_EXECUTION = new Sample() { - @Override - public String getName() { - return "task start"; - } + public static final Sample TIME_TO_TASK_EXECUTION = + new Sample() { + @Override + public String getName() { + return "task start"; + } - @Override - public Duration extractFrom(GradleBuildInvocationResult result) { - return result.timeToTaskExecution; - } - }; + @Override + public Duration extractFrom(GradleBuildInvocationResult result) { + return result.timeToTaskExecution; + } + }; - public static Sample sampleBuildOperation(String buildOperationDetailsClass) { + public static Sample sampleBuildOperation( + String buildOperationDetailsClass) { return new Sample() { @Override public String getName() { @@ -48,19 +52,19 @@ public String getName() { @Override public Duration extractFrom(GradleBuildInvocationResult result) { - return result.cumulativeBuildOperationTimes.getOrDefault(buildOperationDetailsClass, Duration.ZERO); + return result.cumulativeBuildOperationTimes.getOrDefault( + buildOperationDetailsClass, Duration.ZERO); } }; } public GradleBuildInvocationResult( - BuildContext buildContext, - Duration executionTime, - @Nullable Duration garbageCollectionTime, - @Nullable Duration timeToTaskExecution, - Map cumulativeBuildOperationTimes, - String daemonPid - ) { + BuildContext buildContext, + Duration executionTime, + @Nullable Duration garbageCollectionTime, + @Nullable Duration timeToTaskExecution, + Map cumulativeBuildOperationTimes, + String daemonPid) { super(buildContext, executionTime); this.garbageCollectionTime = garbageCollectionTime; this.timeToTaskExecution = timeToTaskExecution; diff --git a/src/main/java/org/gradle/profiler/GradleBuildInvoker.java b/src/main/java/org/gradle/profiler/GradleBuildInvoker.java index 8ea62223..ddad1160 100644 --- a/src/main/java/org/gradle/profiler/GradleBuildInvoker.java +++ b/src/main/java/org/gradle/profiler/GradleBuildInvoker.java @@ -1,15 +1,21 @@ package org.gradle.profiler; public class GradleBuildInvoker extends BuildInvoker { - public static final GradleBuildInvoker ToolingApi = new GradleBuildInvoker(GradleClientSpec.ToolingApi, GradleDaemonReuse.WarmDaemonOnly); - public static final GradleBuildInvoker Cli = new GradleBuildInvoker(GradleClientSpec.GradleCli, GradleDaemonReuse.WarmDaemonOnly); - public static final GradleBuildInvoker CliNoDaemon = new GradleBuildInvoker(GradleClientSpec.GradleCliNoDaemon, GradleDaemonReuse.ColdDaemonOnly) { - @Override - public String toString() { - return "`gradle` command with --no-daemon"; - } - }; - static final GradleBuildInvoker AndroidStudio = new GradleBuildInvoker(GradleClientSpec.AndroidStudio, GradleDaemonReuse.WarmDaemonOnly); + public static final GradleBuildInvoker ToolingApi = + new GradleBuildInvoker(GradleClientSpec.ToolingApi, GradleDaemonReuse.WarmDaemonOnly); + public static final GradleBuildInvoker Cli = + new GradleBuildInvoker(GradleClientSpec.GradleCli, GradleDaemonReuse.WarmDaemonOnly); + public static final GradleBuildInvoker CliNoDaemon = + new GradleBuildInvoker( + GradleClientSpec.GradleCliNoDaemon, GradleDaemonReuse.ColdDaemonOnly) { + @Override + public String toString() { + return "`gradle` command with --no-daemon"; + } + }; + static final GradleBuildInvoker AndroidStudio = + new GradleBuildInvoker( + GradleClientSpec.AndroidStudio, GradleDaemonReuse.WarmDaemonOnly); private final GradleClientSpec client; private final GradleDaemonReuse daemonReuse; diff --git a/src/main/java/org/gradle/profiler/GradleClient.java b/src/main/java/org/gradle/profiler/GradleClient.java index 90ef98de..fb5baede 100644 --- a/src/main/java/org/gradle/profiler/GradleClient.java +++ b/src/main/java/org/gradle/profiler/GradleClient.java @@ -2,5 +2,4 @@ import java.io.Closeable; -public interface GradleClient extends Closeable { -} +public interface GradleClient extends Closeable {} diff --git a/src/main/java/org/gradle/profiler/GradleClientSpec.java b/src/main/java/org/gradle/profiler/GradleClientSpec.java index acf0efd3..1c7497a2 100644 --- a/src/main/java/org/gradle/profiler/GradleClientSpec.java +++ b/src/main/java/org/gradle/profiler/GradleClientSpec.java @@ -4,70 +4,98 @@ import org.gradle.tooling.GradleConnector; import org.gradle.tooling.ProjectConnection; -/** - * Specifies a client to be used to invoke Gradle builds. - */ +/** Specifies a client to be used to invoke Gradle builds. */ public abstract class GradleClientSpec { - public static final GradleClientSpec ToolingApi = new GradleClientSpec() { - @Override - public String toString() { - return "Tooling API"; - } + public static final GradleClientSpec ToolingApi = + new GradleClientSpec() { + @Override + public String toString() { + return "Tooling API"; + } - @Override - public GradleClient create(GradleBuildConfiguration buildConfiguration, InvocationSettings invocationSettings) { - GradleConnector connector = GradleConnector.newConnector() - .useInstallation(buildConfiguration.getGradleHome()) - .useGradleUserHomeDir(invocationSettings.getGradleUserHome().getAbsoluteFile()); - ProjectConnection projectConnection = connector.forProjectDirectory(invocationSettings.getProjectDir()).connect(); - return new ToolingApiGradleClient(projectConnection); - } - }; + @Override + public GradleClient create( + GradleBuildConfiguration buildConfiguration, + InvocationSettings invocationSettings) { + GradleConnector connector = + GradleConnector.newConnector() + .useInstallation(buildConfiguration.getGradleHome()) + .useGradleUserHomeDir( + invocationSettings + .getGradleUserHome() + .getAbsoluteFile()); + ProjectConnection projectConnection = + connector + .forProjectDirectory(invocationSettings.getProjectDir()) + .connect(); + return new ToolingApiGradleClient(projectConnection); + } + }; - public static final GradleClientSpec GradleCli = new GradleClientSpec() { - @Override - public String toString() { - return "`gradle` command"; - } + public static final GradleClientSpec GradleCli = + new GradleClientSpec() { + @Override + public String toString() { + return "`gradle` command"; + } - @Override - public GradleClient create(GradleBuildConfiguration buildConfiguration, InvocationSettings invocationSettings) { - return new CliGradleClient(buildConfiguration, buildConfiguration.getJavaHome(), invocationSettings.getProjectDir(), true, invocationSettings.getBuildLog()); - } - }; + @Override + public GradleClient create( + GradleBuildConfiguration buildConfiguration, + InvocationSettings invocationSettings) { + return new CliGradleClient( + buildConfiguration, + buildConfiguration.getJavaHome(), + invocationSettings.getProjectDir(), + true, + invocationSettings.getBuildLog()); + } + }; - public static final GradleClientSpec GradleCliNoDaemon = new GradleClientSpec() { - @Override - public String toString() { - return "`gradle` command with --no-daemon"; - } + public static final GradleClientSpec GradleCliNoDaemon = + new GradleClientSpec() { + @Override + public String toString() { + return "`gradle` command with --no-daemon"; + } - @Override - public boolean isUsesDaemon() { - return false; - } + @Override + public boolean isUsesDaemon() { + return false; + } - @Override - public GradleClient create(GradleBuildConfiguration buildConfiguration, InvocationSettings invocationSettings) { - return new CliGradleClient(buildConfiguration, buildConfiguration.getJavaHome(), invocationSettings.getProjectDir(), false, invocationSettings.getBuildLog()); - } - }; + @Override + public GradleClient create( + GradleBuildConfiguration buildConfiguration, + InvocationSettings invocationSettings) { + return new CliGradleClient( + buildConfiguration, + buildConfiguration.getJavaHome(), + invocationSettings.getProjectDir(), + false, + invocationSettings.getBuildLog()); + } + }; - public static final GradleClientSpec AndroidStudio = new GradleClientSpec() { - @Override - public String toString() { - return "Android Studio"; - } + public static final GradleClientSpec AndroidStudio = + new GradleClientSpec() { + @Override + public String toString() { + return "Android Studio"; + } - @Override - public GradleClient create(GradleBuildConfiguration buildConfiguration, InvocationSettings invocationSettings) { - return new StudioGradleClient(buildConfiguration, invocationSettings); - } - }; + @Override + public GradleClient create( + GradleBuildConfiguration buildConfiguration, + InvocationSettings invocationSettings) { + return new StudioGradleClient(buildConfiguration, invocationSettings); + } + }; public boolean isUsesDaemon() { return true; } - public abstract GradleClient create(GradleBuildConfiguration buildConfiguration, InvocationSettings invocationSettings); + public abstract GradleClient create( + GradleBuildConfiguration buildConfiguration, InvocationSettings invocationSettings); } diff --git a/src/main/java/org/gradle/profiler/GradleDaemonReuse.java b/src/main/java/org/gradle/profiler/GradleDaemonReuse.java index 34f14345..75e46bf8 100644 --- a/src/main/java/org/gradle/profiler/GradleDaemonReuse.java +++ b/src/main/java/org/gradle/profiler/GradleDaemonReuse.java @@ -1,5 +1,6 @@ package org.gradle.profiler; public enum GradleDaemonReuse { - WarmDaemonOnly, ColdDaemonOnly + WarmDaemonOnly, + ColdDaemonOnly } diff --git a/src/main/java/org/gradle/profiler/GradleInvoker.java b/src/main/java/org/gradle/profiler/GradleInvoker.java index 6aafa4ee..73f339ba 100644 --- a/src/main/java/org/gradle/profiler/GradleInvoker.java +++ b/src/main/java/org/gradle/profiler/GradleInvoker.java @@ -6,13 +6,20 @@ import java.util.List; import java.util.function.Consumer; -/** - * Performs operations on a build using Gradle. - */ +/** Performs operations on a build using Gradle. */ public interface GradleInvoker { void runTasks(List tasks, List gradleArgs, List jvmArgs); - void loadToolingModel(List tasks, List gradleArgs, List jvmArgs, Class toolingModel); + void loadToolingModel( + List tasks, + List gradleArgs, + List jvmArgs, + Class toolingModel); - T runToolingAction(List tasks, List gradleArgs, List jvmArgs, BuildAction action, Consumer> configureAction); + T runToolingAction( + List tasks, + List gradleArgs, + List jvmArgs, + BuildAction action, + Consumer> configureAction); } diff --git a/src/main/java/org/gradle/profiler/GradleInvokerBuildAction.java b/src/main/java/org/gradle/profiler/GradleInvokerBuildAction.java index 6897057a..873332f8 100644 --- a/src/main/java/org/gradle/profiler/GradleInvokerBuildAction.java +++ b/src/main/java/org/gradle/profiler/GradleInvokerBuildAction.java @@ -11,5 +11,6 @@ public Duration run(GradleClient gradleClient, List gradleArgs, List gradleArgs, List jvmArgs); + protected abstract void run( + GradleInvoker buildInvoker, List gradleArgs, List jvmArgs); } diff --git a/src/main/java/org/gradle/profiler/GradleScenarioDefinition.java b/src/main/java/org/gradle/profiler/GradleScenarioDefinition.java index 1ef3bb1c..088c2013 100644 --- a/src/main/java/org/gradle/profiler/GradleScenarioDefinition.java +++ b/src/main/java/org/gradle/profiler/GradleScenarioDefinition.java @@ -22,21 +22,20 @@ public class GradleScenarioDefinition extends ScenarioDefinition { private final List measuredBuildOperations; public GradleScenarioDefinition( - String name, - String title, - GradleBuildInvoker invoker, - GradleBuildConfiguration buildConfiguration, - BuildAction buildAction, - BuildAction cleanupAction, - List gradleArgs, - Map systemProperties, - List buildMutators, - int warmUpCount, - int buildCount, - File outputDir, - List jvmArgs, - List measuredBuildOperations - ) { + String name, + String title, + GradleBuildInvoker invoker, + GradleBuildConfiguration buildConfiguration, + BuildAction buildAction, + BuildAction cleanupAction, + List gradleArgs, + Map systemProperties, + List buildMutators, + int warmUpCount, + int buildCount, + File outputDir, + List jvmArgs, + List measuredBuildOperations) { super(name, title, buildMutators, warmUpCount, buildCount, outputDir); this.invoker = invoker; this.buildAction = buildAction; @@ -108,24 +107,35 @@ public List getMeasuredBuildOperations() { @Override public void visitProblems(InvocationSettings settings, Consumer reporter) { if (getWarmUpCount() < 1) { - reporter.accept("You can not skip warm-ups when profiling or benchmarking a Gradle build. Use --no-daemon or --cold-daemon if you want to profile or benchmark JVM startup"); + reporter.accept( + "You can not skip warm-ups when profiling or benchmarking a Gradle build. Use --no-daemon or --cold-daemon if you want to profile or benchmark JVM startup"); } if (settings.isMeasureGarbageCollection() && isBuildServiceUnsupported()) { - reporter.accept("Measuring garbage collection is only supported for Gradle 6.1-milestone-3 and later"); + reporter.accept( + "Measuring garbage collection is only supported for Gradle 6.1-milestone-3 and later"); } if (settings.isMeasureConfigTime() && isBuildServiceUnsupported()) { - reporter.accept("Measuring build configuration is only supported for Gradle 6.1-milestone-3 and later"); + reporter.accept( + "Measuring build configuration is only supported for Gradle 6.1-milestone-3 and later"); } settings.getProfiler().validate(new ScenarioSettings(settings, this), reporter); } private boolean isBuildServiceUnsupported() { - return buildConfiguration.getGradleVersion().compareTo(GradleVersion.version("6.1-milestone-3")) < 0; + return buildConfiguration + .getGradleVersion() + .compareTo(GradleVersion.version("6.1-milestone-3")) + < 0; } @Override protected void printDetail(PrintStream out) { - out.println(" " + getBuildConfiguration().getGradleVersion() + " (" + getBuildConfiguration().getGradleHome() + ")"); + out.println( + " " + + getBuildConfiguration().getGradleVersion() + + " (" + + getBuildConfiguration().getGradleHome() + + ")"); out.println(" Run using: " + getInvoker()); out.println(" Run: " + getAction().getDisplayName()); out.println(" Cleanup: " + getCleanupAction().getDisplayName()); @@ -140,10 +150,12 @@ protected void printDetail(PrintStream out) { out.println(" Jvm args: " + getJvmArgs()); } if (!measuredBuildOperations.isEmpty()) { - out.println(" Measured build operations: " + measuredBuildOperations.stream() - .map(BuildOperationUtil::getSimpleBuildOperationName) - .sorted() - .collect(Collectors.joining(", "))); + out.println( + " Measured build operations: " + + measuredBuildOperations.stream() + .map(BuildOperationUtil::getSimpleBuildOperationName) + .sorted() + .collect(Collectors.joining(", "))); } } } diff --git a/src/main/java/org/gradle/profiler/GradleScenarioInvoker.java b/src/main/java/org/gradle/profiler/GradleScenarioInvoker.java index 1c3cab93..181f1d0d 100644 --- a/src/main/java/org/gradle/profiler/GradleScenarioInvoker.java +++ b/src/main/java/org/gradle/profiler/GradleScenarioInvoker.java @@ -18,18 +18,22 @@ import static org.gradle.profiler.Phase.MEASURE; import static org.gradle.profiler.Phase.WARM_UP; -public class GradleScenarioInvoker extends ScenarioInvoker { +public class GradleScenarioInvoker + extends ScenarioInvoker { private final DaemonControl daemonControl; private final PidInstrumentation pidInstrumentation; - public GradleScenarioInvoker(DaemonControl daemonControl, PidInstrumentation pidInstrumentation) { + public GradleScenarioInvoker( + DaemonControl daemonControl, PidInstrumentation pidInstrumentation) { this.daemonControl = daemonControl; this.pidInstrumentation = pidInstrumentation; } @Override - public List> samplesFor(InvocationSettings settings, GradleScenarioDefinition scenario) { - ImmutableList.Builder> builder = ImmutableList.builder(); + public List> samplesFor( + InvocationSettings settings, GradleScenarioDefinition scenario) { + ImmutableList.Builder> builder = + ImmutableList.builder(); builder.add(BuildInvocationResult.EXECUTION_TIME); if (settings.isMeasureGarbageCollection()) { builder.add(GradleBuildInvocationResult.GARBAGE_COLLECTION_TIME); @@ -38,30 +42,39 @@ public List> samplesFor(InvocationSe builder.add(GradleBuildInvocationResult.TIME_TO_TASK_EXECUTION); } scenario.getMeasuredBuildOperations().stream() - .map(GradleBuildInvocationResult::sampleBuildOperation) - .forEach(builder::add); + .map(GradleBuildInvocationResult::sampleBuildOperation) + .forEach(builder::add); return builder.build(); } @Override - public void doRun(GradleScenarioDefinition scenario, InvocationSettings settings, Consumer resultConsumer) throws IOException, InterruptedException { + public void doRun( + GradleScenarioDefinition scenario, + InvocationSettings settings, + Consumer resultConsumer) + throws IOException, InterruptedException { if (settings.isProfile() && scenario.getWarmUpCount() == 0) { - throw new IllegalStateException("Using the --profile option requires at least one warm-up"); + throw new IllegalStateException( + "Using the --profile option requires at least one warm-up"); } ScenarioSettings scenarioSettings = new ScenarioSettings(settings, scenario); FileUtils.forceMkdir(scenario.getOutputDir()); - JvmArgsCalculator allBuildsJvmArgsCalculator = settings.getProfiler().newJvmArgsCalculator(scenarioSettings); + JvmArgsCalculator allBuildsJvmArgsCalculator = + settings.getProfiler().newJvmArgsCalculator(scenarioSettings); GradleArgsCalculator allBuildsGradleArgsCalculator = pidInstrumentation; - allBuildsGradleArgsCalculator = allBuildsGradleArgsCalculator.plus(settings.getProfiler().newGradleArgsCalculator(scenarioSettings)); - - BuildOperationInstrumentation buildOperationInstrumentation = new BuildOperationInstrumentation( - settings.isMeasureGarbageCollection(), - settings.isMeasureConfigTime(), - scenario.getMeasuredBuildOperations() - ); + allBuildsGradleArgsCalculator = + allBuildsGradleArgsCalculator.plus( + settings.getProfiler().newGradleArgsCalculator(scenarioSettings)); + + BuildOperationInstrumentation buildOperationInstrumentation = + new BuildOperationInstrumentation( + settings.isMeasureGarbageCollection(), + settings.isMeasureConfigTime(), + scenario.getMeasuredBuildOperations()); if (buildOperationInstrumentation.requiresInitScript()) { - allBuildsGradleArgsCalculator = allBuildsGradleArgsCalculator.plus(buildOperationInstrumentation); + allBuildsGradleArgsCalculator = + allBuildsGradleArgsCalculator.plus(buildOperationInstrumentation); } GradleBuildConfiguration buildConfiguration = scenario.getBuildConfiguration(); @@ -70,7 +83,8 @@ public void doRun(GradleScenarioDefinition scenario, InvocationSettings settings BuildMutator mutator = new CompositeBuildMutator(scenario.getBuildMutators()); ScenarioContext scenarioContext = ScenarioContext.from(settings, scenario); - GradleClient gradleClient = scenario.getInvoker().getClient().create(buildConfiguration, settings); + GradleClient gradleClient = + scenario.getInvoker().getClient().create(buildConfiguration, settings); try { buildConfiguration.printVersionInfo(); @@ -97,10 +111,18 @@ public void doRun(GradleScenarioDefinition scenario, InvocationSettings settings allBuildsGradleArgsCalculator.calculateGradleArgs(allBuildsGradleArgs); logGradleArgs(allBuildsGradleArgs); - BuildUnderTestInvoker uninstrumented = new BuildUnderTestInvoker(allBuildsJvmArgs, allBuildsGradleArgs, gradleClient, pidInstrumentation, buildOperationInstrumentation); + BuildUnderTestInvoker uninstrumented = + new BuildUnderTestInvoker( + allBuildsJvmArgs, + allBuildsGradleArgs, + gradleClient, + pidInstrumentation, + buildOperationInstrumentation); - BuildStepAction cleanupStep = cleanupStep(uninstrumented, mutator, scenario, buildConfiguration); - BuildStepAction warmupBuildStep = buildStep(uninstrumented, scenario); + BuildStepAction cleanupStep = + cleanupStep(uninstrumented, mutator, scenario, buildConfiguration); + BuildStepAction warmupBuildStep = + buildStep(uninstrumented, scenario); mutator.beforeScenario(scenarioContext); @@ -118,13 +140,18 @@ public void doRun(GradleScenarioDefinition scenario, InvocationSettings settings } } - ProfilerController control = settings.getProfiler().newController(pid, scenarioSettings); + ProfilerController control = + settings.getProfiler().newController(pid, scenarioSettings); List instrumentedBuildJvmArgs = new ArrayList<>(allBuildsJvmArgs); - settings.getProfiler().newInstrumentedBuildsJvmArgsCalculator(scenarioSettings).calculateJvmArgs(instrumentedBuildJvmArgs); + settings.getProfiler() + .newInstrumentedBuildsJvmArgsCalculator(scenarioSettings) + .calculateJvmArgs(instrumentedBuildJvmArgs); List instrumentedBuildGradleArgs = new ArrayList<>(allBuildsGradleArgs); - settings.getProfiler().newInstrumentedBuildsGradleArgsCalculator(scenarioSettings).calculateGradleArgs(instrumentedBuildGradleArgs); + settings.getProfiler() + .newInstrumentedBuildsGradleArgsCalculator(scenarioSettings) + .calculateGradleArgs(instrumentedBuildGradleArgs); Logging.detailed().println(); Logging.detailed().println("* Using args for instrumented builds:"); @@ -135,9 +162,14 @@ public void doRun(GradleScenarioDefinition scenario, InvocationSettings settings logGradleArgs(instrumentedBuildGradleArgs); } - BuildUnderTestInvoker instrumentedBuildInvoker = uninstrumented.withJvmArgs(instrumentedBuildJvmArgs).withGradleArgs(instrumentedBuildGradleArgs); - BuildStepAction measuredBuildStep = buildStep(instrumentedBuildInvoker, scenario); - RecordingBuildStepAction recordingBuildStep = new RecordingBuildStepAction(measuredBuildStep, cleanupStep, scenario, control); + BuildUnderTestInvoker instrumentedBuildInvoker = + uninstrumented + .withJvmArgs(instrumentedBuildJvmArgs) + .withGradleArgs(instrumentedBuildGradleArgs); + BuildStepAction measuredBuildStep = + buildStep(instrumentedBuildInvoker, scenario); + RecordingBuildStepAction recordingBuildStep = + new RecordingBuildStepAction(measuredBuildStep, cleanupStep, scenario, control); control.startSession(); for (int i = 1; i <= scenario.getBuildCount(); i++) { @@ -156,14 +188,21 @@ public void doRun(GradleScenarioDefinition scenario, InvocationSettings settings } } - private BuildStepAction buildStep(BuildUnderTestInvoker invoker, GradleScenarioDefinition scenario) { + private BuildStepAction buildStep( + BuildUnderTestInvoker invoker, GradleScenarioDefinition scenario) { return invoker.create(scenario.getAction()); } - private BuildStepAction cleanupStep(BuildUnderTestInvoker invoker, BuildMutator buildMutator, GradleScenarioDefinition scenario, GradleBuildConfiguration buildConfiguration) { - BuildStepAction cleanupStep = invoker.create(scenario.getCleanupAction()); + private BuildStepAction cleanupStep( + BuildUnderTestInvoker invoker, + BuildMutator buildMutator, + GradleScenarioDefinition scenario, + GradleBuildConfiguration buildConfiguration) { + BuildStepAction cleanupStep = + invoker.create(scenario.getCleanupAction()); if (scenario.getInvoker().isShouldCleanUpDaemon()) { - cleanupStep = new StopDaemonAfterAction<>(cleanupStep, daemonControl, buildConfiguration); + cleanupStep = + new StopDaemonAfterAction<>(cleanupStep, daemonControl, buildConfiguration); } return new RunCleanupStepAction<>(cleanupStep, buildMutator); } diff --git a/src/main/java/org/gradle/profiler/InstrumentingProfiler.java b/src/main/java/org/gradle/profiler/InstrumentingProfiler.java index efeaed91..474b8a29 100644 --- a/src/main/java/org/gradle/profiler/InstrumentingProfiler.java +++ b/src/main/java/org/gradle/profiler/InstrumentingProfiler.java @@ -7,25 +7,30 @@ * A profiler that can: * *
    - *
  • Instrument a JVM using JVM args
  • - *
  • Start recording on JVM start, using JVM args
  • - *
  • Capture snapshot on JVM exit, using JVM args
  • - *
  • Use some communication mechanism to start recording in an instrumented JVM that is currently running.
  • - *
  • Use some communication mechanism to pause recording in an instrumented JVM that is currently running.
  • - *
  • Use some communication mechanism to capture a snapshot from an instrumented JVM that is currently running.
  • + *
  • Instrument a JVM using JVM args + *
  • Start recording on JVM start, using JVM args + *
  • Capture snapshot on JVM exit, using JVM args + *
  • Use some communication mechanism to start recording in an instrumented JVM that is + * currently running. + *
  • Use some communication mechanism to pause recording in an instrumented JVM that is + * currently running. + *
  • Use some communication mechanism to capture a snapshot from an instrumented JVM that is + * currently running. *
* - *

The profiler may support starting recording multiple times for a given JVM. The implementation should indicate this by overriding {@link #canRestartRecording(ScenarioSettings)}.

+ *

The profiler may support starting recording multiple times for a given JVM. The implementation + * should indicate this by overriding {@link #canRestartRecording(ScenarioSettings)}. */ public abstract class InstrumentingProfiler extends Profiler { /** * Calculates the JVM args for all builds, including warm-ups. * - *

When the daemon will not be reused, this does nothing as there is no need to instrument the warm-up - * builds in this case. + *

When the daemon will not be reused, this does nothing as there is no need to instrument + * the warm-up builds in this case. * - *

When the daemon will be reused for all builds, then instrument the daemon but do not start recording or capture snapshots yet. - * Recording and capture will be enabled later when the measured builds run. + *

When the daemon will be reused for all builds, then instrument the daemon but do not start + * recording or capture snapshots yet. Recording and capture will be enabled later when the + * measured builds run. */ @Override public JvmArgsCalculator newJvmArgsCalculator(ScenarioSettings settings) { @@ -38,11 +43,14 @@ public JvmArgsCalculator newJvmArgsCalculator(ScenarioSettings settings) { /** * Calculates the JVM args for measured builds. * - *

When the daemon will be reused for all builds, this does nothing as the daemon is already instrumented (above).

+ *

When the daemon will be reused for all builds, this does nothing as the daemon is already + * instrumented (above). * - *

When using a cold daemon, start the JVM with recording enabled but do not capture snapshots yet.

+ *

When using a cold daemon, start the JVM with recording enabled but do not capture + * snapshots yet. * - *

When using no daemon, start the JVM with recording enabled and capture a snapshot when the JVM exits.

+ *

When using no daemon, start the JVM with recording enabled and capture a snapshot when the + * JVM exits. */ @Override public JvmArgsCalculator newInstrumentedBuildsJvmArgsCalculator(ScenarioSettings settings) { @@ -56,14 +64,14 @@ public JvmArgsCalculator newInstrumentedBuildsJvmArgsCalculator(ScenarioSettings /** * Creates a controller for this profiler. * - *

When the daemon will be reused for all builds, create a controller that starts and stops recording when - * requested, and that captures a snapshot at the end of the session.

+ *

When the daemon will be reused for all builds, create a controller that starts and stops + * recording when requested, and that captures a snapshot at the end of the session. * - *

When using a cold daemon, create a controller that stops recording and captures a snapshot when requested, - * but does not start recording as this is already enabled when the JVM starts.

+ *

When using a cold daemon, create a controller that stops recording and captures a snapshot + * when requested, but does not start recording as this is already enabled when the JVM starts. * - *

When using no daemon, return a controller that finishes the session only, as recording and snapshot capture - * are already enabled when the JVM starts.

+ *

When using no daemon, return a controller that finishes the session only, as recording and + * snapshot capture are already enabled when the JVM starts. */ @Override public ProfilerController newController(String pid, ScenarioSettings settings) { @@ -83,42 +91,47 @@ public void validate(ScenarioSettings settings, Consumer reporter) { validateMultipleDaemons(settings, reporter); } - protected void validateMultipleIterationsWithCleanupAction(ScenarioSettings settings, Consumer reporter) { + protected void validateMultipleIterationsWithCleanupAction( + ScenarioSettings settings, Consumer reporter) { GradleScenarioDefinition scenario = settings.getScenario(); - if (scenario.getBuildCount() > 1 && !canRestartRecording(settings) && scenario.getCleanupAction().isDoesSomething()) { - reporter.accept("Profiler " + toString() + " does not support profiling multiple iterations with cleanup steps in between."); + if (scenario.getBuildCount() > 1 + && !canRestartRecording(settings) + && scenario.getCleanupAction().isDoesSomething()) { + reporter.accept( + "Profiler " + + toString() + + " does not support profiling multiple iterations with cleanup steps in between."); } } protected void validateMultipleDaemons(ScenarioSettings settings, Consumer reporter) { GradleScenarioDefinition scenario = settings.getScenario(); if (scenario.getBuildCount() > 1 && !scenario.getInvoker().isReuseDaemon()) { - reporter.accept("Profiler " + toString() + " does not support profiling multiple daemons."); + reporter.accept( + "Profiler " + toString() + " does not support profiling multiple daemons."); } } - /** - * Can this profiler implementation restart recording, for the same JVM? - */ + /** Can this profiler implementation restart recording, for the same JVM? */ protected boolean canRestartRecording(ScenarioSettings settings) { return false; } - /** - * Creates JVM args to instrument that JVM with the given capabilities enabled. - */ - protected abstract JvmArgsCalculator jvmArgsWithInstrumentation(ScenarioSettings settings, boolean startRecordingOnProcessStart, boolean captureSnapshotOnProcessExit); + /** Creates JVM args to instrument that JVM with the given capabilities enabled. */ + protected abstract JvmArgsCalculator jvmArgsWithInstrumentation( + ScenarioSettings settings, + boolean startRecordingOnProcessStart, + boolean captureSnapshotOnProcessExit); - protected abstract SnapshotCapturingProfilerController doNewController(ScenarioSettings settings); + protected abstract SnapshotCapturingProfilerController doNewController( + ScenarioSettings settings); public interface SnapshotCapturingProfilerController { void startRecording(String pid) throws IOException, InterruptedException; void stopRecording(String pid) throws IOException, InterruptedException; - /** - * Capture snapshot, if not already performed on stop. - */ + /** Capture snapshot, if not already performed on stop. */ void captureSnapshot(String pid) throws IOException, InterruptedException; void stopSession() throws IOException, InterruptedException; @@ -134,8 +147,7 @@ private static class DelegatingController implements ProfilerController { } @Override - public void startSession() throws IOException, InterruptedException { - } + public void startSession() throws IOException, InterruptedException {} @Override public void startRecording() throws IOException, InterruptedException { @@ -156,7 +168,8 @@ public void stopSession() throws IOException, InterruptedException { private static class CaptureSnapshotOnSessionEndController extends DelegatingController { private String mostRecentPid; - public CaptureSnapshotOnSessionEndController(String pid, SnapshotCapturingProfilerController controller) { + public CaptureSnapshotOnSessionEndController( + String pid, SnapshotCapturingProfilerController controller) { super(pid, controller); } @@ -174,7 +187,8 @@ public void stopSession() throws IOException, InterruptedException { } private static class RecordingAlreadyStartedController extends DelegatingController { - RecordingAlreadyStartedController(String pid, SnapshotCapturingProfilerController controller) { + RecordingAlreadyStartedController( + String pid, SnapshotCapturingProfilerController controller) { super(pid, controller); } @@ -196,11 +210,9 @@ private static class SessionOnlyController extends DelegatingController { } @Override - public void startRecording() throws IOException, InterruptedException { - } + public void startRecording() throws IOException, InterruptedException {} @Override - public void stopRecording(String pid) throws IOException, InterruptedException { - } + public void stopRecording(String pid) throws IOException, InterruptedException {} } } diff --git a/src/main/java/org/gradle/profiler/InvocationSettings.java b/src/main/java/org/gradle/profiler/InvocationSettings.java index 7767c5c3..71d41f62 100644 --- a/src/main/java/org/gradle/profiler/InvocationSettings.java +++ b/src/main/java/org/gradle/profiler/InvocationSettings.java @@ -1,6 +1,7 @@ package org.gradle.profiler; import javax.annotation.Nullable; + import java.io.File; import java.io.PrintStream; import java.util.List; @@ -30,35 +31,34 @@ public class InvocationSettings { private final Format csvFormat; private final String benchmarkTitle; /** - * The log file which the build should write stdout and stderr to. - * If {@code null}, the stdout and stderr are stored in memory. + * The log file which the build should write stdout and stderr to. If {@code null}, the stdout + * and stderr are stored in memory. */ private final File buildLog; private final UUID invocationId = UUID.randomUUID(); private InvocationSettings( - File projectDir, - Profiler profiler, - boolean benchmark, - File outputDir, - BuildInvoker invoker, - boolean dryRun, - File scenarioFile, - List versions, - List targets, - Map sysProperties, - File gradleUserHome, - File studioInstallDir, - Integer warmupCount, - Integer iterations, - boolean measureGarbageCollection, - boolean measureConfigTime, - List measuredBuildOperations, - Format csvFormat, - String benchmarkTitle, - File buildLog - ) { + File projectDir, + Profiler profiler, + boolean benchmark, + File outputDir, + BuildInvoker invoker, + boolean dryRun, + File scenarioFile, + List versions, + List targets, + Map sysProperties, + File gradleUserHome, + File studioInstallDir, + Integer warmupCount, + Integer iterations, + boolean measureGarbageCollection, + boolean measureConfigTime, + List measuredBuildOperations, + Format csvFormat, + String benchmarkTitle, + File buildLog) { this.benchmark = benchmark; this.projectDir = projectDir; this.profiler = profiler; @@ -174,9 +174,7 @@ public Format getCsvFormat() { return csvFormat; } - /** - * The title of the benchmark. Shown on the HTML report and on the console. - */ + /** The title of the benchmark. Shown on the HTML report and on the console. */ public String getBenchmarkTitle() { return benchmarkTitle; } @@ -302,7 +300,8 @@ public InvocationSettingsBuilder setIterations(Integer iterations) { return this; } - public InvocationSettingsBuilder setMeasureGarbageCollection(boolean measureGarbageCollection) { + public InvocationSettingsBuilder setMeasureGarbageCollection( + boolean measureGarbageCollection) { this.measureGarbageCollection = measureGarbageCollection; return this; } @@ -312,7 +311,8 @@ public InvocationSettingsBuilder setMeasureConfigTime(boolean measureConfigTime) return this; } - public InvocationSettingsBuilder setMeasuredBuildOperations(List measuredBuildOperations) { + public InvocationSettingsBuilder setMeasuredBuildOperations( + List measuredBuildOperations) { this.measuredBuildOperations = measuredBuildOperations; return this; } @@ -322,9 +322,7 @@ public InvocationSettingsBuilder setCsvFormat(Format csvFormat) { return this; } - /** - * The title of the benchmark. Shown on the HTML report and on the console. - */ + /** The title of the benchmark. Shown on the HTML report and on the console. */ public InvocationSettingsBuilder setBenchmarkTitle(@Nullable String benchmarkTitle) { this.benchmarkTitle = benchmarkTitle; return this; @@ -337,27 +335,26 @@ public InvocationSettingsBuilder setBuildLog(File buildLog) { public InvocationSettings build() { return new InvocationSettings( - projectDir, - profiler, - benchmark, - outputDir, - invoker, - dryRun, - scenarioFile, - versions, - targets, - sysProperties, - gradleUserHome, - studioInstallDir, - warmupCount, - iterations, - measureGarbageCollection, - measureConfigTime, - measuredBuildOperations, - csvFormat, - benchmarkTitle, - buildLog - ); + projectDir, + profiler, + benchmark, + outputDir, + invoker, + dryRun, + scenarioFile, + versions, + targets, + sysProperties, + gradleUserHome, + studioInstallDir, + warmupCount, + iterations, + measureGarbageCollection, + measureConfigTime, + measuredBuildOperations, + csvFormat, + benchmarkTitle, + buildLog); } } } diff --git a/src/main/java/org/gradle/profiler/JvmArgsCalculator.java b/src/main/java/org/gradle/profiler/JvmArgsCalculator.java index 8ddc799a..66e96a5a 100644 --- a/src/main/java/org/gradle/profiler/JvmArgsCalculator.java +++ b/src/main/java/org/gradle/profiler/JvmArgsCalculator.java @@ -3,8 +3,7 @@ import java.util.List; public interface JvmArgsCalculator { - JvmArgsCalculator DEFAULT = jvmArgs -> { - }; + JvmArgsCalculator DEFAULT = jvmArgs -> {}; void calculateJvmArgs(List jvmArgs); } diff --git a/src/main/java/org/gradle/profiler/Logging.java b/src/main/java/org/gradle/profiler/Logging.java index d076a128..0ddee9fd 100644 --- a/src/main/java/org/gradle/profiler/Logging.java +++ b/src/main/java/org/gradle/profiler/Logging.java @@ -8,9 +8,7 @@ public class Logging { private static PrintStream detail = System.out; private static OutputStream log; - /** - * Resets logging to its original state before {@link #setupLogging(File)} was called. - */ + /** Resets logging to its original state before {@link #setupLogging(File)} was called. */ public static void resetLogging() throws IOException { if (System.out != originalStdOut) { System.out.flush(); @@ -29,6 +27,7 @@ public static void resetLogging() throws IOException { /** * Routes System.out to log file. + * * @param outputDir */ public static void setupLogging(File outputDir) throws IOException { @@ -41,16 +40,12 @@ public static void setupLogging(File outputDir) throws IOException { System.setErr(output); } - /** - * A stream to write detailed logging messages to. - */ + /** A stream to write detailed logging messages to. */ public static PrintStream detailed() { return detail; } - /** - * Writes an operation header. - */ + /** Writes an operation header. */ public static void startOperation(String name) { System.out.println(); System.out.println("* " + name); diff --git a/src/main/java/org/gradle/profiler/Main.java b/src/main/java/org/gradle/profiler/Main.java index 72b006da..50dd26b9 100644 --- a/src/main/java/org/gradle/profiler/Main.java +++ b/src/main/java/org/gradle/profiler/Main.java @@ -44,7 +44,9 @@ public void run(String[] args) throws Exception { settings.printTo(System.out); DaemonControl daemonControl = new DaemonControl(settings.getGradleUserHome()); - GradleBuildConfigurationReader gradleBuildConfigurationReader = new DefaultGradleBuildConfigurationReader(settings.getProjectDir(), settings.getGradleUserHome(), daemonControl); + GradleBuildConfigurationReader gradleBuildConfigurationReader = + new DefaultGradleBuildConfigurationReader( + settings.getProjectDir(), settings.getGradleUserHome(), daemonControl); ScenarioLoader scenarioLoader = new ScenarioLoader(gradleBuildConfigurationReader); List scenarios = scenarioLoader.loadScenarios(settings); int totalScenarios = scenarios.size(); @@ -53,9 +55,13 @@ public void run(String[] args) throws Exception { File cvsFile = new File(settings.getOutputDir(), "benchmark.csv"); File htmlFile = new File(settings.getOutputDir(), "benchmark.html"); - BenchmarkResultCollector benchmarkResults = new BenchmarkResultCollector(new CsvGenerator(cvsFile, settings.getCsvFormat()), new HtmlGenerator(htmlFile)); + BenchmarkResultCollector benchmarkResults = + new BenchmarkResultCollector( + new CsvGenerator(cvsFile, settings.getCsvFormat()), + new HtmlGenerator(htmlFile)); PidInstrumentation pidInstrumentation = new PidInstrumentation(); - GradleScenarioInvoker gradleScenarioInvoker = new GradleScenarioInvoker(daemonControl, pidInstrumentation); + GradleScenarioInvoker gradleScenarioInvoker = + new GradleScenarioInvoker(daemonControl, pidInstrumentation); BazelScenarioInvoker bazelScenarioInvoker = new BazelScenarioInvoker(); BuckScenarioInvoker buckScenarioInvoker = new BuckScenarioInvoker(); MavenScenarioInvoker mavenScenarioInvoker = new MavenScenarioInvoker(); @@ -65,15 +71,42 @@ public void run(String[] args) throws Exception { for (ScenarioDefinition scenario : scenarios) { scenarioCount++; - Logging.startOperation("Running scenario " + scenario.getDisplayName() + " (scenario " + scenarioCount + "/" + totalScenarios + ")"); + Logging.startOperation( + "Running scenario " + + scenario.getDisplayName() + + " (scenario " + + scenarioCount + + "/" + + totalScenarios + + ")"); if (scenario instanceof BazelScenarioDefinition) { - invoke(bazelScenarioInvoker, (BazelScenarioDefinition) scenario, settings, benchmarkResults, failures); + invoke( + bazelScenarioInvoker, + (BazelScenarioDefinition) scenario, + settings, + benchmarkResults, + failures); } else if (scenario instanceof BuckScenarioDefinition) { - invoke(buckScenarioInvoker, (BuckScenarioDefinition) scenario, settings, benchmarkResults, failures); + invoke( + buckScenarioInvoker, + (BuckScenarioDefinition) scenario, + settings, + benchmarkResults, + failures); } else if (scenario instanceof MavenScenarioDefinition) { - invoke(mavenScenarioInvoker, (MavenScenarioDefinition) scenario, settings, benchmarkResults, failures); + invoke( + mavenScenarioInvoker, + (MavenScenarioDefinition) scenario, + settings, + benchmarkResults, + failures); } else if (scenario instanceof GradleScenarioDefinition) { - invoke(gradleScenarioInvoker, (GradleScenarioDefinition) scenario, settings, benchmarkResults, failures); + invoke( + gradleScenarioInvoker, + (GradleScenarioDefinition) scenario, + settings, + benchmarkResults, + failures); } else { throw new IllegalArgumentException("Don't know how to run scenario."); } @@ -81,7 +114,8 @@ public void run(String[] args) throws Exception { if (settings.isBenchmark()) { // Write the final results and generate the reports - // This overwrites the existing reports, so may leave them in a corrupted state if this process crashes during the generation. + // This overwrites the existing reports, so may leave them in a corrupted state if + // this process crashes during the generation. benchmarkResults.write(settings); } @@ -105,15 +139,23 @@ public void run(String[] args) throws Exception { } } - private void invoke(ScenarioInvoker invoker, S scenario, InvocationSettings settings, BenchmarkResultCollector benchmarkResults, List failures) throws IOException { + private void invoke( + ScenarioInvoker invoker, + S scenario, + InvocationSettings settings, + BenchmarkResultCollector benchmarkResults, + List failures) + throws IOException { try { invoker.run(scenario, settings, benchmarkResults); } catch (Throwable t) { t.printStackTrace(); failures.add(t); } finally { - // Write the current results and generate the reports, so that if this process crashes the results (which may have taken quite some time to collect) are not lost. - // This overwrites the existing reports, so may leave them in a corrupted state if this process crashes during the generation. + // Write the current results and generate the reports, so that if this process crashes + // the results (which may have taken quite some time to collect) are not lost. + // This overwrites the existing reports, so may leave them in a corrupted state if this + // process crashes during the generation. // This is just intended to be a simple best effort solution if (settings.isBenchmark()) { benchmarkResults.write(settings); @@ -121,7 +163,8 @@ private void inv } } - private void printReportSummary(InvocationSettings settings, BenchmarkResultCollector benchmarkResults) { + private void printReportSummary( + InvocationSettings settings, BenchmarkResultCollector benchmarkResults) { if (settings.isBenchmark()) { benchmarkResults.summarizeResults(line -> System.out.println(" " + line)); } diff --git a/src/main/java/org/gradle/profiler/MavenScenarioDefinition.java b/src/main/java/org/gradle/profiler/MavenScenarioDefinition.java index 48cd9032..0e218d65 100644 --- a/src/main/java/org/gradle/profiler/MavenScenarioDefinition.java +++ b/src/main/java/org/gradle/profiler/MavenScenarioDefinition.java @@ -1,21 +1,29 @@ package org.gradle.profiler; import javax.annotation.Nullable; + import java.io.File; import java.util.List; public class MavenScenarioDefinition extends BuildToolCommandLineScenarioDefinition { public MavenScenarioDefinition( - String scenarioName, - @Nullable String title, - List targets, - List buildMutators, - int warmUpCount, - int buildCount, - File outputDir, - @Nullable File mavenHome - ) { - super(scenarioName, title, targets, buildMutators, warmUpCount, buildCount, outputDir, mavenHome); + String scenarioName, + @Nullable String title, + List targets, + List buildMutators, + int warmUpCount, + int buildCount, + File outputDir, + @Nullable File mavenHome) { + super( + scenarioName, + title, + targets, + buildMutators, + warmUpCount, + buildCount, + outputDir, + mavenHome); } @Override diff --git a/src/main/java/org/gradle/profiler/MavenScenarioInvoker.java b/src/main/java/org/gradle/profiler/MavenScenarioInvoker.java index c20c7d8a..bc76a2c8 100644 --- a/src/main/java/org/gradle/profiler/MavenScenarioInvoker.java +++ b/src/main/java/org/gradle/profiler/MavenScenarioInvoker.java @@ -6,9 +6,13 @@ import java.util.List; import java.util.function.Consumer; -public class MavenScenarioInvoker extends BuildToolCommandLineInvoker { +public class MavenScenarioInvoker + extends BuildToolCommandLineInvoker { @Override - void doRun(MavenScenarioDefinition scenario, InvocationSettings settings, Consumer resultConsumer) { + void doRun( + MavenScenarioDefinition scenario, + InvocationSettings settings, + Consumer resultConsumer) { List commandLine = new ArrayList<>(); commandLine.add(scenario.getExecutablePath()); commandLine.addAll(scenario.getTargets()); diff --git a/src/main/java/org/gradle/profiler/OperatingSystem.java b/src/main/java/org/gradle/profiler/OperatingSystem.java index 97807cb7..e4e9b0a8 100644 --- a/src/main/java/org/gradle/profiler/OperatingSystem.java +++ b/src/main/java/org/gradle/profiler/OperatingSystem.java @@ -16,7 +16,8 @@ public static boolean isMacOS() { } public static boolean isLinuxX86() { - return OS_NAME.startsWith("linux") && (OS_ARCH.equals("amd64") || OS_ARCH.equals("x86_64") || OS_ARCH.equals("x86")); + return OS_NAME.startsWith("linux") + && (OS_ARCH.equals("amd64") || OS_ARCH.equals("x86_64") || OS_ARCH.equals("x86")); } public static String getId() { diff --git a/src/main/java/org/gradle/profiler/Phase.java b/src/main/java/org/gradle/profiler/Phase.java index 4d475885..ecb751ae 100644 --- a/src/main/java/org/gradle/profiler/Phase.java +++ b/src/main/java/org/gradle/profiler/Phase.java @@ -1,15 +1,16 @@ package org.gradle.profiler; public enum Phase { - WARM_UP("warm-up"), MEASURE("measured"); + WARM_UP("warm-up"), + MEASURE("measured"); - private final String name; + private final String name; - Phase(String name) { - this.name = name; - } + Phase(String name) { + this.name = name; + } - public String displayBuildNumber(int number) { - return name + " build #" + number; - } + public String displayBuildNumber(int number) { + return name + " build #" + number; + } } diff --git a/src/main/java/org/gradle/profiler/Profiler.java b/src/main/java/org/gradle/profiler/Profiler.java index 796dfe8f..8456e174 100644 --- a/src/main/java/org/gradle/profiler/Profiler.java +++ b/src/main/java/org/gradle/profiler/Profiler.java @@ -20,51 +20,53 @@ public class Profiler { - public static final Profiler NONE = new Profiler() { - @Override - public String toString() { - return "none"; - } - }; + public static final Profiler NONE = + new Profiler() { + @Override + public String toString() { + return "none"; + } + }; - public void validate(ScenarioSettings settings, Consumer reporter) { - } + public void validate(ScenarioSettings settings, Consumer reporter) {} public ProfilerController newController(String pid, ScenarioSettings settings) { return ProfilerController.EMPTY; } /** - * Returns a calculator that provides JVM args that should be applied to all builds, including warm-up builds. + * Returns a calculator that provides JVM args that should be applied to all builds, including + * warm-up builds. */ public JvmArgsCalculator newJvmArgsCalculator(ScenarioSettings settings) { return JvmArgsCalculator.DEFAULT; } /** - * Returns a calculator that provides JVM args that should be applied to instrumented builds, but not warm-up builds. + * Returns a calculator that provides JVM args that should be applied to instrumented builds, + * but not warm-up builds. */ public JvmArgsCalculator newInstrumentedBuildsJvmArgsCalculator(ScenarioSettings settings) { return JvmArgsCalculator.DEFAULT; } /** - * Returns a calculator that provides Gradle args that should be applied to all builds, including warm-up builds. + * Returns a calculator that provides Gradle args that should be applied to all builds, + * including warm-up builds. */ public GradleArgsCalculator newGradleArgsCalculator(ScenarioSettings settings) { return GradleArgsCalculator.DEFAULT; } /** - * Returns a calculator that provides Gradle args that should be applied to instrumented builds, but not warm-up builds. + * Returns a calculator that provides Gradle args that should be applied to instrumented builds, + * but not warm-up builds. */ - public GradleArgsCalculator newInstrumentedBuildsGradleArgsCalculator(ScenarioSettings settings) { + public GradleArgsCalculator newInstrumentedBuildsGradleArgsCalculator( + ScenarioSettings settings) { return GradleArgsCalculator.DEFAULT; } - /** - * Describe the given file, if recognized and should be reported to the user. - */ - public void summarizeResultFile(File resultFile, Consumer consumer) { - } + /** Describe the given file, if recognized and should be reported to the user. */ + public void summarizeResultFile(File resultFile, Consumer consumer) {} } diff --git a/src/main/java/org/gradle/profiler/ProfilerController.java b/src/main/java/org/gradle/profiler/ProfilerController.java index 021e0dff..8f556ef6 100644 --- a/src/main/java/org/gradle/profiler/ProfilerController.java +++ b/src/main/java/org/gradle/profiler/ProfilerController.java @@ -18,33 +18,25 @@ import java.io.IOException; public interface ProfilerController { - ProfilerController EMPTY = new ProfilerController() { - @Override - public void startSession() { + ProfilerController EMPTY = + new ProfilerController() { + @Override + public void startSession() {} - } + @Override + public void startRecording() {} - @Override - public void startRecording() { + @Override + public void stopRecording(String pid) {} - } - - @Override - public void stopRecording(String pid) { - - } - - @Override - public void stopSession() { - - } - }; + @Override + public void stopSession() {} + }; /** - * Connects the profiler to the daemon and does any other one-time setup work. - * The profiler should not start collecting data yet. If the profiler cannot - * connect without starting data collection, it should defer startup to {@link #startRecording()} - * instead. + * Connects the profiler to the daemon and does any other one-time setup work. The profiler + * should not start collecting data yet. If the profiler cannot connect without starting data + * collection, it should defer startup to {@link #startRecording()} instead. */ void startSession() throws IOException, InterruptedException; @@ -55,17 +47,16 @@ public void stopSession() { void startRecording() throws IOException, InterruptedException; /** - * Tells the profiler to stop collecting data for now, e.g. so it doesn't - * profile cleanup tasks. If the data collection can only be stopped by - * stopping the session, the profiler should implement this as a no-op - * and throw an exception when {@link #startRecording()} is called another - * time. + * Tells the profiler to stop collecting data for now, e.g. so it doesn't profile cleanup tasks. + * If the data collection can only be stopped by stopping the session, the profiler should + * implement this as a no-op and throw an exception when {@link #startRecording()} is called + * another time. */ void stopRecording(String pid) throws IOException, InterruptedException; /** - * Ends the profiling session, writing the collected results to disk - * and disconnecting the profiler from the daemon. + * Ends the profiling session, writing the collected results to disk and disconnecting the + * profiler from the daemon. */ void stopSession() throws IOException, InterruptedException; } diff --git a/src/main/java/org/gradle/profiler/ProfilerFactory.java b/src/main/java/org/gradle/profiler/ProfilerFactory.java index 1141092f..1dcab556 100644 --- a/src/main/java/org/gradle/profiler/ProfilerFactory.java +++ b/src/main/java/org/gradle/profiler/ProfilerFactory.java @@ -17,30 +17,36 @@ import java.util.stream.Collectors; /** - * Represents some profiling strategy. Produces {@link Profiler} instances from a set of command-line options. + * Represents some profiling strategy. Produces {@link Profiler} instances from a set of + * command-line options. */ public abstract class ProfilerFactory { - public static final ProfilerFactory NONE = new ProfilerFactory() { - @Override - public Profiler createFromOptions(OptionSet parsedOptions) { - return Profiler.NONE; - } - }; + public static final ProfilerFactory NONE = + new ProfilerFactory() { + @Override + public Profiler createFromOptions(OptionSet parsedOptions) { + return Profiler.NONE; + } + }; - private final static Map AVAILABLE_PROFILERS = Collections.unmodifiableMap( - new LinkedHashMap() {{ - put("buildscan", new BuildScanProfilerFactory()); - put("jfr", new JfrProfilerFactory()); - put("jprofiler", new JProfilerProfilerFactory()); - put("yourkit", new YourKitSamplingProfilerFactory()); - put("yourkit-tracing", new YourKitTracingProfilerFactory()); - put("yourkit-heap", new YourKitHeapAllocationProfilerFactory()); - put("async-profiler", AsyncProfilerFactory.INSTANCE); - put("async-profiler-heap", AsyncProfilerHeapAllocationProfilerFactory.INSTANCE); - put("heap-dump", new HeapDumpProfilerFactory()); - put("chrome-trace", new ChromeTraceProfilerFactory()); - }} - ); + private static final Map AVAILABLE_PROFILERS = + Collections.unmodifiableMap( + new LinkedHashMap() { + { + put("buildscan", new BuildScanProfilerFactory()); + put("jfr", new JfrProfilerFactory()); + put("jprofiler", new JProfilerProfilerFactory()); + put("yourkit", new YourKitSamplingProfilerFactory()); + put("yourkit-tracing", new YourKitTracingProfilerFactory()); + put("yourkit-heap", new YourKitHeapAllocationProfilerFactory()); + put("async-profiler", AsyncProfilerFactory.INSTANCE); + put( + "async-profiler-heap", + AsyncProfilerHeapAllocationProfilerFactory.INSTANCE); + put("heap-dump", new HeapDumpProfilerFactory()); + put("chrome-trace", new ChromeTraceProfilerFactory()); + } + }); public static Set getAvailableProfilers() { return AVAILABLE_PROFILERS.keySet(); @@ -65,14 +71,12 @@ public static ProfilerFactory of(List profilersList) { String first = profilersList.get(0); return of(first); } - return new CompositeProfilerFactory(profilersList.stream().map(ProfilerFactory::of).collect(Collectors.toList())); + return new CompositeProfilerFactory( + profilersList.stream().map(ProfilerFactory::of).collect(Collectors.toList())); } - /** - * Creates a profiler from the given options. - */ + /** Creates a profiler from the given options. */ public abstract Profiler createFromOptions(OptionSet parsedOptions); - public void addOptions(OptionParser parser) { - } + public void addOptions(OptionParser parser) {} } diff --git a/src/main/java/org/gradle/profiler/RecordingBuildStepAction.java b/src/main/java/org/gradle/profiler/RecordingBuildStepAction.java index e09891bb..951a9988 100644 --- a/src/main/java/org/gradle/profiler/RecordingBuildStepAction.java +++ b/src/main/java/org/gradle/profiler/RecordingBuildStepAction.java @@ -2,18 +2,17 @@ import java.io.IOException; -import static org.gradle.profiler.BuildStep.BUILD; - public class RecordingBuildStepAction implements BuildStepAction { private final BuildStepAction action; private final BuildStepAction cleanupAction; private final GradleScenarioDefinition scenario; private final ProfilerController controller; - public RecordingBuildStepAction(BuildStepAction action, - BuildStepAction cleanupAction, - GradleScenarioDefinition scenario, - ProfilerController controller) { + public RecordingBuildStepAction( + BuildStepAction action, + BuildStepAction cleanupAction, + GradleScenarioDefinition scenario, + ProfilerController controller) { this.action = action; this.cleanupAction = cleanupAction; this.scenario = scenario; @@ -37,7 +36,8 @@ public GradleBuildInvocationResult run(BuildContext buildContext, BuildStep buil GradleBuildInvocationResult result = action.run(buildContext, buildStep); - if ((buildContext.getIteration() == scenario.getBuildCount() || cleanupAction.isDoesSomething())) { + if ((buildContext.getIteration() == scenario.getBuildCount() + || cleanupAction.isDoesSomething())) { try { controller.stopRecording(result.getDaemonPid()); } catch (IOException | InterruptedException e) { diff --git a/src/main/java/org/gradle/profiler/ScenarioContext.java b/src/main/java/org/gradle/profiler/ScenarioContext.java index a387eaae..b545fdb6 100644 --- a/src/main/java/org/gradle/profiler/ScenarioContext.java +++ b/src/main/java/org/gradle/profiler/ScenarioContext.java @@ -1,8 +1,10 @@ package org.gradle.profiler; public interface ScenarioContext { - static ScenarioContext from(InvocationSettings invocationSettings, ScenarioDefinition scenarioDefinition) { - return new DefaultScenarioContext(invocationSettings.getInvocationId(), scenarioDefinition.getName()); + static ScenarioContext from( + InvocationSettings invocationSettings, ScenarioDefinition scenarioDefinition) { + return new DefaultScenarioContext( + invocationSettings.getInvocationId(), scenarioDefinition.getName()); } String getUniqueScenarioId(); diff --git a/src/main/java/org/gradle/profiler/ScenarioDefinition.java b/src/main/java/org/gradle/profiler/ScenarioDefinition.java index 4ebb361e..c4826125 100644 --- a/src/main/java/org/gradle/profiler/ScenarioDefinition.java +++ b/src/main/java/org/gradle/profiler/ScenarioDefinition.java @@ -1,6 +1,7 @@ package org.gradle.profiler; import javax.annotation.Nullable; + import java.io.File; import java.io.PrintStream; import java.util.List; @@ -15,13 +16,12 @@ public abstract class ScenarioDefinition { private final File outputDir; public ScenarioDefinition( - String name, - @Nullable String title, - List buildMutators, - int warmUpCount, - int buildCount, - File outputDir - ) { + String name, + @Nullable String title, + List buildMutators, + int warmUpCount, + int buildCount, + File outputDir) { this.name = name; this.title = title; this.buildMutators = buildMutators; @@ -35,35 +35,32 @@ public void validate() { try { buildMutator.validate(getInvoker()); } catch (Exception ex) { - throw new IllegalStateException("Scenario '" + getTitle() + "' is invalid: " + ex.getMessage(), ex); + throw new IllegalStateException( + "Scenario '" + getTitle() + "' is invalid: " + ex.getMessage(), ex); } } } /** - * A specific title defined for the scenario to be used in reports (defaults to {@link #getName()}. + * A specific title defined for the scenario to be used in reports (defaults to {@link + * #getName()}. */ public String getTitle() { return title != null ? title : name; } - /** - * A human consumable and unique display name for this scenario using {@link #getTitle()}. - */ + /** A human consumable and unique display name for this scenario using {@link #getTitle()}. */ public abstract String getDisplayName(); - /** - * A unique name for this scenario, that can be used for file names and other identifiers. - */ + /** A unique name for this scenario, that can be used for file names and other identifiers. */ public abstract String getProfileName(); - /** - * A human consumable description of the build tool that runs this scenario. - */ + /** A human consumable description of the build tool that runs this scenario. */ public abstract String getBuildToolDisplayName(); /** - * A human consumable description of the 'tasks' that are run for this scenario (may not be Gradle tasks). + * A human consumable description of the 'tasks' that are run for this scenario (may not be + * Gradle tasks). */ public abstract String getTasksDisplayName(); @@ -97,9 +94,7 @@ public void printTo(PrintStream out) { out.println(" Builds: " + getBuildCount()); } - public void visitProblems(InvocationSettings settings, Consumer reporter) { - } + public void visitProblems(InvocationSettings settings, Consumer reporter) {} - protected void printDetail(PrintStream out) { - } + protected void printDetail(PrintStream out) {} } diff --git a/src/main/java/org/gradle/profiler/ScenarioInvoker.java b/src/main/java/org/gradle/profiler/ScenarioInvoker.java index 202d95bc..3aec9358 100644 --- a/src/main/java/org/gradle/profiler/ScenarioInvoker.java +++ b/src/main/java/org/gradle/profiler/ScenarioInvoker.java @@ -8,32 +8,33 @@ import java.util.List; import java.util.function.Consumer; -public abstract class ScenarioInvoker { - /** - * Runs a scenario and collects the results. - */ - public final void run(T scenario, InvocationSettings settings, BenchmarkResultCollector collector) throws IOException, InterruptedException { +public abstract class ScenarioInvoker< + T extends ScenarioDefinition, R extends BuildInvocationResult> { + /** Runs a scenario and collects the results. */ + public final void run( + T scenario, InvocationSettings settings, BenchmarkResultCollector collector) + throws IOException, InterruptedException { Consumer resultConsumer = collector.scenario(scenario, samplesFor(settings, scenario)); doRun(scenario, settings, resultConsumer); } - /** - * Runs a scenario and collects the results. - */ - abstract void doRun(T scenario, InvocationSettings settings, Consumer resultConsumer) throws IOException, InterruptedException; + /** Runs a scenario and collects the results. */ + abstract void doRun(T scenario, InvocationSettings settings, Consumer resultConsumer) + throws IOException, InterruptedException; - /** - * Which samples will this invoker generate for the given settings? - */ + /** Which samples will this invoker generate for the given settings? */ public List> samplesFor(InvocationSettings settings, T scenario) { return Collections.singletonList(BuildInvocationResult.EXECUTION_TIME); } - /** - * Runs a single measured build and collects the result. - */ - protected R runMeasured(BuildContext buildContext, BuildMutator buildMutator, BuildStepAction action, Consumer consumer) { - R result = new RunBuildStepAction(action, buildMutator).run(buildContext, BuildStep.BUILD); + /** Runs a single measured build and collects the result. */ + protected R runMeasured( + BuildContext buildContext, + BuildMutator buildMutator, + BuildStepAction action, + Consumer consumer) { + R result = + new RunBuildStepAction(action, buildMutator).run(buildContext, BuildStep.BUILD); consumer.accept(result); return result; } diff --git a/src/main/java/org/gradle/profiler/ScenarioLoader.java b/src/main/java/org/gradle/profiler/ScenarioLoader.java index 6d6d3fa6..0c7cd181 100644 --- a/src/main/java/org/gradle/profiler/ScenarioLoader.java +++ b/src/main/java/org/gradle/profiler/ScenarioLoader.java @@ -54,17 +54,23 @@ class ScenarioLoader { private static final String MEASURED_BUILD_OPERATIONS = "measured-build-ops"; private static final String APPLY_ABI_CHANGE_TO = "apply-abi-change-to"; private static final String APPLY_NON_ABI_CHANGE_TO = "apply-non-abi-change-to"; - private static final String APPLY_ANDROID_RESOURCE_CHANGE_TO = "apply-android-resource-change-to"; - private static final String APPLY_ANDROID_RESOURCE_VALUE_CHANGE_TO = "apply-android-resource-value-change-to"; + private static final String APPLY_ANDROID_RESOURCE_CHANGE_TO = + "apply-android-resource-change-to"; + private static final String APPLY_ANDROID_RESOURCE_VALUE_CHANGE_TO = + "apply-android-resource-value-change-to"; private static final String APPLY_ANDROID_LAYOUT_CHANGE_TO = "apply-android-layout-change-to"; - private static final String APPLY_PROPERTY_RESOURCE_CHANGE_TO = "apply-property-resource-change-to"; - private static final String APPLY_ANDROID_MANIFEST_CHANGE_TO = "apply-android-manifest-change-to"; + private static final String APPLY_PROPERTY_RESOURCE_CHANGE_TO = + "apply-property-resource-change-to"; + private static final String APPLY_ANDROID_MANIFEST_CHANGE_TO = + "apply-android-manifest-change-to"; private static final String APPLY_CPP_SOURCE_CHANGE_TO = "apply-cpp-change-to"; private static final String APPLY_H_SOURCE_CHANGE_TO = "apply-h-change-to"; private static final String CLEAR_BUILD_CACHE_BEFORE = "clear-build-cache-before"; private static final String CLEAR_GRADLE_USER_HOME_BEFORE = "clear-gradle-user-home-before"; - private static final String CLEAR_INSTANT_EXECUTION_STATE_BEFORE = "clear-instant-execution-state-before"; - private static final String CLEAR_CONFIGURATION_CACHE_STATE_BEFORE = "clear-configuration-cache-state-before"; + private static final String CLEAR_INSTANT_EXECUTION_STATE_BEFORE = + "clear-instant-execution-state-before"; + private static final String CLEAR_CONFIGURATION_CACHE_STATE_BEFORE = + "clear-configuration-cache-state-before"; private static final String CLEAR_PROJECT_CACHE_BEFORE = "clear-project-cache-before"; private static final String CLEAR_TRANSFORM_CACHE_BEFORE = "clear-transform-cache-before"; private static final String CLEAR_JARS_CACHE_BEFORE = "clear-jars-cache-before"; @@ -77,51 +83,88 @@ class ScenarioLoader { private static final String ANDROID_STUDIO_SYNC = "android-studio-sync"; private static final String JVM_ARGS = "jvm-args"; - private static final Map BUILD_MUTATOR_CONFIGURATORS = ImmutableMap.builder() - .put(APPLY_ABI_CHANGE_TO, new FileChangeMutatorConfigurator(ApplyAbiChangeToSourceFileMutator.class)) - .put(APPLY_NON_ABI_CHANGE_TO, new FileChangeMutatorConfigurator(ApplyNonAbiChangeToSourceFileMutator.class)) - .put(APPLY_ANDROID_RESOURCE_CHANGE_TO, new FileChangeMutatorConfigurator(ApplyChangeToAndroidResourceFileMutator.class)) - .put(APPLY_ANDROID_RESOURCE_VALUE_CHANGE_TO, new FileChangeMutatorConfigurator(ApplyValueChangeToAndroidResourceFileMutator.class)) - .put(APPLY_ANDROID_LAYOUT_CHANGE_TO, new FileChangeMutatorConfigurator(ApplyChangeToAndroidLayoutFileMutator.class)) - .put(APPLY_ANDROID_MANIFEST_CHANGE_TO, new FileChangeMutatorConfigurator(ApplyChangeToAndroidManifestFileMutator.class)) - .put(APPLY_PROPERTY_RESOURCE_CHANGE_TO, new FileChangeMutatorConfigurator(ApplyChangeToPropertyResourceFileMutator.class)) - .put(APPLY_CPP_SOURCE_CHANGE_TO, new FileChangeMutatorConfigurator(ApplyChangeToNativeSourceFileMutator.class)) - .put(APPLY_H_SOURCE_CHANGE_TO, new FileChangeMutatorConfigurator(ApplyChangeToNativeSourceFileMutator.class)) - .put(CLEAR_BUILD_CACHE_BEFORE, new ClearBuildCacheMutator.Configurator()) - .put(CLEAR_GRADLE_USER_HOME_BEFORE, new ClearGradleUserHomeMutator.Configurator()) - .put(CLEAR_INSTANT_EXECUTION_STATE_BEFORE, new ClearConfigurationCacheStateMutator.Configurator()) - .put(CLEAR_CONFIGURATION_CACHE_STATE_BEFORE, new ClearConfigurationCacheStateMutator.Configurator()) - .put(CLEAR_PROJECT_CACHE_BEFORE, new ClearProjectCacheMutator.Configurator()) - .put(CLEAR_TRANSFORM_CACHE_BEFORE, new ClearArtifactTransformCacheMutator.Configurator()) - .put(CLEAR_JARS_CACHE_BEFORE, new ClearJarsCacheMutator.Configurator()) - .put(SHOW_BUILD_CACHE_SIZE, new ShowBuildCacheSizeMutator.Configurator()) - .put(GIT_CHECKOUT, new GitCheckoutMutator.Configurator()) - .put(GIT_REVERT, new GitRevertMutator.Configurator()) - .build(); - - private static final List ALL_SCENARIO_KEYS = ImmutableList.builder() - .addAll(BUILD_MUTATOR_CONFIGURATORS.keySet()) - .addAll(Arrays.asList( - TITLE, - VERSIONS, - TASKS, - CLEANUP_TASKS, - GRADLE_ARGS, - RUN_USING, - SYSTEM_PROPERTIES, - WARM_UP_COUNT, - ITERATIONS, - MEASURED_BUILD_OPERATIONS, - BAZEL, - BUCK, - MAVEN, - MODEL, - TOOL_HOME, - ANDROID_STUDIO_SYNC, - DAEMON, - JVM_ARGS - )) - .build(); + private static final Map BUILD_MUTATOR_CONFIGURATORS = + ImmutableMap.builder() + .put( + APPLY_ABI_CHANGE_TO, + new FileChangeMutatorConfigurator( + ApplyAbiChangeToSourceFileMutator.class)) + .put( + APPLY_NON_ABI_CHANGE_TO, + new FileChangeMutatorConfigurator( + ApplyNonAbiChangeToSourceFileMutator.class)) + .put( + APPLY_ANDROID_RESOURCE_CHANGE_TO, + new FileChangeMutatorConfigurator( + ApplyChangeToAndroidResourceFileMutator.class)) + .put( + APPLY_ANDROID_RESOURCE_VALUE_CHANGE_TO, + new FileChangeMutatorConfigurator( + ApplyValueChangeToAndroidResourceFileMutator.class)) + .put( + APPLY_ANDROID_LAYOUT_CHANGE_TO, + new FileChangeMutatorConfigurator( + ApplyChangeToAndroidLayoutFileMutator.class)) + .put( + APPLY_ANDROID_MANIFEST_CHANGE_TO, + new FileChangeMutatorConfigurator( + ApplyChangeToAndroidManifestFileMutator.class)) + .put( + APPLY_PROPERTY_RESOURCE_CHANGE_TO, + new FileChangeMutatorConfigurator( + ApplyChangeToPropertyResourceFileMutator.class)) + .put( + APPLY_CPP_SOURCE_CHANGE_TO, + new FileChangeMutatorConfigurator( + ApplyChangeToNativeSourceFileMutator.class)) + .put( + APPLY_H_SOURCE_CHANGE_TO, + new FileChangeMutatorConfigurator( + ApplyChangeToNativeSourceFileMutator.class)) + .put(CLEAR_BUILD_CACHE_BEFORE, new ClearBuildCacheMutator.Configurator()) + .put( + CLEAR_GRADLE_USER_HOME_BEFORE, + new ClearGradleUserHomeMutator.Configurator()) + .put( + CLEAR_INSTANT_EXECUTION_STATE_BEFORE, + new ClearConfigurationCacheStateMutator.Configurator()) + .put( + CLEAR_CONFIGURATION_CACHE_STATE_BEFORE, + new ClearConfigurationCacheStateMutator.Configurator()) + .put(CLEAR_PROJECT_CACHE_BEFORE, new ClearProjectCacheMutator.Configurator()) + .put( + CLEAR_TRANSFORM_CACHE_BEFORE, + new ClearArtifactTransformCacheMutator.Configurator()) + .put(CLEAR_JARS_CACHE_BEFORE, new ClearJarsCacheMutator.Configurator()) + .put(SHOW_BUILD_CACHE_SIZE, new ShowBuildCacheSizeMutator.Configurator()) + .put(GIT_CHECKOUT, new GitCheckoutMutator.Configurator()) + .put(GIT_REVERT, new GitRevertMutator.Configurator()) + .build(); + + private static final List ALL_SCENARIO_KEYS = + ImmutableList.builder() + .addAll(BUILD_MUTATOR_CONFIGURATORS.keySet()) + .addAll( + Arrays.asList( + TITLE, + VERSIONS, + TASKS, + CLEANUP_TASKS, + GRADLE_ARGS, + RUN_USING, + SYSTEM_PROPERTIES, + WARM_UP_COUNT, + ITERATIONS, + MEASURED_BUILD_OPERATIONS, + BAZEL, + BUCK, + MAVEN, + MODEL, + TOOL_HOME, + ANDROID_STUDIO_SYNC, + DAEMON, + JVM_ARGS)) + .build(); private static final List BAZEL_KEYS = Arrays.asList(TARGETS, TOOL_HOME); private static final List BUCK_KEYS = Arrays.asList(TARGETS, TYPE, TOOL_HOME); @@ -137,7 +180,11 @@ public List loadScenarios(InvocationSettings settings) { List scenarios = doLoadScenarios(settings); List problems = new ArrayList<>(); for (ScenarioDefinition scenario : scenarios) { - scenario.visitProblems(settings, message -> problems.add("- Scenario " + scenario.getDisplayName() + ": " + message)); + scenario.visitProblems( + settings, + message -> + problems.add( + "- Scenario " + scenario.getDisplayName() + ": " + message)); } if (!problems.isEmpty()) { System.out.println(); @@ -146,14 +193,16 @@ public List loadScenarios(InvocationSettings settings) { System.out.println(problem); } System.out.println(); - throw new IllegalArgumentException("There were some problems with the profiler configuration. Please see the log output for details."); + throw new IllegalArgumentException( + "There were some problems with the profiler configuration. Please see the log output for details."); } return scenarios; } private List doLoadScenarios(InvocationSettings settings) { if (settings.getScenarioFile() != null) { - return loadScenarios(settings.getScenarioFile(), settings, gradleBuildConfigurationReader); + return loadScenarios( + settings.getScenarioFile(), settings, gradleBuildConfigurationReader); } else { return adhocScenarios(settings); } @@ -170,30 +219,46 @@ private List adhocScenarios(InvocationSettings settings) { } for (GradleBuildConfiguration version : versions) { - File outputDir = versions.size() == 1 ? settings.getOutputDir() : new File(settings.getOutputDir(), version.getGradleVersion().getVersion()); - scenarios.add(new AdhocGradleScenarioDefinition( - version, - (GradleBuildInvoker) settings.getInvoker(), - new RunTasksAction(settings.getTargets()), - settings.getSystemProperties(), - getWarmUpCount(settings, settings.getInvoker(), settings.getWarmUpCount()), - getBuildCount(settings), - outputDir, - settings.getMeasuredBuildOperations() - )); + File outputDir = + versions.size() == 1 + ? settings.getOutputDir() + : new File( + settings.getOutputDir(), + version.getGradleVersion().getVersion()); + scenarios.add( + new AdhocGradleScenarioDefinition( + version, + (GradleBuildInvoker) settings.getInvoker(), + new RunTasksAction(settings.getTargets()), + settings.getSystemProperties(), + getWarmUpCount( + settings, settings.getInvoker(), settings.getWarmUpCount()), + getBuildCount(settings), + outputDir, + settings.getMeasuredBuildOperations())); } return scenarios; } - static List loadScenarios(File scenarioFile, InvocationSettings settings, GradleBuildConfigurationReader inspector) { + static List loadScenarios( + File scenarioFile, + InvocationSettings settings, + GradleBuildConfigurationReader inspector) { List definitions = new ArrayList<>(); - Config config = ConfigFactory.parseFile(scenarioFile, ConfigParseOptions.defaults().setAllowMissing(false)).resolve(); + Config config = + ConfigFactory.parseFile( + scenarioFile, ConfigParseOptions.defaults().setAllowMissing(false)) + .resolve(); Set roots = config.root().keySet(); Set selectedScenarios; if (!settings.getTargets().isEmpty()) { for (String target : settings.getTargets()) { if (!roots.contains(target)) { - throw new IllegalArgumentException("Unknown scenario '" + target + "' requested. Available scenarios are: " + roots.stream().sorted().collect(Collectors.joining(", "))); + throw new IllegalArgumentException( + "Unknown scenario '" + + target + + "' requested. Available scenarios are: " + + roots.stream().sorted().collect(Collectors.joining(", "))); } } selectedScenarios = new LinkedHashSet<>(settings.getTargets()); @@ -206,76 +271,136 @@ static List loadScenarios(File scenarioFile, InvocationSetti Config scenario = config.getConfig(scenarioName); for (String key : config.getObject(scenarioName).keySet()) { if (!ALL_SCENARIO_KEYS.contains(key)) { - throw new IllegalArgumentException("Unrecognized key '" + scenarioName + "." + key + "' defined in scenario file " + scenarioFile); + throw new IllegalArgumentException( + "Unrecognized key '" + + scenarioName + + "." + + key + + "' defined in scenario file " + + scenarioFile); } } String title = scenario.hasPath(TITLE) ? scenario.getString(TITLE) : null; - List mutators = BUILD_MUTATOR_CONFIGURATORS.entrySet().stream() - .filter(entry -> scenario.hasPath(entry.getKey())) - .map(entry -> entry.getValue().configure(scenario, scenarioName, settings, entry.getKey())) - .filter(mutator -> mutator != BuildMutator.NOOP) - .collect(Collectors.toList()); + List mutators = + BUILD_MUTATOR_CONFIGURATORS.entrySet().stream() + .filter(entry -> scenario.hasPath(entry.getKey())) + .map( + entry -> + entry.getValue() + .configure( + scenario, + scenarioName, + settings, + entry.getKey())) + .filter(mutator -> mutator != BuildMutator.NOOP) + .collect(Collectors.toList()); int buildCount = getBuildCount(settings, scenario); - File scenarioBaseDir = new File(settings.getOutputDir(), GradleScenarioDefinition.safeFileName(scenarioName)); + File scenarioBaseDir = + new File( + settings.getOutputDir(), + GradleScenarioDefinition.safeFileName(scenarioName)); if (scenario.hasPath(BAZEL) && settings.isBazel()) { - Config executionInstructions = getConfig(scenarioFile, settings, scenarioName, scenario, BAZEL, BAZEL_KEYS); + Config executionInstructions = + getConfig( + scenarioFile, settings, scenarioName, scenario, BAZEL, BAZEL_KEYS); List targets = ConfigUtil.strings(executionInstructions, TARGETS); File bazelHome = getToolHome(executionInstructions); File outputDir = new File(scenarioBaseDir, "bazel"); int warmUpCount = getWarmUpCount(settings, scenario); - definitions.add(new BazelScenarioDefinition(scenarioName, title, targets, mutators, warmUpCount, buildCount, outputDir, bazelHome)); + definitions.add( + new BazelScenarioDefinition( + scenarioName, + title, + targets, + mutators, + warmUpCount, + buildCount, + outputDir, + bazelHome)); } else if (scenario.hasPath(BUCK) && settings.isBuck()) { - Config executionInstructions = getConfig(scenarioFile, settings, scenarioName, scenario, BUCK, BUCK_KEYS); + Config executionInstructions = + getConfig(scenarioFile, settings, scenarioName, scenario, BUCK, BUCK_KEYS); List targets = ConfigUtil.strings(executionInstructions, TARGETS); String type = ConfigUtil.string(executionInstructions, TYPE, null); File buckHome = getToolHome(executionInstructions); File outputDir = new File(scenarioBaseDir, "buck"); int warmUpCount = getWarmUpCount(settings, scenario); - definitions.add(new BuckScenarioDefinition(scenarioName, title, targets, type, mutators, warmUpCount, buildCount, outputDir, buckHome)); + definitions.add( + new BuckScenarioDefinition( + scenarioName, + title, + targets, + type, + mutators, + warmUpCount, + buildCount, + outputDir, + buckHome)); } else if (scenario.hasPath(MAVEN) && settings.isMaven()) { - Config executionInstructions = getConfig(scenarioFile, settings, scenarioName, scenario, MAVEN, MAVEN_KEYS); + Config executionInstructions = + getConfig( + scenarioFile, settings, scenarioName, scenario, MAVEN, MAVEN_KEYS); List targets = ConfigUtil.strings(executionInstructions, TARGETS); File mavenHome = getToolHome(executionInstructions); File outputDir = new File(scenarioBaseDir, "maven"); int warmUpCount = getWarmUpCount(settings, scenario); - definitions.add(new MavenScenarioDefinition(scenarioName, title, targets, mutators, warmUpCount, buildCount, outputDir, mavenHome)); + definitions.add( + new MavenScenarioDefinition( + scenarioName, + title, + targets, + mutators, + warmUpCount, + buildCount, + outputDir, + mavenHome)); } else if (!settings.isBazel() && !settings.isBuck() && !settings.isMaven()) { - List versions = ConfigUtil.strings(scenario, VERSIONS, settings.getVersions()).stream().map(inspector::readConfiguration).collect( - Collectors.toList()); + List versions = + ConfigUtil.strings(scenario, VERSIONS, settings.getVersions()).stream() + .map(inspector::readConfiguration) + .collect(Collectors.toList()); if (versions.isEmpty()) { versions.add(inspector.readConfiguration()); } List gradleArgs = ConfigUtil.strings(scenario, GRADLE_ARGS); BuildAction buildAction = getBuildAction(scenario, scenarioFile, settings); - GradleBuildInvoker invoker = invoker(scenario, (GradleBuildInvoker) settings.getInvoker(), buildAction); + GradleBuildInvoker invoker = + invoker(scenario, (GradleBuildInvoker) settings.getInvoker(), buildAction); int warmUpCount = getWarmUpCount(settings, invoker, scenario); - List measuredBuildOperations = getMeasuredBuildOperations(settings, scenario); + List measuredBuildOperations = + getMeasuredBuildOperations(settings, scenario); BuildAction cleanupAction = getCleanupAction(scenario); - Map systemProperties = ConfigUtil.map(scenario, SYSTEM_PROPERTIES, settings.getSystemProperties()); + Map systemProperties = + ConfigUtil.map(scenario, SYSTEM_PROPERTIES, settings.getSystemProperties()); List jvmArgs = ConfigUtil.strings(scenario, JVM_ARGS); for (GradleBuildConfiguration version : versions) { - File outputDir = versions.size() == 1 ? scenarioBaseDir : new File(scenarioBaseDir, version.getGradleVersion().getVersion()); - definitions.add(new GradleScenarioDefinition( - scenarioName, - title, - invoker, - version, - buildAction, - cleanupAction, - gradleArgs, - systemProperties, - mutators, - warmUpCount, - buildCount, - outputDir, - jvmArgs, - measuredBuildOperations - )); + File outputDir = + versions.size() == 1 + ? scenarioBaseDir + : new File( + scenarioBaseDir, + version.getGradleVersion().getVersion()); + definitions.add( + new GradleScenarioDefinition( + scenarioName, + title, + invoker, + version, + buildAction, + cleanupAction, + gradleArgs, + systemProperties, + mutators, + warmUpCount, + buildCount, + outputDir, + jvmArgs, + measuredBuildOperations)); } } } @@ -285,25 +410,41 @@ static List loadScenarios(File scenarioFile, InvocationSetti return definitions; } - private static Config getConfig(File scenarioFile, InvocationSettings settings, String scenarioName, Config scenario, String toolName, List toolKeys) { + private static Config getConfig( + File scenarioFile, + InvocationSettings settings, + String scenarioName, + Config scenario, + String toolName, + List toolKeys) { if (settings.isProfile()) { - throw new IllegalArgumentException("Can only profile scenario '" + scenarioName + "' when building using Gradle."); + throw new IllegalArgumentException( + "Can only profile scenario '" + scenarioName + "' when building using Gradle."); } Config executionInstructions = scenario.getConfig(toolName); for (String key : scenario.getObject(toolName).keySet()) { if (!toolKeys.contains(key)) { - throw new IllegalArgumentException("Unrecognized key '" + scenarioName + "." + toolName + "." + key + "' defined in scenario file " + scenarioFile); + throw new IllegalArgumentException( + "Unrecognized key '" + + scenarioName + + "." + + toolName + + "." + + key + + "' defined in scenario file " + + scenarioFile); } } return executionInstructions; } - private static ImmutableList getMeasuredBuildOperations(InvocationSettings settings, Config scenario) { + private static ImmutableList getMeasuredBuildOperations( + InvocationSettings settings, Config scenario) { return ImmutableSet.builder() - .addAll(settings.getMeasuredBuildOperations()) - .addAll(ConfigUtil.strings(scenario, MEASURED_BUILD_OPERATIONS)) - .build() - .asList(); + .addAll(settings.getMeasuredBuildOperations()) + .addAll(ConfigUtil.strings(scenario, MEASURED_BUILD_OPERATIONS)) + .build() + .asList(); } private static int getBuildCount(InvocationSettings settings) { @@ -337,14 +478,20 @@ private static File getToolHome(Config config) { } private static int getWarmUpCount(InvocationSettings settings, Config scenario) { - return getWarmUpCount(settings, settings.getInvoker(), ConfigUtil.optionalInteger(scenario, WARM_UP_COUNT)); + return getWarmUpCount( + settings, + settings.getInvoker(), + ConfigUtil.optionalInteger(scenario, WARM_UP_COUNT)); } - private static int getWarmUpCount(InvocationSettings settings, BuildInvoker invoker, Config scenario) { - return getWarmUpCount(settings, invoker, ConfigUtil.optionalInteger(scenario, WARM_UP_COUNT)); + private static int getWarmUpCount( + InvocationSettings settings, BuildInvoker invoker, Config scenario) { + return getWarmUpCount( + settings, invoker, ConfigUtil.optionalInteger(scenario, WARM_UP_COUNT)); } - private static int getWarmUpCount(InvocationSettings settings, BuildInvoker invoker, Integer providedValue) { + private static int getWarmUpCount( + InvocationSettings settings, BuildInvoker invoker, Integer providedValue) { if (settings.isDryRun()) { return 1; } @@ -361,7 +508,8 @@ private static int getWarmUpCount(InvocationSettings settings, BuildInvoker invo } } - public static GradleBuildInvoker invoker(Config config, GradleBuildInvoker defaultValue, BuildAction buildAction) { + public static GradleBuildInvoker invoker( + Config config, GradleBuildInvoker defaultValue, BuildAction buildAction) { GradleBuildInvoker invoker = defaultValue; boolean sync = buildAction instanceof AndroidStudioSyncAction; if (sync) { @@ -370,7 +518,8 @@ public static GradleBuildInvoker invoker(Config config, GradleBuildInvoker defau if (config.hasPath(RUN_USING)) { if (sync) { - throw new IllegalArgumentException("Cannot specify '" + RUN_USING + "' when performing Android sync."); + throw new IllegalArgumentException( + "Cannot specify '" + RUN_USING + "' when performing Android sync."); } String value = ConfigUtil.string(config, RUN_USING, null); if (value.equals("cli")) { @@ -378,20 +527,23 @@ public static GradleBuildInvoker invoker(Config config, GradleBuildInvoker defau } else if (value.equals("tooling-api")) { invoker = GradleBuildInvoker.ToolingApi; } else { - throw new IllegalArgumentException("Unexpected value for '" + RUN_USING + "' provided: " + value); + throw new IllegalArgumentException( + "Unexpected value for '" + RUN_USING + "' provided: " + value); } } if (config.hasPath(DAEMON)) { String value = ConfigUtil.string(config, DAEMON, null); if (value.equals("none")) { if (sync) { - throw new IllegalArgumentException("Cannot use no daemon when performing Android sync."); + throw new IllegalArgumentException( + "Cannot use no daemon when performing Android sync."); } invoker = GradleBuildInvoker.CliNoDaemon; } else if (value.equals("cold")) { invoker = invoker.withColdDaemon(); } else if (!value.equals("warm")) { - throw new IllegalArgumentException("Unexpected value for '" + DAEMON + "' provided: " + value); + throw new IllegalArgumentException( + "Unexpected value for '" + DAEMON + "' provided: " + value); } // else, already warm } @@ -406,20 +558,24 @@ private static BuildAction getCleanupAction(Config scenario) { return new RunTasksAction(tasks); } - private static BuildAction getBuildAction(Config scenario, File scenarioFile, InvocationSettings invocationSettings) { + private static BuildAction getBuildAction( + Config scenario, File scenarioFile, InvocationSettings invocationSettings) { Class toolingModel = getToolingModelClass(scenario, scenarioFile); boolean sync = scenario.hasPath(ANDROID_STUDIO_SYNC); List tasks = ConfigUtil.strings(scenario, TASKS); if (sync) { if (toolingModel != null) { - throw new IllegalArgumentException("Cannot load tooling model and Android studio sync in same scenario."); + throw new IllegalArgumentException( + "Cannot load tooling model and Android studio sync in same scenario."); } if (!tasks.isEmpty()) { - throw new IllegalArgumentException("Cannot run tasks and Android studio sync in same scenario."); + throw new IllegalArgumentException( + "Cannot run tasks and Android studio sync in same scenario."); } if (invocationSettings.getStudioInstallDir() == null) { - throw new IllegalArgumentException("Android Studio installation directory should be specified using --studio-install-dir when measuring Android studio sync."); + throw new IllegalArgumentException( + "Android Studio installation directory should be specified using --studio-install-dir when measuring Android studio sync."); } return new AndroidStudioSyncAction(); } @@ -439,7 +595,11 @@ private static Class getToolingModelClass(Config scenario, File scenarioFile) try { return Class.forName(toolingModelName); } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("Unrecognized tooling model '" + toolingModelName + "' defined in scenario file " + scenarioFile); + throw new IllegalArgumentException( + "Unrecognized tooling model '" + + toolingModelName + + "' defined in scenario file " + + scenarioFile); } } } diff --git a/src/main/java/org/gradle/profiler/ScenarioSettings.java b/src/main/java/org/gradle/profiler/ScenarioSettings.java index 00714eee..0ee92bef 100644 --- a/src/main/java/org/gradle/profiler/ScenarioSettings.java +++ b/src/main/java/org/gradle/profiler/ScenarioSettings.java @@ -4,7 +4,8 @@ public class ScenarioSettings { private final InvocationSettings invocationSettings; private final GradleScenarioDefinition scenario; - public ScenarioSettings(InvocationSettings invocationSettings, GradleScenarioDefinition scenario) { + public ScenarioSettings( + InvocationSettings invocationSettings, GradleScenarioDefinition scenario) { this.invocationSettings = invocationSettings; this.scenario = scenario; } diff --git a/src/main/java/org/gradle/profiler/StopDaemonAfterAction.java b/src/main/java/org/gradle/profiler/StopDaemonAfterAction.java index 9ef3bc6d..3e80063d 100644 --- a/src/main/java/org/gradle/profiler/StopDaemonAfterAction.java +++ b/src/main/java/org/gradle/profiler/StopDaemonAfterAction.java @@ -7,7 +7,10 @@ public class StopDaemonAfterAction implements B private final DaemonControl daemonControl; private final GradleBuildConfiguration configuration; - public StopDaemonAfterAction(BuildStepAction action, DaemonControl daemonControl, GradleBuildConfiguration configuration) { + public StopDaemonAfterAction( + BuildStepAction action, + DaemonControl daemonControl, + GradleBuildConfiguration configuration) { this.action = action; this.daemonControl = daemonControl; this.configuration = configuration; diff --git a/src/main/java/org/gradle/profiler/ToolingApiGradleClient.java b/src/main/java/org/gradle/profiler/ToolingApiGradleClient.java index 76311383..5fdeedd8 100644 --- a/src/main/java/org/gradle/profiler/ToolingApiGradleClient.java +++ b/src/main/java/org/gradle/profiler/ToolingApiGradleClient.java @@ -36,43 +36,55 @@ private static R run(T operation, Function R runOperation( - Function createOperation, - Function operationAction - ) { + Function createOperation, Function operationAction) { return run(createOperation.apply(projectConnection), operationAction); } @Override public void runTasks(List tasks, List gradleArgs, List jvmArgs) { - runOperation(ProjectConnection::newBuild, build -> { - build.forTasks(tasks.toArray(new String[0])); - build.withArguments(gradleArgs); - build.setJvmArguments(jvmArgs); - build.run(); - return null; - }); + runOperation( + ProjectConnection::newBuild, + build -> { + build.forTasks(tasks.toArray(new String[0])); + build.withArguments(gradleArgs); + build.setJvmArguments(jvmArgs); + build.run(); + return null; + }); } @Override - public void loadToolingModel(List tasks, List gradleArgs, List jvmArgs, Class toolingModel) { - runOperation(connection -> connection.model(toolingModel), build -> { - build.forTasks(tasks.toArray(new String[0])); - build.withArguments(gradleArgs); - build.setJvmArguments(jvmArgs); - build.get(); - return null; - }); + public void loadToolingModel( + List tasks, + List gradleArgs, + List jvmArgs, + Class toolingModel) { + runOperation( + connection -> connection.model(toolingModel), + build -> { + build.forTasks(tasks.toArray(new String[0])); + build.withArguments(gradleArgs); + build.setJvmArguments(jvmArgs); + build.get(); + return null; + }); } @Override - public T runToolingAction(List tasks, List gradleArgs, List jvmArgs, BuildAction action, Consumer> configureAction) { - return runOperation(connection -> connection.action(action), build -> { - build.forTasks(tasks.toArray(new String[0])); - build.withArguments(gradleArgs); - build.setJvmArguments(jvmArgs); - configureAction.accept(build); - return build.run(); - }); + public T runToolingAction( + List tasks, + List gradleArgs, + List jvmArgs, + BuildAction action, + Consumer> configureAction) { + return runOperation( + connection -> connection.action(action), + build -> { + build.forTasks(tasks.toArray(new String[0])); + build.withArguments(gradleArgs); + build.setJvmArguments(jvmArgs); + configureAction.accept(build); + return build.run(); + }); } } - diff --git a/src/main/java/org/gradle/profiler/Version.java b/src/main/java/org/gradle/profiler/Version.java index ffcc5bd7..95128fd5 100644 --- a/src/main/java/org/gradle/profiler/Version.java +++ b/src/main/java/org/gradle/profiler/Version.java @@ -3,8 +3,6 @@ public class Version { public static String getVersion() { String version = Version.class.getPackage().getImplementationVersion(); - return version != null - ? version - : "UNKNOWN"; + return version != null ? version : "UNKNOWN"; } } diff --git a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfiler.java b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfiler.java index 883b2040..12ee39ce 100644 --- a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfiler.java +++ b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfiler.java @@ -16,7 +16,10 @@ public class AsyncProfiler extends InstrumentingProfiler { } @Override - protected JvmArgsCalculator jvmArgsWithInstrumentation(ScenarioSettings settings, boolean startRecordingOnProcessStart, boolean captureSnapshotOnProcessExit) { + protected JvmArgsCalculator jvmArgsWithInstrumentation( + ScenarioSettings settings, + boolean startRecordingOnProcessStart, + boolean captureSnapshotOnProcessExit) { if (!startRecordingOnProcessStart && !captureSnapshotOnProcessExit) { // Can attach later instead return JvmArgsCalculator.DEFAULT; diff --git a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerConfig.java b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerConfig.java index 70e6008b..8df5acc4 100644 --- a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerConfig.java +++ b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerConfig.java @@ -11,7 +11,14 @@ public class AsyncProfilerConfig { private final int frameBuffer; private final boolean includeSystemThreads; - public AsyncProfilerConfig(File profilerHome, String event, Counter counter, int interval, int stackDepth, int frameBuffer, boolean includeSystemThreads) { + public AsyncProfilerConfig( + File profilerHome, + String event, + Counter counter, + int interval, + int stackDepth, + int frameBuffer, + boolean includeSystemThreads) { this.profilerHome = profilerHome; this.event = event; this.counter = counter; diff --git a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerController.java b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerController.java index a223f86f..19998926 100644 --- a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerController.java +++ b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerController.java @@ -17,23 +17,26 @@ import static org.gradle.profiler.asyncprofiler.AsyncProfilerConfig.Counter; import static org.gradle.profiler.flamegraph.FlameGraphSanitizer.*; -public class AsyncProfilerController implements InstrumentingProfiler.SnapshotCapturingProfilerController { +public class AsyncProfilerController + implements InstrumentingProfiler.SnapshotCapturingProfilerController { private final AsyncProfilerConfig profilerConfig; private final ScenarioSettings scenarioSettings; private final FlameGraphTool flamegraphGenerator; private final FlameGraphSanitizer flamegraphSanitizer; private final File stacks; - public AsyncProfilerController(AsyncProfilerConfig profilerConfig, ScenarioSettings scenarioSettings) { + public AsyncProfilerController( + AsyncProfilerConfig profilerConfig, ScenarioSettings scenarioSettings) { this.profilerConfig = profilerConfig; this.scenarioSettings = scenarioSettings; - ImmutableList.Builder sanitizers = ImmutableList.builder(); + ImmutableList.Builder sanitizers = + ImmutableList.builder(); if (!profilerConfig.isIncludeSystemThreads()) { sanitizers.add(new RemoveSystemThreads()); - } sanitizers.add(COLLAPSE_BUILD_SCRIPTS, COLLAPSE_GRADLE_INFRASTRUCTURE, SIMPLE_NAMES); - this.flamegraphSanitizer = new FlameGraphSanitizer(sanitizers.build().toArray(new SanitizeFunction[0])); + this.flamegraphSanitizer = + new FlameGraphSanitizer(sanitizers.build().toArray(new SanitizeFunction[0])); this.flamegraphGenerator = new FlameGraphTool(); this.stacks = AsyncProfiler.stacksFileFor(scenarioSettings.getScenario()); @@ -45,60 +48,79 @@ public String getName() { @Override public void startRecording(String pid) throws IOException, InterruptedException { - new CommandExec().run( - getProfilerScript().getAbsolutePath(), - "start", - "-e", profilerConfig.getEvent(), - "-i", String.valueOf(profilerConfig.getInterval()), - "-j", String.valueOf(profilerConfig.getStackDepth()), - "-b", String.valueOf(profilerConfig.getFrameBuffer()), - pid - ); + new CommandExec() + .run( + getProfilerScript().getAbsolutePath(), + "start", + "-e", + profilerConfig.getEvent(), + "-i", + String.valueOf(profilerConfig.getInterval()), + "-j", + String.valueOf(profilerConfig.getStackDepth()), + "-b", + String.valueOf(profilerConfig.getFrameBuffer()), + pid); } @Override public void stopRecording(String pid) throws IOException, InterruptedException { - new CommandExec().run( - getProfilerScript().getAbsolutePath(), - "stop", - "-o", "collapsed=" + profilerConfig.getCounter().name().toLowerCase(Locale.ROOT), - "-a", - "-f", stacks.getAbsolutePath(), - pid - ); + new CommandExec() + .run( + getProfilerScript().getAbsolutePath(), + "stop", + "-o", + "collapsed=" + profilerConfig.getCounter().name().toLowerCase(Locale.ROOT), + "-a", + "-f", + stacks.getAbsolutePath(), + pid); } @Override - public void captureSnapshot(String pid) { - } + public void captureSnapshot(String pid) {} @Override public void stopSession() { GradleScenarioDefinition scenario = scenarioSettings.getScenario(); if (flamegraphGenerator.checkInstallation()) { - File simplifiedStacks = new File(scenario.getOutputDir(), scenario.getProfileName() + ".simplified-stacks.txt"); + File simplifiedStacks = + new File( + scenario.getOutputDir(), + scenario.getProfileName() + ".simplified-stacks.txt"); flamegraphSanitizer.sanitize(stacks, simplifiedStacks); Counter counter = profilerConfig.getCounter(); String unit = counter == Counter.SAMPLES ? "samples" : "units"; String titlePrefix = profilerConfig.getEvent().toUpperCase(Locale.ROOT); - File flamegraph = new File(scenario.getOutputDir(), scenario.getProfileName() + "-flames.svg"); + File flamegraph = + new File(scenario.getOutputDir(), scenario.getProfileName() + "-flames.svg"); flamegraphGenerator.generateFlameGraph( - simplifiedStacks, flamegraph, - "--colors", "java", - "--minwidth", "1", - "--title", titlePrefix + " Flame Graph", - "--countname", unit - ); - File iciclegraph = new File(scenario.getOutputDir(), scenario.getProfileName() + "-icicles.svg"); + simplifiedStacks, + flamegraph, + "--colors", + "java", + "--minwidth", + "1", + "--title", + titlePrefix + " Flame Graph", + "--countname", + unit); + File iciclegraph = + new File(scenario.getOutputDir(), scenario.getProfileName() + "-icicles.svg"); flamegraphGenerator.generateFlameGraph( - simplifiedStacks, iciclegraph, - "--reverse", "--invert", - "--colors", "java", - "--minwidth", "2", - "--title", titlePrefix + " Icicle Graph", - "--countname", unit - ); + simplifiedStacks, + iciclegraph, + "--reverse", + "--invert", + "--colors", + "java", + "--minwidth", + "2", + "--title", + titlePrefix + " Icicle Graph", + "--countname", + unit); } } @@ -118,5 +140,4 @@ public List map(List stack) { return stack; } } - } diff --git a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerDownload.java b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerDownload.java index 1ccecb86..f0e6e261 100644 --- a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerDownload.java +++ b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerDownload.java @@ -21,14 +21,13 @@ import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; -/** - * Downloads a version of async profiler and installs into ~/.gradle-profiler-dist. - */ +/** Downloads a version of async profiler and installs into ~/.gradle-profiler-dist. */ public class AsyncProfilerDownload { private static final String ASYNC_PROFILER_VERSION = "1.8.2"; /** - * Attempts to locate a default install of async profiler. Uses a previously downloaded installation, or downloads if not available. + * Attempts to locate a default install of async profiler. Uses a previously downloaded + * installation, or downloads if not available. * * @return null if not available. */ @@ -42,16 +41,27 @@ static File defaultHome() { return null; } - File installDist = new File(new File(System.getProperty("user.home")), ".gradle-profiler-dist/" + ASYNC_PROFILER_VERSION + "-" + platformName); + File installDist = + new File( + new File(System.getProperty("user.home")), + ".gradle-profiler-dist/" + ASYNC_PROFILER_VERSION + "-" + platformName); File marker = new File(installDist, "ok"); - File homeDir = new File(installDist, String.format("async-profiler-%s-%s", ASYNC_PROFILER_VERSION, platformName)); + File homeDir = + new File( + installDist, + String.format( + "async-profiler-%s-%s", ASYNC_PROFILER_VERSION, platformName)); if (marker.isFile()) { return homeDir; } try { - URL download = new URL(String.format("https://github.com/jvm-profiling-tools/async-profiler/releases/download/v%s/async-profiler-%s-%s.tar.gz", ASYNC_PROFILER_VERSION, ASYNC_PROFILER_VERSION, platformName)); + URL download = + new URL( + String.format( + "https://github.com/jvm-profiling-tools/async-profiler/releases/download/v%s/async-profiler-%s-%s.tar.gz", + ASYNC_PROFILER_VERSION, ASYNC_PROFILER_VERSION, platformName)); Logging.startOperation("Download and install " + download); Files.createDirectories(installDist.toPath()); @@ -70,7 +80,9 @@ static File defaultHome() { } private static void untarTo(File source, File destDir) throws IOException { - try (TarArchiveInputStream tarStream = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(source)))) { + try (TarArchiveInputStream tarStream = + new TarArchiveInputStream( + new GzipCompressorInputStream(new FileInputStream(source)))) { while (tarStream.getNextEntry() != null) { if (tarStream.getCurrentEntry().isDirectory()) { continue; @@ -81,7 +93,8 @@ private static void untarTo(File source, File destDir) throws IOException { Files.copy(tarStream, file.toPath(), REPLACE_EXISTING); boolean executable = (tarStream.getCurrentEntry().getMode() & 0x40) != 0; if (executable) { - Set permissions = Files.getPosixFilePermissions(file.toPath()); + Set permissions = + Files.getPosixFilePermissions(file.toPath()); ImmutableSet.Builder withExecute = ImmutableSet.builder(); withExecute.addAll(permissions); withExecute.add(PosixFilePermission.OWNER_EXECUTE); @@ -99,19 +112,23 @@ private static void copyTo(URL source, File dest) throws IOException { private static void deleteDir(File homeDir) throws IOException { if (homeDir.exists()) { - Files.walkFileTree(homeDir.toPath(), new SimpleFileVisitor() { - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - Files.delete(dir); - return FileVisitResult.CONTINUE; - } - }); + Files.walkFileTree( + homeDir.toPath(), + new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) + throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) + throws IOException { + Files.delete(dir); + return FileVisitResult.CONTINUE; + } + }); } } } diff --git a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerFactory.java b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerFactory.java index c26f662b..f73872de 100644 --- a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerFactory.java +++ b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerFactory.java @@ -25,39 +25,54 @@ public class AsyncProfilerFactory extends ProfilerFactory { @Override public void addOptions(OptionParser parser) { - profilerHomeOption = parser.accepts("async-profiler-home", "Async Profiler home directory") - .availableIf("profile") - .withRequiredArg() - .ofType(File.class); - eventOption = parser.accepts("async-profiler-event", "The event to sample, e.g. 'cpu' or 'alloc'.") - .availableIf("profile") - .withRequiredArg() - .defaultsTo("cpu"); - counterOption = parser.accepts("async-profiler-counter", "The counter to use, either 'samples' or 'totals'") - .availableIf("profile") - .withRequiredArg() - .withValuesConvertedBy(new CounterConverter()) - .defaultsTo(AsyncProfilerConfig.Counter.SAMPLES); - intervalOption = parser.accepts("async-profiler-interval", "The sampling interval in nanoseconds.") - .availableIf("profile") - .withRequiredArg() - .ofType(Integer.class) - .defaultsTo(10_000_000); - stackDepthOption = parser.accepts("async-profiler-stackdepth", "The maximum Java stack depth.") - .availableIf("profile") - .withRequiredArg() - .ofType(Integer.class) - .defaultsTo(2048); - frameBufferOption = parser.accepts("async-profiler-framebuffer", "The size of the frame buffer in bytes.") - .availableIf("profile") - .withRequiredArg() - .ofType(Integer.class) - .defaultsTo(10_000_000); - systemThreadOption = parser.accepts("async-profiler-system-threads", "Whether to show system threads like GC and JIT compiler.") - .availableIf("profile") - .withRequiredArg() - .ofType(Boolean.class) - .defaultsTo(false); + profilerHomeOption = + parser.accepts("async-profiler-home", "Async Profiler home directory") + .availableIf("profile") + .withRequiredArg() + .ofType(File.class); + eventOption = + parser.accepts( + "async-profiler-event", + "The event to sample, e.g. 'cpu' or 'alloc'.") + .availableIf("profile") + .withRequiredArg() + .defaultsTo("cpu"); + counterOption = + parser.accepts( + "async-profiler-counter", + "The counter to use, either 'samples' or 'totals'") + .availableIf("profile") + .withRequiredArg() + .withValuesConvertedBy(new CounterConverter()) + .defaultsTo(AsyncProfilerConfig.Counter.SAMPLES); + intervalOption = + parser.accepts("async-profiler-interval", "The sampling interval in nanoseconds.") + .availableIf("profile") + .withRequiredArg() + .ofType(Integer.class) + .defaultsTo(10_000_000); + stackDepthOption = + parser.accepts("async-profiler-stackdepth", "The maximum Java stack depth.") + .availableIf("profile") + .withRequiredArg() + .ofType(Integer.class) + .defaultsTo(2048); + frameBufferOption = + parser.accepts( + "async-profiler-framebuffer", + "The size of the frame buffer in bytes.") + .availableIf("profile") + .withRequiredArg() + .ofType(Integer.class) + .defaultsTo(10_000_000); + systemThreadOption = + parser.accepts( + "async-profiler-system-threads", + "Whether to show system threads like GC and JIT compiler.") + .availableIf("profile") + .withRequiredArg() + .ofType(Boolean.class) + .defaultsTo(false); } @Override @@ -74,7 +89,8 @@ AsyncProfilerConfig createConfig(OptionSet parsedOptions) { int stackDepth = stackDepthOption.value(parsedOptions); int frameBuffer = frameBufferOption.value(parsedOptions); Boolean showSystemThreads = systemThreadOption.value(parsedOptions); - return new AsyncProfilerConfig(profilerHome, event, counter, interval, stackDepth, frameBuffer, showSystemThreads); + return new AsyncProfilerConfig( + profilerHome, event, counter, interval, stackDepth, frameBuffer, showSystemThreads); } private File getProfilerHome(OptionSet parsedOptions) { @@ -90,7 +106,8 @@ private File getProfilerHome(OptionSet parsedOptions) { profilerHome = AsyncProfilerDownload.defaultHome(); } if (profilerHome == null) { - throw new IllegalStateException("Async profiler not supported on " + OperatingSystem.getId()); + throw new IllegalStateException( + "Async profiler not supported on " + OperatingSystem.getId()); } return profilerHome; } diff --git a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerHeapAllocationProfilerFactory.java b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerHeapAllocationProfilerFactory.java index 26aaa9bc..d21f24df 100644 --- a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerHeapAllocationProfilerFactory.java +++ b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerHeapAllocationProfilerFactory.java @@ -5,7 +5,8 @@ import org.gradle.profiler.ProfilerFactory; public class AsyncProfilerHeapAllocationProfilerFactory extends ProfilerFactory { - public static final ProfilerFactory INSTANCE = new AsyncProfilerHeapAllocationProfilerFactory(AsyncProfilerFactory.INSTANCE); + public static final ProfilerFactory INSTANCE = + new AsyncProfilerHeapAllocationProfilerFactory(AsyncProfilerFactory.INSTANCE); private final AsyncProfilerFactory asyncProfilerFactory; @@ -16,7 +17,15 @@ public AsyncProfilerHeapAllocationProfilerFactory(AsyncProfilerFactory asyncProf @Override public Profiler createFromOptions(OptionSet parsedOptions) { AsyncProfilerConfig config = asyncProfilerFactory.createConfig(parsedOptions); - AsyncProfilerConfig overrides = new AsyncProfilerConfig(config.getProfilerHome(), "alloc", AsyncProfilerConfig.Counter.TOTAL, 10, config.getStackDepth(), config.getFrameBuffer(), config.isIncludeSystemThreads()); + AsyncProfilerConfig overrides = + new AsyncProfilerConfig( + config.getProfilerHome(), + "alloc", + AsyncProfilerConfig.Counter.TOTAL, + 10, + config.getStackDepth(), + config.getFrameBuffer(), + config.isIncludeSystemThreads()); return new AsyncProfiler(overrides); } } diff --git a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerJvmArgsCalculator.java b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerJvmArgsCalculator.java index 91f749ce..3828b9c2 100644 --- a/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerJvmArgsCalculator.java +++ b/src/main/java/org/gradle/profiler/asyncprofiler/AsyncProfilerJvmArgsCalculator.java @@ -13,7 +13,10 @@ class AsyncProfilerJvmArgsCalculator implements JvmArgsCalculator { private final ScenarioSettings scenarioSettings; private final boolean captureSnapshotOnProcessExit; - AsyncProfilerJvmArgsCalculator(AsyncProfilerConfig profilerConfig, ScenarioSettings scenarioSettings, boolean captureSnapshotOnProcessExit) { + AsyncProfilerJvmArgsCalculator( + AsyncProfilerConfig profilerConfig, + ScenarioSettings scenarioSettings, + boolean captureSnapshotOnProcessExit) { this.profilerConfig = profilerConfig; this.scenarioSettings = scenarioSettings; this.captureSnapshotOnProcessExit = captureSnapshotOnProcessExit; @@ -21,14 +24,22 @@ class AsyncProfilerJvmArgsCalculator implements JvmArgsCalculator { @Override public void calculateJvmArgs(List jvmArgs) { - StringBuilder agent = new StringBuilder() - .append("-agentpath:").append(profilerConfig.getProfilerHome()).append("/build/libasyncProfiler.so=start") - .append(",event=").append(profilerConfig.getEvent()) - .append(",interval=").append(profilerConfig.getInterval()) - .append(",jstackdepth=").append(profilerConfig.getStackDepth()) - .append(",buffer=").append(profilerConfig.getFrameBuffer()) - .append(",collapsed=").append(profilerConfig.getCounter().name().toLowerCase(Locale.ROOT)) - .append(",ann"); + StringBuilder agent = + new StringBuilder() + .append("-agentpath:") + .append(profilerConfig.getProfilerHome()) + .append("/build/libasyncProfiler.so=start") + .append(",event=") + .append(profilerConfig.getEvent()) + .append(",interval=") + .append(profilerConfig.getInterval()) + .append(",jstackdepth=") + .append(profilerConfig.getStackDepth()) + .append(",buffer=") + .append(profilerConfig.getFrameBuffer()) + .append(",collapsed=") + .append(profilerConfig.getCounter().name().toLowerCase(Locale.ROOT)) + .append(",ann"); if (captureSnapshotOnProcessExit) { GradleScenarioDefinition scenario = scenarioSettings.getScenario(); diff --git a/src/main/java/org/gradle/profiler/buildops/BuildOperationInstrumentation.java b/src/main/java/org/gradle/profiler/buildops/BuildOperationInstrumentation.java index 1264bb7d..7d740522 100644 --- a/src/main/java/org/gradle/profiler/buildops/BuildOperationInstrumentation.java +++ b/src/main/java/org/gradle/profiler/buildops/BuildOperationInstrumentation.java @@ -23,14 +23,24 @@ public class BuildOperationInstrumentation extends GradleInstrumentation { private final File configurationTimeDataFile; private final Map buildOperationDataFiles; - public BuildOperationInstrumentation(boolean measureGarbageCollection, boolean measureConfigTime, List measuredBuildOperations) throws IOException { + public BuildOperationInstrumentation( + boolean measureGarbageCollection, + boolean measureConfigTime, + List measuredBuildOperations) + throws IOException { this.measureGarbageCollection = measureGarbageCollection; this.totalGarbageCollectionTimeDataFile = File.createTempFile("gradle-profiler", "gc-time"); this.measureConfigTime = measureConfigTime; - this.configurationTimeDataFile = File.createTempFile("gradle-profiler", "build-ops-config-time"); + this.configurationTimeDataFile = + File.createTempFile("gradle-profiler", "build-ops-config-time"); this.configurationTimeDataFile.deleteOnExit(); - this.buildOperationDataFiles = measuredBuildOperations.stream() - .collect(Collectors.toMap(Function.identity(), BuildOperationInstrumentation::createBuildOperationTempFile)); + this.buildOperationDataFiles = + measuredBuildOperations.stream() + .collect( + Collectors.toMap( + Function.identity(), + BuildOperationInstrumentation + ::createBuildOperationTempFile)); } public boolean requiresInitScript() { @@ -51,16 +61,19 @@ private static File createBuildOperationTempFile(String op) { protected void generateInitScriptBody(PrintWriter writer) { writer.print("new org.gradle.trace.buildops.BuildOperationTrace(gradle)"); if (measureGarbageCollection) { - writer.print(".measureGarbageCollection(" + newFile(totalGarbageCollectionTimeDataFile) + ")"); + writer.print( + ".measureGarbageCollection(" + + newFile(totalGarbageCollectionTimeDataFile) + + ")"); } if (measureConfigTime) { writer.print(".measureConfigurationTime(" + newFile(configurationTimeDataFile) + ")"); } if (!buildOperationDataFiles.isEmpty()) { writer.print(".measureBuildOperations("); - buildOperationDataFiles.forEach((opName, dataFile) -> - writer.print(String.format("'%s': %s,", opName, newFile(dataFile))) - ); + buildOperationDataFiles.forEach( + (opName, dataFile) -> + writer.print(String.format("'%s': %s,", opName, newFile(dataFile)))); writer.print(")"); } } @@ -70,7 +83,8 @@ private String newFile(File dataFile) { } /** - * This is the cumulative total GC time since the process started, not the GC time of the current invocation. + * This is the cumulative total GC time since the process started, not the GC time of the + * current invocation. */ public Optional getTotalGarbageCollectionTime() { if (totalGarbageCollectionTimeDataFile.length() == 0) { @@ -85,10 +99,10 @@ public Optional getTimeToTaskExecution() { return Optional.empty(); } try { - try (Stream lines = Files.lines(configurationTimeDataFile.toPath(), StandardCharsets.UTF_8)) { - return lines - .reduce((first, second) -> second) - .map(line -> Duration.ofMillis(Long.parseLong(line))); + try (Stream lines = + Files.lines(configurationTimeDataFile.toPath(), StandardCharsets.UTF_8)) { + return lines.reduce((first, second) -> second) + .map(line -> Duration.ofMillis(Long.parseLong(line))); } } catch (IOException e) { throw new UncheckedIOException("Could not read result from file.", e); @@ -97,11 +111,11 @@ public Optional getTimeToTaskExecution() { public Map getCumulativeBuildOperationTimes() { return buildOperationDataFiles.entrySet().stream() - .filter(entry -> entry.getValue().length() > 0) - .collect(Collectors.toMap( - Map.Entry::getKey, - (entry -> readCumulativeTimeFromDataFile(entry.getValue()))) - ); + .filter(entry -> entry.getValue().length() > 0) + .collect( + Collectors.toMap( + Map.Entry::getKey, + (entry -> readCumulativeTimeFromDataFile(entry.getValue())))); } private static Duration readCumulativeTimeFromDataFile(File dataFile) { diff --git a/src/main/java/org/gradle/profiler/buildops/BuildOperationUtil.java b/src/main/java/org/gradle/profiler/buildops/BuildOperationUtil.java index 3a432d42..4417e66d 100644 --- a/src/main/java/org/gradle/profiler/buildops/BuildOperationUtil.java +++ b/src/main/java/org/gradle/profiler/buildops/BuildOperationUtil.java @@ -4,7 +4,7 @@ public class BuildOperationUtil { public static String getSimpleBuildOperationName(String buildOperationDetailsClass) { int lastDot = buildOperationDetailsClass.lastIndexOf('.'); return lastDot == -1 - ? buildOperationDetailsClass - : buildOperationDetailsClass.substring(lastDot + 1); + ? buildOperationDetailsClass + : buildOperationDetailsClass.substring(lastDot + 1); } } diff --git a/src/main/java/org/gradle/profiler/buildscan/BuildScanInitScript.java b/src/main/java/org/gradle/profiler/buildscan/BuildScanInitScript.java index b6c2ae69..739e4044 100644 --- a/src/main/java/org/gradle/profiler/buildscan/BuildScanInitScript.java +++ b/src/main/java/org/gradle/profiler/buildscan/BuildScanInitScript.java @@ -41,7 +41,8 @@ public void writeContents(final PrintWriter writer) { writer.write("}\n"); writer.write("\n"); writer.write("rootProject { prj ->\n"); - writer.write(" apply plugin: initscript.classLoader.loadClass(\"com.gradle.scan.plugin.BuildScanPlugin\")\n"); + writer.write( + " apply plugin: initscript.classLoader.loadClass(\"com.gradle.scan.plugin.BuildScanPlugin\")\n"); writer.write(" buildScan {\n"); if (version.startsWith("0.") || version.startsWith("1.")) { writer.write(" licenseAgreementUrl = 'https://gradle.com/terms-of-service'\n"); @@ -53,6 +54,4 @@ public void writeContents(final PrintWriter writer) { writer.write(" }\n"); writer.write("}\n"); } - - } diff --git a/src/main/java/org/gradle/profiler/buildscan/BuildScanProfiler.java b/src/main/java/org/gradle/profiler/buildscan/BuildScanProfiler.java index e57aec15..6ac18f63 100644 --- a/src/main/java/org/gradle/profiler/buildscan/BuildScanProfiler.java +++ b/src/main/java/org/gradle/profiler/buildscan/BuildScanProfiler.java @@ -38,8 +38,10 @@ public String toString() { } private static class LogParser implements Consumer { - private static final Pattern RUNNING_SCENARIO = Pattern.compile("\\* Running scenario (.*) \\(scenario \\d+/\\d+\\)"); - private static final Pattern RUNNING_BUILD = Pattern.compile("\\* Running measured build #(\\d+)"); + private static final Pattern RUNNING_SCENARIO = + Pattern.compile("\\* Running scenario (.*) \\(scenario \\d+/\\d+\\)"); + private static final Pattern RUNNING_BUILD = + Pattern.compile("\\* Running measured build #(\\d+)"); private boolean nextLineIsBuildScanUrl; private String measuredBuildNumber = null; private final Consumer results; @@ -52,7 +54,10 @@ public LogParser(Consumer results) { public void accept(String line) { if (nextLineIsBuildScanUrl) { if (measuredBuildNumber != null) { - results.accept(String.format("- Build scan for measured build #%s: %s", measuredBuildNumber, line)); + results.accept( + String.format( + "- Build scan for measured build #%s: %s", + measuredBuildNumber, line)); measuredBuildNumber = null; } nextLineIsBuildScanUrl = false; @@ -88,25 +93,31 @@ public void summarizeResultFile(File resultFile, Consumer consumer) { @Override public GradleArgsCalculator newGradleArgsCalculator(ScenarioSettings settings) { return gradleArgs -> { - GradleBuildConfiguration buildConfiguration = settings.getScenario().getBuildConfiguration(); + GradleBuildConfiguration buildConfiguration = + settings.getScenario().getBuildConfiguration(); if (!buildConfiguration.isUsesScanPlugin()) { String effectiveBuildScanVersion = getEffectiveBuildScanVersion(buildConfiguration); - GeneratedInitScript buildScanInitScript = (buildConfiguration.getGradleVersion().compareTo(GRADLE_6) < 0) - ? new BuildScanInitScript(effectiveBuildScanVersion) - : new GradleEnterpriseInitScript(effectiveBuildScanVersion); + GeneratedInitScript buildScanInitScript = + (buildConfiguration.getGradleVersion().compareTo(GRADLE_6) < 0) + ? new BuildScanInitScript(effectiveBuildScanVersion) + : new GradleEnterpriseInitScript(effectiveBuildScanVersion); buildScanInitScript.calculateGradleArgs(gradleArgs); } }; } @Override - public GradleArgsCalculator newInstrumentedBuildsGradleArgsCalculator(ScenarioSettings settings) { + public GradleArgsCalculator newInstrumentedBuildsGradleArgsCalculator( + ScenarioSettings settings) { return gradleArgs -> { - GradleBuildConfiguration buildConfiguration = settings.getScenario().getBuildConfiguration(); + GradleBuildConfiguration buildConfiguration = + settings.getScenario().getBuildConfiguration(); if (buildConfiguration.isUsesScanPlugin()) { System.out.println("Using build scan plugin specified in the build"); } else { - System.out.println("Using build scan plugin " + getEffectiveBuildScanVersion(buildConfiguration)); + System.out.println( + "Using build scan plugin " + + getEffectiveBuildScanVersion(buildConfiguration)); } if (buildConfiguration.getGradleVersion().compareTo(GRADLE_5) < 0) { gradleArgs.add("-Dscan"); @@ -117,6 +128,8 @@ public GradleArgsCalculator newInstrumentedBuildsGradleArgsCalculator(ScenarioSe } private String getEffectiveBuildScanVersion(GradleBuildConfiguration buildConfiguration) { - return buildScanVersion != null ? buildScanVersion : defaultBuildScanVersion(buildConfiguration.getGradleVersion()); + return buildScanVersion != null + ? buildScanVersion + : defaultBuildScanVersion(buildConfiguration.getGradleVersion()); } } diff --git a/src/main/java/org/gradle/profiler/buildscan/BuildScanProfilerFactory.java b/src/main/java/org/gradle/profiler/buildscan/BuildScanProfilerFactory.java index cda856da..568c705e 100644 --- a/src/main/java/org/gradle/profiler/buildscan/BuildScanProfilerFactory.java +++ b/src/main/java/org/gradle/profiler/buildscan/BuildScanProfilerFactory.java @@ -14,7 +14,7 @@ public Profiler createFromOptions(OptionSet parsedOptions) { @Override public void addOptions(final OptionParser parser) { parser.accepts("buildscan-version", "Version of the Build Scan plugin") - .availableIf("profile") - .withOptionalArg(); + .availableIf("profile") + .withOptionalArg(); } } diff --git a/src/main/java/org/gradle/profiler/buildscan/GradleEnterpriseInitScript.java b/src/main/java/org/gradle/profiler/buildscan/GradleEnterpriseInitScript.java index 4220a65e..e6d2a3b7 100644 --- a/src/main/java/org/gradle/profiler/buildscan/GradleEnterpriseInitScript.java +++ b/src/main/java/org/gradle/profiler/buildscan/GradleEnterpriseInitScript.java @@ -34,13 +34,17 @@ public void writeContents(final PrintWriter writer) { writer.write(" gradlePluginPortal()\n"); writer.write(" }\n"); writer.write(" dependencies {\n"); - writer.write(" classpath \"com.gradle:gradle-enterprise-gradle-plugin:" + version + "\"\n"); + writer.write( + " classpath \"com.gradle:gradle-enterprise-gradle-plugin:" + + version + + "\"\n"); writer.write(" }\n"); writer.write("}\n"); writer.write("\n"); writer.write("settingsEvaluated {\n"); writer.write(" if (!it.pluginManager.hasPlugin(\"com.gradle.enterprise\")) {\n"); - writer.write(" it.pluginManager.apply(com.gradle.enterprise.gradleplugin.GradleEnterprisePlugin)\n"); + writer.write( + " it.pluginManager.apply(com.gradle.enterprise.gradleplugin.GradleEnterprisePlugin)\n"); writer.write(" }\n"); writer.write(" it.extensions[\"gradleEnterprise\"].buildScan.with {\n"); writer.write(" termsOfServiceUrl = 'https://gradle.com/terms-of-service'\n"); @@ -48,6 +52,4 @@ public void writeContents(final PrintWriter writer) { writer.write(" }\n"); writer.write("}\n"); } - - } diff --git a/src/main/java/org/gradle/profiler/chrometrace/ChromeTraceInstrumentation.java b/src/main/java/org/gradle/profiler/chrometrace/ChromeTraceInstrumentation.java index f7a57bef..798b6d5c 100644 --- a/src/main/java/org/gradle/profiler/chrometrace/ChromeTraceInstrumentation.java +++ b/src/main/java/org/gradle/profiler/chrometrace/ChromeTraceInstrumentation.java @@ -15,9 +15,9 @@ */ package org.gradle.profiler.chrometrace; -import org.gradle.profiler.instrument.GradleInstrumentation; import org.gradle.profiler.GradleScenarioDefinition; import org.gradle.profiler.ScenarioSettings; +import org.gradle.profiler.instrument.GradleInstrumentation; import java.io.File; import java.io.PrintWriter; @@ -32,6 +32,9 @@ public ChromeTraceInstrumentation(ScenarioSettings scenarioSettings) { @Override protected void generateInitScriptBody(PrintWriter writer) { - writer.println("org.gradle.trace.GradleTracingPlugin.start(gradle, new File(new URI(\"" + traceFile.toURI() + "\")))"); + writer.println( + "org.gradle.trace.GradleTracingPlugin.start(gradle, new File(new URI(\"" + + traceFile.toURI() + + "\")))"); } } diff --git a/src/main/java/org/gradle/profiler/chrometrace/ChromeTraceProfiler.java b/src/main/java/org/gradle/profiler/chrometrace/ChromeTraceProfiler.java index a6e93399..7d10e758 100644 --- a/src/main/java/org/gradle/profiler/chrometrace/ChromeTraceProfiler.java +++ b/src/main/java/org/gradle/profiler/chrometrace/ChromeTraceProfiler.java @@ -26,7 +26,8 @@ public GradleArgsCalculator newGradleArgsCalculator(ScenarioSettings settings) { } @Override - public GradleArgsCalculator newInstrumentedBuildsGradleArgsCalculator(ScenarioSettings settings) { + public GradleArgsCalculator newInstrumentedBuildsGradleArgsCalculator( + ScenarioSettings settings) { return gradleArgs -> gradleArgs.add("-Dtrace"); } } diff --git a/src/main/java/org/gradle/profiler/flamegraph/FlameGraphSanitizer.java b/src/main/java/org/gradle/profiler/flamegraph/FlameGraphSanitizer.java index ed8ac194..b90b2bd3 100644 --- a/src/main/java/org/gradle/profiler/flamegraph/FlameGraphSanitizer.java +++ b/src/main/java/org/gradle/profiler/flamegraph/FlameGraphSanitizer.java @@ -1,8 +1,5 @@ package org.gradle.profiler.flamegraph; -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; - import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; @@ -25,47 +22,79 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * Simplifies stacks to make flame graphs more readable. - */ +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; + +/** Simplifies stacks to make flame graphs more readable. */ public class FlameGraphSanitizer { private static final Splitter STACKTRACE_SPLITTER = Splitter.on(";").omitEmptyStrings(); private static final Joiner STACKTRACE_JOINER = Joiner.on(";"); - public static final SanitizeFunction COLLAPSE_BUILD_SCRIPTS = new ReplaceRegex( - ImmutableMap.of( - Pattern.compile("build_[a-z0-9]+"), "build script", - Pattern.compile("settings_[a-z0-9]+"), "settings script" - ) - ); - - public static final SanitizeFunction COLLAPSE_GRADLE_INFRASTRUCTURE = new CompositeSanitizeFunction( - new ChopPrefix("loadSettings"), - new ChopPrefix("configureBuild"), - new ChopPrefix("constructTaskGraph"), - new ChopPrefix("executeTasks"), - new ChopPrefix("org.gradle.api.internal.tasks.execution"), - new ReplaceContainment(singletonList("org.gradle.api.internal.tasks.execution"), "task execution_[j]"), - new ReplaceContainment(asList("DynamicObject", "Closure.call", "MetaClass", "MetaMethod", "CallSite", "ConfigureDelegate", "Method.invoke", "MethodAccessor", "Proxy", "ConfigureUtil", "Script.invoke", "ClosureBackedAction", "getProperty("), "dynamic invocation_[j]"), - new ReplaceContainment(asList("BuildOperation", "PluginManager", "ObjectConfigurationAction", "PluginTarget", "PluginAware", "Script.apply", "ScriptPlugin", "ScriptTarget", "ScriptRunner", "ProjectEvaluator", "Project.evaluate"), "Gradle infrastructure_[j]") - ); + public static final SanitizeFunction COLLAPSE_BUILD_SCRIPTS = + new ReplaceRegex( + ImmutableMap.of( + Pattern.compile("build_[a-z0-9]+"), "build script", + Pattern.compile("settings_[a-z0-9]+"), "settings script")); + + public static final SanitizeFunction COLLAPSE_GRADLE_INFRASTRUCTURE = + new CompositeSanitizeFunction( + new ChopPrefix("loadSettings"), + new ChopPrefix("configureBuild"), + new ChopPrefix("constructTaskGraph"), + new ChopPrefix("executeTasks"), + new ChopPrefix("org.gradle.api.internal.tasks.execution"), + new ReplaceContainment( + singletonList("org.gradle.api.internal.tasks.execution"), + "task execution_[j]"), + new ReplaceContainment( + asList( + "DynamicObject", + "Closure.call", + "MetaClass", + "MetaMethod", + "CallSite", + "ConfigureDelegate", + "Method.invoke", + "MethodAccessor", + "Proxy", + "ConfigureUtil", + "Script.invoke", + "ClosureBackedAction", + "getProperty("), + "dynamic invocation_[j]"), + new ReplaceContainment( + asList( + "BuildOperation", + "PluginManager", + "ObjectConfigurationAction", + "PluginTarget", + "PluginAware", + "Script.apply", + "ScriptPlugin", + "ScriptTarget", + "ScriptRunner", + "ProjectEvaluator", + "Project.evaluate"), + "Gradle infrastructure_[j]")); public static final SanitizeFunction SIMPLE_NAMES = new ToSimpleName(); private final SanitizeFunction sanitizeFunction; public FlameGraphSanitizer(SanitizeFunction... sanitizeFunctions) { - ImmutableList functions = ImmutableList.builder() - .addAll(Arrays.asList(sanitizeFunctions)) - .add(new CollapseDuplicateFrames()) - .build(); + ImmutableList functions = + ImmutableList.builder() + .addAll(Arrays.asList(sanitizeFunctions)) + .add(new CollapseDuplicateFrames()) + .build(); this.sanitizeFunction = new CompositeSanitizeFunction(functions); } public void sanitize(final File in, File out) { out.getParentFile().mkdirs(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(out))) { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(in)))) { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(new FileInputStream(in)))) { String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { @@ -90,7 +119,6 @@ public void sanitize(final File in, File out) { } catch (IOException e) { throw new RuntimeException(e); } - } public interface SanitizeFunction { @@ -119,7 +147,7 @@ public List map(List stack) { } } - private static abstract class FrameWiseSanitizeFunction implements SanitizeFunction { + private abstract static class FrameWiseSanitizeFunction implements SanitizeFunction { @Override public final List map(List stack) { List result = new ArrayList<>(stack.size()); diff --git a/src/main/java/org/gradle/profiler/flamegraph/FlameGraphTool.java b/src/main/java/org/gradle/profiler/flamegraph/FlameGraphTool.java index 9f1c6bc6..5b858b07 100644 --- a/src/main/java/org/gradle/profiler/flamegraph/FlameGraphTool.java +++ b/src/main/java/org/gradle/profiler/flamegraph/FlameGraphTool.java @@ -11,14 +11,13 @@ import java.util.Arrays; import java.util.List; -/** - * Generates flame graphs from collapsed stacks. - */ +/** Generates flame graphs from collapsed stacks. */ public class FlameGraphTool { private final File flamegraphScript; private static File createScript(String scriptName) { - try (InputStream stream = FlameGraphTool.class.getResource(scriptName + ".pl").openStream()) { + try (InputStream stream = + FlameGraphTool.class.getResource(scriptName + ".pl").openStream()) { File script = File.createTempFile(scriptName, ".pl"); Files.copy(stream, script.toPath(), StandardCopyOption.REPLACE_EXISTING); script.deleteOnExit(); @@ -59,5 +58,4 @@ public void generateFlameGraph(File stacks, File flames, List args) { public void generateFlameGraph(File stacks, File flames, String... args) { generateFlameGraph(stacks, flames, Arrays.asList(args)); } - } diff --git a/src/main/java/org/gradle/profiler/heapdump/HeapDumpProfiler.java b/src/main/java/org/gradle/profiler/heapdump/HeapDumpProfiler.java index 8e48be2b..1e068669 100644 --- a/src/main/java/org/gradle/profiler/heapdump/HeapDumpProfiler.java +++ b/src/main/java/org/gradle/profiler/heapdump/HeapDumpProfiler.java @@ -15,8 +15,14 @@ public GradleArgsCalculator newGradleArgsCalculator(ScenarioSettings settings) { return new GradleInstrumentation() { @Override protected void generateInitScriptBody(PrintWriter writer) { - File baseName = new File(settings.getScenario().getOutputDir(), settings.getScenario().getProfileName()); - writer.println("new org.gradle.trace.heapdump.HeapDump(gradle, new File(new URI('" + baseName.toURI() + "')))"); + File baseName = + new File( + settings.getScenario().getOutputDir(), + settings.getScenario().getProfileName()); + writer.println( + "new org.gradle.trace.heapdump.HeapDump(gradle, new File(new URI('" + + baseName.toURI() + + "')))"); } }; } diff --git a/src/main/java/org/gradle/profiler/instrument/GradleInstrumentation.java b/src/main/java/org/gradle/profiler/instrument/GradleInstrumentation.java index eaf3dc67..6f8478f8 100644 --- a/src/main/java/org/gradle/profiler/instrument/GradleInstrumentation.java +++ b/src/main/java/org/gradle/profiler/instrument/GradleInstrumentation.java @@ -30,24 +30,34 @@ private void maybeGenerate() { File buildOpJar = unpackPlugin("build-operations"); File chromeTraceJar = unpackPlugin("chrome-trace"); File heapDumpJar = unpackPlugin("heap-dump"); - initScript = new GeneratedInitScript() { - @Override - public void writeContents(final PrintWriter writer) { - writer.write("initscript {\n"); - writer.write(" dependencies {\n"); - writer.write(" classpath files('" + buildOpJar.toURI() + "', '" + chromeTraceJar.toURI() + "', '" + heapDumpJar.toURI() + "')\n"); - writer.write(" }\n"); - writer.write("}\n"); - writer.write("\n"); - generateInitScriptBody(writer); - } - }; + initScript = + new GeneratedInitScript() { + @Override + public void writeContents(final PrintWriter writer) { + writer.write("initscript {\n"); + writer.write(" dependencies {\n"); + writer.write( + " classpath files('" + + buildOpJar.toURI() + + "', '" + + chromeTraceJar.toURI() + + "', '" + + heapDumpJar.toURI() + + "')\n"); + writer.write(" }\n"); + writer.write("}\n"); + writer.write("\n"); + generateInitScriptBody(writer); + } + }; } public static File unpackPlugin(String jarName) { try { File pluginJar = File.createTempFile(jarName, "jar").getCanonicalFile(); - try (InputStream inputStream = GradleInstrumentation.class.getResourceAsStream("/META-INF/jars/" + jarName + ".jar")) { + try (InputStream inputStream = + GradleInstrumentation.class.getResourceAsStream( + "/META-INF/jars/" + jarName + ".jar")) { Files.copy(inputStream, pluginJar.toPath(), StandardCopyOption.REPLACE_EXISTING); } pluginJar.deleteOnExit(); diff --git a/src/main/java/org/gradle/profiler/instrument/PidInstrumentation.java b/src/main/java/org/gradle/profiler/instrument/PidInstrumentation.java index a69bd1c2..23e4944d 100644 --- a/src/main/java/org/gradle/profiler/instrument/PidInstrumentation.java +++ b/src/main/java/org/gradle/profiler/instrument/PidInstrumentation.java @@ -12,7 +12,10 @@ public PidInstrumentation() throws IOException { @Override protected void generateInitScriptBody(PrintWriter writer) { - writer.println("org.gradle.trace.pid.PidCollector.collect(gradle, new File(new URI('" + pidFile.toURI() + "')))"); + writer.println( + "org.gradle.trace.pid.PidCollector.collect(gradle, new File(new URI('" + + pidFile.toURI() + + "')))"); } public String getPidForLastBuild() { diff --git a/src/main/java/org/gradle/profiler/jfr/JFRControl.java b/src/main/java/org/gradle/profiler/jfr/JFRControl.java index ae270624..cfe743f9 100644 --- a/src/main/java/org/gradle/profiler/jfr/JFRControl.java +++ b/src/main/java/org/gradle/profiler/jfr/JFRControl.java @@ -29,8 +29,7 @@ public void stopRecording(String pid) throws IOException, InterruptedException { } @Override - public void captureSnapshot(String pid) { - } + public void captureSnapshot(String pid) {} @Override public void stopSession() throws IOException, InterruptedException { diff --git a/src/main/java/org/gradle/profiler/jfr/JFRJvmArgsCalculator.java b/src/main/java/org/gradle/profiler/jfr/JFRJvmArgsCalculator.java index a618febf..f997f381 100644 --- a/src/main/java/org/gradle/profiler/jfr/JFRJvmArgsCalculator.java +++ b/src/main/java/org/gradle/profiler/jfr/JFRJvmArgsCalculator.java @@ -13,7 +13,8 @@ public class JFRJvmArgsCalculator implements JvmArgsCalculator { private final boolean captureOnExit; private final File outputFile; - public JFRJvmArgsCalculator(JFRArgs args, boolean profileOnStart, boolean captureOnExit, File outputFile) { + public JFRJvmArgsCalculator( + JFRArgs args, boolean profileOnStart, boolean captureOnExit, File outputFile) { this.args = args; this.profileOnStart = profileOnStart; this.captureOnExit = captureOnExit; @@ -24,7 +25,8 @@ public JFRJvmArgsCalculator(JFRArgs args, boolean profileOnStart, boolean captur public void calculateJvmArgs(List jvmArgs) { if (!JavaVersion.current().isJava11Compatible()) { if (!isOracleVm()) { - throw new IllegalArgumentException("JFR is only supported on OpenJDK since Java 11 and Oracle JDK since Java 7"); + throw new IllegalArgumentException( + "JFR is only supported on OpenJDK since Java 11 and Oracle JDK since Java 7"); } jvmArgs.add("-XX:+UnlockCommercialFeatures"); } @@ -32,14 +34,16 @@ public void calculateJvmArgs(List jvmArgs) { jvmArgs.add("-XX:+UnlockDiagnosticVMOptions"); jvmArgs.add("-XX:+DebugNonSafepoints"); - StringBuilder flightRecorderOptions = new StringBuilder("-XX:FlightRecorderOptions=stackdepth=1024"); + StringBuilder flightRecorderOptions = + new StringBuilder("-XX:FlightRecorderOptions=stackdepth=1024"); if (profileOnStart) { jvmArgs.add("-XX:StartFlightRecording=name=profile,settings=" + args.getJfrSettings()); if (captureOnExit) { - flightRecorderOptions.append(",defaultrecording=true,dumponexit=true") - .append(",dumponexitpath=") - .append(outputFile.getParentFile().getAbsolutePath()); + flightRecorderOptions + .append(",defaultrecording=true,dumponexit=true") + .append(",dumponexitpath=") + .append(outputFile.getParentFile().getAbsolutePath()); } } diff --git a/src/main/java/org/gradle/profiler/jfr/JcmdRunner.java b/src/main/java/org/gradle/profiler/jfr/JcmdRunner.java index 7e59056b..99deab58 100644 --- a/src/main/java/org/gradle/profiler/jfr/JcmdRunner.java +++ b/src/main/java/org/gradle/profiler/jfr/JcmdRunner.java @@ -18,7 +18,10 @@ public JcmdRunner() { jcmd = new File(javaHome.getParentFile(), jcmdPath()); } if (!jcmd.isFile()) { - throw new RuntimeException("Could not find 'jcmd' executable for Java home directory " + javaHome + ". Make sure your JAVA_HOME variable points to a JDK."); + throw new RuntimeException( + "Could not find 'jcmd' executable for Java home directory " + + javaHome + + ". Make sure your JAVA_HOME variable points to a JDK."); } this.jcmd = jcmd; } @@ -34,5 +37,4 @@ public void run(String pid, String... command) { commandLine.addAll(Arrays.asList(command)); new CommandExec().run(commandLine); } - } diff --git a/src/main/java/org/gradle/profiler/jfr/JfrFlameGraphGenerator.java b/src/main/java/org/gradle/profiler/jfr/JfrFlameGraphGenerator.java index f51baf87..ea4948bf 100644 --- a/src/main/java/org/gradle/profiler/jfr/JfrFlameGraphGenerator.java +++ b/src/main/java/org/gradle/profiler/jfr/JfrFlameGraphGenerator.java @@ -20,8 +20,8 @@ /** * Generates flame graphs based on JFR recordings. - *

- * TODO create flame graph diffs between profiled versions + * + *

TODO create flame graph diffs between profiled versions */ class JfrFlameGraphGenerator { private JfrToStacksConverter stacksConverter = new JfrToStacksConverter(); @@ -32,15 +32,20 @@ public void generateGraphs(File jfrFile) { return; } - List recordings = Stream.of( - requireNonNull(jfrFile.getParentFile().listFiles((dir, name) -> name.endsWith(".jfr"))) - ).map(file -> { - try { - return JfrLoaderToolkit.loadEvents(file); - } catch (IOException | CouldNotLoadRecordingException e) { - throw new RuntimeException(e); - } - }).collect(Collectors.toList()); + List recordings = + Stream.of( + requireNonNull( + jfrFile.getParentFile() + .listFiles((dir, name) -> name.endsWith(".jfr")))) + .map( + file -> { + try { + return JfrLoaderToolkit.loadEvents(file); + } catch (IOException | CouldNotLoadRecordingException e) { + throw new RuntimeException(e); + } + }) + .collect(Collectors.toList()); try { generateGraphs(jfrFile, recordings); @@ -60,9 +65,14 @@ private void generateGraphs(File jfrFile, List recordings) thro } } - private File generateStacks(File baseDir, List recordings, EventType type, DetailLevel level) throws IOException { + private File generateStacks( + File baseDir, List recordings, EventType type, DetailLevel level) + throws IOException { File stacks = File.createTempFile("stacks", ".txt"); - stacksConverter.convertToStacks(recordings, stacks, new Options(type, level.isShowArguments(), level.isShowLineNumbers())); + stacksConverter.convertToStacks( + recordings, + stacks, + new Options(type, level.isShowArguments(), level.isShowLineNumbers())); File sanitizedStacks = stacksFileName(baseDir, type, level); level.getSanitizer().sanitize(stacks, sanitizedStacks); stacks.delete(); @@ -80,7 +90,12 @@ private void generateFlameGraph(File stacks, EventType type, DetailLevel level) File flames = new File(stacks.getParentFile(), "flames.svg"); List options = new ArrayList<>(); options.addAll(level.getFlameGraphOptions()); - options.addAll(Arrays.asList("--title", type.getDisplayName() + " Flame Graph", "--countname", type.getUnitOfMeasure())); + options.addAll( + Arrays.asList( + "--title", + type.getDisplayName() + " Flame Graph", + "--countname", + type.getUnitOfMeasure())); flameGraphGenerator.generateFlameGraph(stacks, flames, options); } @@ -91,25 +106,35 @@ private void generateIcicleGraph(File stacks, EventType type, DetailLevel level) File icicles = new File(stacks.getParentFile(), "icicles.svg"); List options = new ArrayList<>(); options.addAll(level.getIcicleGraphOptions()); - options.addAll(Arrays.asList("--title", type.getDisplayName() + " Icicle Graph", "--countname", type.getUnitOfMeasure(), "--reverse", "--invert", "--colors", "aqua")); + options.addAll( + Arrays.asList( + "--title", + type.getDisplayName() + " Icicle Graph", + "--countname", + type.getUnitOfMeasure(), + "--reverse", + "--invert", + "--colors", + "aqua")); flameGraphGenerator.generateFlameGraph(stacks, icicles, options); } private enum DetailLevel { RAW( - true, - true, - Arrays.asList("--minwidth", "0.5"), - Arrays.asList("--minwidth", "1"), - new FlameGraphSanitizer(FlameGraphSanitizer.COLLAPSE_BUILD_SCRIPTS) - ), + true, + true, + Arrays.asList("--minwidth", "0.5"), + Arrays.asList("--minwidth", "1"), + new FlameGraphSanitizer(FlameGraphSanitizer.COLLAPSE_BUILD_SCRIPTS)), SIMPLIFIED( - false, - false, - Arrays.asList("--minwidth", "1"), - Arrays.asList("--minwidth", "2"), - new FlameGraphSanitizer(FlameGraphSanitizer.COLLAPSE_BUILD_SCRIPTS, FlameGraphSanitizer.COLLAPSE_GRADLE_INFRASTRUCTURE, FlameGraphSanitizer.SIMPLE_NAMES) - ); + false, + false, + Arrays.asList("--minwidth", "1"), + Arrays.asList("--minwidth", "2"), + new FlameGraphSanitizer( + FlameGraphSanitizer.COLLAPSE_BUILD_SCRIPTS, + FlameGraphSanitizer.COLLAPSE_GRADLE_INFRASTRUCTURE, + FlameGraphSanitizer.SIMPLE_NAMES)); private final boolean showArguments; private final boolean showLineNumbers; @@ -117,7 +142,12 @@ private enum DetailLevel { private List icicleGraphOptions; private FlameGraphSanitizer sanitizer; - DetailLevel(boolean showArguments, boolean showLineNumbers, List flameGraphOptions, List icicleGraphOptions, FlameGraphSanitizer sanitizer) { + DetailLevel( + boolean showArguments, + boolean showLineNumbers, + List flameGraphOptions, + List icicleGraphOptions, + FlameGraphSanitizer sanitizer) { this.showArguments = showArguments; this.showLineNumbers = showLineNumbers; this.flameGraphOptions = flameGraphOptions; @@ -144,6 +174,5 @@ public List getIcicleGraphOptions() { public FlameGraphSanitizer getSanitizer() { return sanitizer; } - } } diff --git a/src/main/java/org/gradle/profiler/jfr/JfrProfiler.java b/src/main/java/org/gradle/profiler/jfr/JfrProfiler.java index 92bc92e2..f2e7eb2e 100644 --- a/src/main/java/org/gradle/profiler/jfr/JfrProfiler.java +++ b/src/main/java/org/gradle/profiler/jfr/JfrProfiler.java @@ -37,13 +37,19 @@ protected SnapshotCapturingProfilerController doNewController(ScenarioSettings s } @Override - protected JvmArgsCalculator jvmArgsWithInstrumentation(ScenarioSettings settings, boolean startRecordingOnProcessStart, boolean captureSnapshotOnProcessExit) { + protected JvmArgsCalculator jvmArgsWithInstrumentation( + ScenarioSettings settings, + boolean startRecordingOnProcessStart, + boolean captureSnapshotOnProcessExit) { File jfrFile = getJfrFile(settings); - return new JFRJvmArgsCalculator(jfrArgs, startRecordingOnProcessStart, captureSnapshotOnProcessExit, jfrFile); + return new JFRJvmArgsCalculator( + jfrArgs, startRecordingOnProcessStart, captureSnapshotOnProcessExit, jfrFile); } private File getJfrFile(ScenarioSettings settings) { - return new File(settings.getScenario().getOutputDir(), settings.getScenario().getProfileName() + PROFILE_JFR_SUFFIX); + return new File( + settings.getScenario().getOutputDir(), + settings.getScenario().getProfileName() + PROFILE_JFR_SUFFIX); } @Override diff --git a/src/main/java/org/gradle/profiler/jfr/JfrProfilerFactory.java b/src/main/java/org/gradle/profiler/jfr/JfrProfilerFactory.java index 94e4084a..7f5c8902 100644 --- a/src/main/java/org/gradle/profiler/jfr/JfrProfilerFactory.java +++ b/src/main/java/org/gradle/profiler/jfr/JfrProfilerFactory.java @@ -19,7 +19,8 @@ public class JfrProfilerFactory extends ProfilerFactory { private static File createDefaultConfig() { try { File jfcFile = File.createTempFile("gradle", ".jfc"); - String jfcTemplateName = JavaVersion.current().isJava9Compatible() ? "gradle-java9.jfc" : "gradle.jfc"; + String jfcTemplateName = + JavaVersion.current().isJava9Compatible() ? "gradle-java9.jfc" : "gradle.jfc"; URL jfcResource = JfrProfiler.class.getResource(jfcTemplateName); try (InputStream stream = jfcResource.openStream()) { Files.copy(stream, jfcFile.toPath(), StandardCopyOption.REPLACE_EXISTING); @@ -33,10 +34,12 @@ private static File createDefaultConfig() { @Override public void addOptions(final OptionParser parser) { - parser.accepts("jfr-settings", "JFR settings - Either a .jfc file or the name of a template known to your JFR installation") - .availableIf("profile") - .withOptionalArg() - .defaultsTo(defaultConfig.getAbsolutePath()); + parser.accepts( + "jfr-settings", + "JFR settings - Either a .jfc file or the name of a template known to your JFR installation") + .availableIf("profile") + .withOptionalArg() + .defaultsTo(defaultConfig.getAbsolutePath()); } @Override diff --git a/src/main/java/org/gradle/profiler/jfr/JfrToStacksConverter.java b/src/main/java/org/gradle/profiler/jfr/JfrToStacksConverter.java index c34c796d..2f392d44 100644 --- a/src/main/java/org/gradle/profiler/jfr/JfrToStacksConverter.java +++ b/src/main/java/org/gradle/profiler/jfr/JfrToStacksConverter.java @@ -33,11 +33,10 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -/** - * Converts JFR recordings to the collapsed stacks format used by the FlameGraph tool. - */ +/** Converts JFR recordings to the collapsed stacks format used by the FlameGraph tool. */ class JfrToStacksConverter { - public void convertToStacks(List recordings, File targetFile, Options options) { + public void convertToStacks( + List recordings, File targetFile, Options options) { Map foldedStacks = foldStacks(recordings, options); writeFoldedStacks(foldedStacks, targetFile); } @@ -45,17 +44,18 @@ public void convertToStacks(List recordings, File targetFile, O private Map foldStacks(List recordings, Options options) { StackFolder folder = new StackFolder(options); recordings.stream() - .flatMap(recording -> StreamSupport.stream(recording.spliterator(), false)) - .flatMap(eventStream -> StreamSupport.stream(eventStream.spliterator(), false)) - .filter(options.eventType::matches) - .filter(event -> getStackTrace(event) != null) - .forEach(folder); + .flatMap(recording -> StreamSupport.stream(recording.spliterator(), false)) + .flatMap(eventStream -> StreamSupport.stream(eventStream.spliterator(), false)) + .filter(options.eventType::matches) + .filter(event -> getStackTrace(event) != null) + .forEach(folder); return folder.getFoldedStacks(); } private void writeFoldedStacks(Map foldedStacks, File targetFile) { targetFile.getParentFile().mkdirs(); - try (BufferedWriter writer = Files.newBufferedWriter(targetFile.toPath(), StandardCharsets.UTF_8)) { + try (BufferedWriter writer = + Files.newBufferedWriter(targetFile.toPath(), StandardCharsets.UTF_8)) { for (Map.Entry entry : foldedStacks.entrySet()) { writer.write(String.format("%s %d%n", entry.getKey(), entry.getValue())); } @@ -65,7 +65,9 @@ private void writeFoldedStacks(Map foldedStacks, File targetFile) } private static IMCStackTrace getStackTrace(IItem event) { - return ItemToolkit.getItemType(event).getAccessor(JfrAttributes.EVENT_STACKTRACE.getKey()).getMember(event); + return ItemToolkit.getItemType(event) + .getAccessor(JfrAttributes.EVENT_STACKTRACE.getKey()) + .getMember(event); } private static class StackFolder implements Consumer { @@ -93,22 +95,23 @@ private String toStack(IItem event) { IMCStackTrace stackTrace = getStackTrace(event); List reverseStacks = new ArrayList<>(stackTrace.getFrames()); Collections.reverse(reverseStacks); - return reverseStacks.stream() - .map(this::frameName) - .collect(Collectors.joining(";")); + return reverseStacks.stream().map(this::frameName).collect(Collectors.joining(";")); } private String frameName(IMCFrame frame) { return StacktraceFormatToolkit.formatFrame( - frame, - new FrameSeparator(options.isShowLineNumbers() ? FrameCategorization.LINE : FrameCategorization.METHOD, false), - false, - false, - true, - true, - options.isShowArguments(), - true - ); + frame, + new FrameSeparator( + options.isShowLineNumbers() + ? FrameCategorization.LINE + : FrameCategorization.METHOD, + false), + false, + false, + true, + true, + options.isShowArguments(), + true); } private long getValue(IItem event) { @@ -145,11 +148,35 @@ public boolean isShowLineNumbers() { } public enum EventType { - - CPU("cpu", "CPU", "samples", ValueField.COUNT, "Method Profiling Sample", "Method Profiling Sample Native"), - ALLOCATION("allocation", "Allocation size", "kB", ValueField.ALLOCATION_SIZE, "Allocation in new TLAB", "Allocation outside TLAB"), - MONITOR_BLOCKED("monitor-blocked", "Java Monitor Blocked", "ms", ValueField.DURATION, "Java Monitor Blocked"), - IO("io", "File and Socket IO", "ms", ValueField.DURATION, "File Read", "File Write", "Socket Read", "Socket Write"); + CPU( + "cpu", + "CPU", + "samples", + ValueField.COUNT, + "Method Profiling Sample", + "Method Profiling Sample Native"), + ALLOCATION( + "allocation", + "Allocation size", + "kB", + ValueField.ALLOCATION_SIZE, + "Allocation in new TLAB", + "Allocation outside TLAB"), + MONITOR_BLOCKED( + "monitor-blocked", + "Java Monitor Blocked", + "ms", + ValueField.DURATION, + "Java Monitor Blocked"), + IO( + "io", + "File and Socket IO", + "ms", + ValueField.DURATION, + "File Read", + "File Write", + "Socket Read", + "Socket Write"); private final String id; private final String displayName; @@ -157,7 +184,12 @@ public enum EventType { private final ValueField valueField; private final Set eventNames; - EventType(String id, String displayName, String unitOfMeasure, ValueField valueField, String... eventNames) { + EventType( + String id, + String displayName, + String unitOfMeasure, + ValueField valueField, + String... eventNames) { this.id = id; this.displayName = displayName; this.unitOfMeasure = unitOfMeasure; @@ -196,10 +228,13 @@ public long getValue(IItem event) { @Override public long getValue(IItem event) { IType itemType = ItemToolkit.getItemType(event); - IMemberAccessor duration = itemType.getAccessor(JfrAttributes.DURATION.getKey()); + IMemberAccessor duration = + itemType.getAccessor(JfrAttributes.DURATION.getKey()); if (duration == null) { - IMemberAccessor startTime = itemType.getAccessor(JfrAttributes.START_TIME.getKey()); - IMemberAccessor endTime = itemType.getAccessor(JfrAttributes.END_TIME.getKey()); + IMemberAccessor startTime = + itemType.getAccessor(JfrAttributes.START_TIME.getKey()); + IMemberAccessor endTime = + itemType.getAccessor(JfrAttributes.END_TIME.getKey()); duration = MemberAccessorToolkit.difference(endTime, startTime); } return duration.getMember(event).in(UnitLookup.MILLISECOND).longValue(); @@ -209,13 +244,14 @@ public long getValue(IItem event) { @Override public long getValue(IItem event) { IType itemType = ItemToolkit.getItemType(event); - IMemberAccessor accessor = itemType.getAccessor(JdkAttributes.TLAB_SIZE.getKey()); + IMemberAccessor accessor = + itemType.getAccessor(JdkAttributes.TLAB_SIZE.getKey()); if (accessor == null) { accessor = itemType.getAccessor(JdkAttributes.ALLOCATION_SIZE.getKey()); } return accessor.getMember(event) - .in(UnitLookup.MEMORY.getUnit(BinaryPrefix.KIBI)) - .longValue(); + .in(UnitLookup.MEMORY.getUnit(BinaryPrefix.KIBI)) + .longValue(); } }; diff --git a/src/main/java/org/gradle/profiler/jprofiler/JProfiler.java b/src/main/java/org/gradle/profiler/jprofiler/JProfiler.java index 021fb85f..a66dcd34 100644 --- a/src/main/java/org/gradle/profiler/jprofiler/JProfiler.java +++ b/src/main/java/org/gradle/profiler/jprofiler/JProfiler.java @@ -26,7 +26,7 @@ public static String getSnapshotPath(ScenarioSettings settings) { int i = 0; File snapshotFile; do { - snapshotFile = new File(outputDir, snapshotName + ( i == 0 ? "" : ("_" + i)) + ".jps"); + snapshotFile = new File(outputDir, snapshotName + (i == 0 ? "" : ("_" + i)) + ".jps"); ++i; } while (snapshotFile.exists()); return snapshotFile.getAbsolutePath(); diff --git a/src/main/java/org/gradle/profiler/jprofiler/JProfilerConfig.java b/src/main/java/org/gradle/profiler/jprofiler/JProfilerConfig.java index dcf6ca8d..1dd00343 100644 --- a/src/main/java/org/gradle/profiler/jprofiler/JProfilerConfig.java +++ b/src/main/java/org/gradle/profiler/jprofiler/JProfilerConfig.java @@ -17,7 +17,15 @@ public class JProfilerConfig { private int port; - public JProfilerConfig(String homeDir, String config, String sessionId, String configFile, boolean recordAlloc, boolean recordMonitors, boolean heapDump, List recordedProbeSpecs) { + public JProfilerConfig( + String homeDir, + String config, + String sessionId, + String configFile, + boolean recordAlloc, + boolean recordMonitors, + boolean heapDump, + List recordedProbeSpecs) { this.homeDir = homeDir; this.sessionId = sessionId; this.configFile = configFile; diff --git a/src/main/java/org/gradle/profiler/jprofiler/JProfilerConfigFileTransformer.java b/src/main/java/org/gradle/profiler/jprofiler/JProfilerConfigFileTransformer.java index 93b592c1..642e5652 100644 --- a/src/main/java/org/gradle/profiler/jprofiler/JProfilerConfigFileTransformer.java +++ b/src/main/java/org/gradle/profiler/jprofiler/JProfilerConfigFileTransformer.java @@ -9,6 +9,7 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; + import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -18,13 +19,21 @@ public class JProfilerConfigFileTransformer { - public static File transform(File configFile, String id, JProfilerConfig jProfilerConfig, String snapshotPath, boolean captureOnExit) { + public static File transform( + File configFile, + String id, + JProfilerConfig jProfilerConfig, + String snapshotPath, + boolean captureOnExit) { try { File transformedConfigFile = File.createTempFile("jprofiler", ".xml"); transformedConfigFile.deleteOnExit(); File probesFile = createProbesDocument(jProfilerConfig); - URL resource = JProfilerConfigFileTransformer.class.getResource("/jprofiler/transform.xsl"); - Templates template = TransformerFactory.newInstance().newTemplates(new StreamSource(resource.openStream())); + URL resource = + JProfilerConfigFileTransformer.class.getResource("/jprofiler/transform.xsl"); + Templates template = + TransformerFactory.newInstance() + .newTemplates(new StreamSource(resource.openStream())); Source source = new StreamSource(new FileInputStream(configFile)); Result result = new StreamResult(new FileOutputStream(transformedConfigFile)); Transformer transformer = template.newTransformer(); @@ -45,7 +54,8 @@ public static File transform(File configFile, String id, JProfilerConfig jProfil } } - private static File createProbesDocument(JProfilerConfig jProfilerConfig) throws ParserConfigurationException, TransformerException, IOException { + private static File createProbesDocument(JProfilerConfig jProfilerConfig) + throws ParserConfigurationException, TransformerException, IOException { File probesFile = File.createTempFile("jprofiler", ".xml"); probesFile.deleteOnExit(); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); @@ -53,8 +63,14 @@ private static File createProbesDocument(JProfilerConfig jProfilerConfig) throws for (String probeName : jProfilerConfig.getRecordedProbes()) { Element probeElement = document.createElement("probe"); probeElement.setAttribute("name", probeName); - probeElement.setAttribute("events", String.valueOf(jProfilerConfig.getProbesWithEventRecording().contains(probeName))); - probeElement.setAttribute("recordSpecial", String.valueOf(jProfilerConfig.getProbesWithSpecialRecording().contains(probeName))); + probeElement.setAttribute( + "events", + String.valueOf( + jProfilerConfig.getProbesWithEventRecording().contains(probeName))); + probeElement.setAttribute( + "recordSpecial", + String.valueOf( + jProfilerConfig.getProbesWithSpecialRecording().contains(probeName))); probesElement.appendChild(probeElement); } document.appendChild(probesElement); @@ -63,5 +79,4 @@ private static File createProbesDocument(JProfilerConfig jProfilerConfig) throws TransformerFactory.newInstance().newTransformer().transform(source, result); return probesFile; } - } diff --git a/src/main/java/org/gradle/profiler/jprofiler/JProfilerController.java b/src/main/java/org/gradle/profiler/jprofiler/JProfilerController.java index 094dcace..6b090459 100644 --- a/src/main/java/org/gradle/profiler/jprofiler/JProfilerController.java +++ b/src/main/java/org/gradle/profiler/jprofiler/JProfilerController.java @@ -8,11 +8,13 @@ import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; + import java.io.IOException; import java.util.Arrays; import java.util.Collections; -public class JProfilerController implements InstrumentingProfiler.SnapshotCapturingProfilerController { +public class JProfilerController + implements InstrumentingProfiler.SnapshotCapturingProfilerController { private final JProfilerConfig jProfilerConfig; private final ScenarioSettings settings; @@ -36,8 +38,10 @@ public void startRecording(String pid) throws IOException, InterruptedException invoke("startMonitorRecording"); } for (String probeName : jProfilerConfig.getRecordedProbes()) { - boolean eventRecording = jProfilerConfig.getProbesWithEventRecording().contains(probeName); - boolean specialRecording = jProfilerConfig.getProbesWithSpecialRecording().contains(probeName); + boolean eventRecording = + jProfilerConfig.getProbesWithEventRecording().contains(probeName); + boolean specialRecording = + jProfilerConfig.getProbesWithSpecialRecording().contains(probeName); invoke("startProbeRecording", probeName, eventRecording, specialRecording); } if (jProfilerConfig.isHeapDump() && hasOperation("markHeap")) { // available in JProfiler 10 @@ -79,8 +83,13 @@ private String getSnapshotPath() { private void ensureConnected() throws IOException { if (connector == null) { try { - JMXServiceURL jmxUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + jProfilerConfig.getPort() + "/jmxrmi"); - JMXConnector newConnector = JMXConnectorFactory.newJMXConnector(jmxUrl, Collections.emptyMap()); + JMXServiceURL jmxUrl = + new JMXServiceURL( + "service:jmx:rmi:///jndi/rmi://localhost:" + + jProfilerConfig.getPort() + + "/jmxrmi"); + JMXConnector newConnector = + JMXConnectorFactory.newJMXConnector(jmxUrl, Collections.emptyMap()); newConnector.connect(); connection = newConnector.getMBeanServerConnection(); objectName = new ObjectName("com.jprofiler.api.agent.mbean:type=RemoteController"); @@ -108,11 +117,12 @@ private void closeConnection() { private void invoke(String operationName, Object... parameterValues) throws IOException { ensureConnected(); - String[] parameterTypes = Arrays.stream(parameterValues) - .map(Object::getClass) - .map(this::replaceWrapperWithPrimitive) - .map(Class::getName) - .toArray(String[]::new); + String[] parameterTypes = + Arrays.stream(parameterValues) + .map(Object::getClass) + .map(this::replaceWrapperWithPrimitive) + .map(Class::getName) + .toArray(String[]::new); try { connection.invoke(objectName, operationName, parameterValues, parameterTypes); } catch (InstanceNotFoundException | MBeanException | ReflectionException e) { diff --git a/src/main/java/org/gradle/profiler/jprofiler/JProfilerJvmArgsCalculator.java b/src/main/java/org/gradle/profiler/jprofiler/JProfilerJvmArgsCalculator.java index b1d67d31..b2d15aa2 100644 --- a/src/main/java/org/gradle/profiler/jprofiler/JProfilerJvmArgsCalculator.java +++ b/src/main/java/org/gradle/profiler/jprofiler/JProfilerJvmArgsCalculator.java @@ -22,7 +22,11 @@ public class JProfilerJvmArgsCalculator implements JvmArgsCalculator { private final boolean startRecordingOnProcessStart; private final boolean captureSnapshotOnProcessExit; - public JProfilerJvmArgsCalculator(JProfilerConfig jProfilerConfig, ScenarioSettings settings, boolean startRecordingOnProcessStart, boolean captureSnapshotOnProcessExit) { + public JProfilerJvmArgsCalculator( + JProfilerConfig jProfilerConfig, + ScenarioSettings settings, + boolean startRecordingOnProcessStart, + boolean captureSnapshotOnProcessExit) { this.jProfilerConfig = jProfilerConfig; this.settings = settings; this.startRecordingOnProcessStart = startRecordingOnProcessStart; @@ -39,7 +43,10 @@ public void calculateJvmArgs(List jvmArgs) { private String getAgentPathParameter(int port) { File jprofilerDir = getJProfilerDir(); if (!jprofilerDir.exists()) { - throw new RuntimeException("JProfiler home directory " + jprofilerDir + " does not exist, please specify a different directory with --jprofiler-home"); + throw new RuntimeException( + "JProfiler home directory " + + jprofilerDir + + " does not exist, please specify a different directory with --jprofiler-home"); } boolean is64Bit = System.getProperty("sun.arch.data.model", "64").equals("64"); @@ -69,7 +76,8 @@ private String getAgentPathParameter(int port) { builder.append(File.separator); builder.append("libjprofilerti.so"); } else { - throw new RuntimeException("Currently only Windows, macOS and Linux-x86 are detected for the native JProfiler agent library"); + throw new RuntimeException( + "Currently only Windows, macOS and Linux-x86 are detected for the native JProfiler agent library"); } builder.append("=offline,"); @@ -98,7 +106,12 @@ private String getAgentPathParameter(int port) { private File transformConfigFile(File configFile, String id) { if (startRecordingOnProcessStart) { - return JProfilerConfigFileTransformer.transform(configFile, id, jProfilerConfig, JProfiler.getSnapshotPath(settings), captureSnapshotOnProcessExit); + return JProfilerConfigFileTransformer.transform( + configFile, + id, + jProfilerConfig, + JProfiler.getSnapshotPath(settings), + captureSnapshotOnProcessExit); } else { return configFile; } diff --git a/src/main/java/org/gradle/profiler/jprofiler/JProfilerProfiler.java b/src/main/java/org/gradle/profiler/jprofiler/JProfilerProfiler.java index 3c4ad27a..982f5884 100644 --- a/src/main/java/org/gradle/profiler/jprofiler/JProfilerProfiler.java +++ b/src/main/java/org/gradle/profiler/jprofiler/JProfilerProfiler.java @@ -37,7 +37,14 @@ protected SnapshotCapturingProfilerController doNewController(ScenarioSettings s } @Override - protected JvmArgsCalculator jvmArgsWithInstrumentation(ScenarioSettings settings, boolean startRecordingOnProcessStart, boolean captureSnapshotOnProcessExit) { - return new JProfilerJvmArgsCalculator(jProfilerConfig, settings, startRecordingOnProcessStart, captureSnapshotOnProcessExit); + protected JvmArgsCalculator jvmArgsWithInstrumentation( + ScenarioSettings settings, + boolean startRecordingOnProcessStart, + boolean captureSnapshotOnProcessExit) { + return new JProfilerJvmArgsCalculator( + jProfilerConfig, + settings, + startRecordingOnProcessStart, + captureSnapshotOnProcessExit); } } diff --git a/src/main/java/org/gradle/profiler/jprofiler/JProfilerProfilerFactory.java b/src/main/java/org/gradle/profiler/jprofiler/JProfilerProfilerFactory.java index a72d5944..9587407e 100644 --- a/src/main/java/org/gradle/profiler/jprofiler/JProfilerProfilerFactory.java +++ b/src/main/java/org/gradle/profiler/jprofiler/JProfilerProfilerFactory.java @@ -19,22 +19,50 @@ public class JProfilerProfilerFactory extends ProfilerFactory { @Override public void addOptions(OptionParser parser) { - homeDir = parser.accepts("jprofiler-home", "JProfiler installation directory").availableIf("profile") - .withOptionalArg().ofType(String.class).defaultsTo(JProfiler.getDefaultHomeDir()); - configOption = parser.accepts("jprofiler-config", "JProfiler built-in configuration name (sampling|sampling-all|instrumentation)") - .availableIf("profile").withOptionalArg().ofType(String.class).defaultsTo("sampling"); - sessionIdOption = parser.accepts("jprofiler-session-id", "Use session with this id from the JProfiler installation instead of using the built-in config") - .availableUnless("jprofiler-config").withRequiredArg().ofType(String.class); - configFileOption = parser.accepts("jprofiler-config-file", "Use another config file for --jprofiler-session-id instead of the global config file") - .availableIf("jprofiler-session-id").withRequiredArg().ofType(String.class); - allocOption = parser.accepts("jprofiler-alloc", "Record allocations") - .availableIf("profile"); - monitorsOption = parser.accepts("jprofiler-monitors", "Record monitor usage") - .availableIf("profile"); - heapDumpOption = parser.accepts("jprofiler-heapdump", "Trigger heap dump after a build") - .availableIf("profile"); - probesOption = parser.accepts("jprofiler-probes", "Record probes (builtin.FileProbe|builtin.SocketProbe|builtin.ProcessProbe|builtin.ClassLoaderProbe|builtin.ExceptionProbe, see Controller javadoc for the full list) separated by commas, add :+events to probe name to enable event recording") - .availableIf("profile").withRequiredArg().ofType(String.class).withValuesSeparatedBy(',').defaultsTo(new String[0]); + homeDir = + parser.accepts("jprofiler-home", "JProfiler installation directory") + .availableIf("profile") + .withOptionalArg() + .ofType(String.class) + .defaultsTo(JProfiler.getDefaultHomeDir()); + configOption = + parser.accepts( + "jprofiler-config", + "JProfiler built-in configuration name (sampling|sampling-all|instrumentation)") + .availableIf("profile") + .withOptionalArg() + .ofType(String.class) + .defaultsTo("sampling"); + sessionIdOption = + parser.accepts( + "jprofiler-session-id", + "Use session with this id from the JProfiler installation instead of using the built-in config") + .availableUnless("jprofiler-config") + .withRequiredArg() + .ofType(String.class); + configFileOption = + parser.accepts( + "jprofiler-config-file", + "Use another config file for --jprofiler-session-id instead of the global config file") + .availableIf("jprofiler-session-id") + .withRequiredArg() + .ofType(String.class); + allocOption = + parser.accepts("jprofiler-alloc", "Record allocations").availableIf("profile"); + monitorsOption = + parser.accepts("jprofiler-monitors", "Record monitor usage").availableIf("profile"); + heapDumpOption = + parser.accepts("jprofiler-heapdump", "Trigger heap dump after a build") + .availableIf("profile"); + probesOption = + parser.accepts( + "jprofiler-probes", + "Record probes (builtin.FileProbe|builtin.SocketProbe|builtin.ProcessProbe|builtin.ClassLoaderProbe|builtin.ExceptionProbe, see Controller javadoc for the full list) separated by commas, add :+events to probe name to enable event recording") + .availableIf("profile") + .withRequiredArg() + .ofType(String.class) + .withValuesSeparatedBy(',') + .defaultsTo(new String[0]); } @Override @@ -44,13 +72,13 @@ public Profiler createFromOptions(OptionSet parsedOptions) { private JProfilerConfig newConfigObject(OptionSet parsedOptions) { return new JProfilerConfig( - parsedOptions.valueOf(homeDir), - parsedOptions.valueOf(configOption), - parsedOptions.valueOf(sessionIdOption), - parsedOptions.valueOf(configFileOption), - parsedOptions.has(allocOption), - parsedOptions.has(monitorsOption), - parsedOptions.has(heapDumpOption), - parsedOptions.valuesOf(probesOption)); + parsedOptions.valueOf(homeDir), + parsedOptions.valueOf(configOption), + parsedOptions.valueOf(sessionIdOption), + parsedOptions.valueOf(configFileOption), + parsedOptions.has(allocOption), + parsedOptions.has(monitorsOption), + parsedOptions.has(heapDumpOption), + parsedOptions.valuesOf(probesOption)); } } diff --git a/src/main/java/org/gradle/profiler/mutations/AbstractBuildMutatorWithoutOptionsConfigurator.java b/src/main/java/org/gradle/profiler/mutations/AbstractBuildMutatorWithoutOptionsConfigurator.java index b6d19428..b4e3f9df 100644 --- a/src/main/java/org/gradle/profiler/mutations/AbstractBuildMutatorWithoutOptionsConfigurator.java +++ b/src/main/java/org/gradle/profiler/mutations/AbstractBuildMutatorWithoutOptionsConfigurator.java @@ -4,12 +4,14 @@ import org.gradle.profiler.BuildMutator; import org.gradle.profiler.InvocationSettings; -public abstract class AbstractBuildMutatorWithoutOptionsConfigurator implements BuildMutatorConfigurator { +public abstract class AbstractBuildMutatorWithoutOptionsConfigurator + implements BuildMutatorConfigurator { abstract BuildMutator createBuildMutator(InvocationSettings settings); @Override - public BuildMutator configure(Config scenario, String scenarioName, InvocationSettings settings, String key) { + public BuildMutator configure( + Config scenario, String scenarioName, InvocationSettings settings, String key) { boolean enabled = scenario.getBoolean(key); return enabled ? createBuildMutator(settings) : BuildMutator.NOOP; } diff --git a/src/main/java/org/gradle/profiler/mutations/AbstractCacheCleanupMutator.java b/src/main/java/org/gradle/profiler/mutations/AbstractCacheCleanupMutator.java index 5b608126..d3b01a59 100644 --- a/src/main/java/org/gradle/profiler/mutations/AbstractCacheCleanupMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/AbstractCacheCleanupMutator.java @@ -7,7 +7,8 @@ public abstract class AbstractCacheCleanupMutator extends AbstractCleanupMutator private final File gradleUserHome; private final String cacheNamePrefix; - public AbstractCacheCleanupMutator(File gradleUserHome, CleanupSchedule schedule, String cacheNamePrefix) { + public AbstractCacheCleanupMutator( + File gradleUserHome, CleanupSchedule schedule, String cacheNamePrefix) { super(schedule); this.gradleUserHome = gradleUserHome; this.cacheNamePrefix = cacheNamePrefix; @@ -18,9 +19,13 @@ protected void cleanup() { System.out.println("> Cleaning " + cacheNamePrefix + " caches in " + gradleUserHome); File cachesDir = new File(gradleUserHome, "caches"); if (cachesDir.isDirectory()) { - File[] cacheDirs = cachesDir.listFiles((File file) -> file.getName().startsWith(cacheNamePrefix)); + File[] cacheDirs = + cachesDir.listFiles((File file) -> file.getName().startsWith(cacheNamePrefix)); if (cacheDirs == null) { - throw new IllegalStateException(String.format("Cannot find cache directories with prefix '%s' in %s", cacheNamePrefix, gradleUserHome)); + throw new IllegalStateException( + String.format( + "Cannot find cache directories with prefix '%s' in %s", + cacheNamePrefix, gradleUserHome)); } for (File cacheDir : cacheDirs) { if (cacheDir.isDirectory()) { diff --git a/src/main/java/org/gradle/profiler/mutations/AbstractCleanupMutator.java b/src/main/java/org/gradle/profiler/mutations/AbstractCleanupMutator.java index 06d2db1e..2f6b5b64 100644 --- a/src/main/java/org/gradle/profiler/mutations/AbstractCleanupMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/AbstractCleanupMutator.java @@ -24,7 +24,8 @@ public AbstractCleanupMutator(CleanupSchedule schedule) { @Override public void validate(BuildInvoker invoker) { if (schedule != CleanupSchedule.SCENARIO && !invoker.allowsCleanupBetweenBuilds()) { - throw new IllegalStateException(this + " is not allowed to be executed between builds with invoker " + invoker); + throw new IllegalStateException( + this + " is not allowed to be executed between builds with invoker " + invoker); } } @@ -49,7 +50,7 @@ public void beforeCleanup(BuildContext context) { } } - abstract protected void cleanup(); + protected abstract void cleanup(); protected static void delete(File f) { try { @@ -63,17 +64,24 @@ protected static void delete(File f) { } } - protected static abstract class Configurator implements BuildMutatorConfigurator { + protected abstract static class Configurator implements BuildMutatorConfigurator { @Override - public BuildMutator configure(Config scenario, String scenarioName, InvocationSettings settings, String key) { - CleanupSchedule schedule = ConfigUtil.enumValue(scenario, key, CleanupSchedule.class, null); + public BuildMutator configure( + Config scenario, String scenarioName, InvocationSettings settings, String key) { + CleanupSchedule schedule = + ConfigUtil.enumValue(scenario, key, CleanupSchedule.class, null); if (schedule == null) { throw new IllegalArgumentException("Schedule for cleanup is not specified"); } return newInstance(scenario, scenarioName, settings, key, schedule); } - protected abstract BuildMutator newInstance(Config scenario, String scenarioName, InvocationSettings settings, String key, CleanupSchedule schedule); + protected abstract BuildMutator newInstance( + Config scenario, + String scenarioName, + InvocationSettings settings, + String key, + CleanupSchedule schedule); } @Override @@ -82,6 +90,8 @@ public String toString() { } public enum CleanupSchedule { - SCENARIO, CLEANUP, BUILD + SCENARIO, + CLEANUP, + BUILD } } diff --git a/src/main/java/org/gradle/profiler/mutations/AbstractFileChangeMutator.java b/src/main/java/org/gradle/profiler/mutations/AbstractFileChangeMutator.java index 6453888c..b707e9db 100644 --- a/src/main/java/org/gradle/profiler/mutations/AbstractFileChangeMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/AbstractFileChangeMutator.java @@ -48,8 +48,7 @@ public void afterScenario(ScenarioContext context) { } @Override - public String toString() - { + public String toString() { return getClass().getSimpleName() + '(' + sourceFile + ')'; } } diff --git a/src/main/java/org/gradle/profiler/mutations/AbstractGitMutator.java b/src/main/java/org/gradle/profiler/mutations/AbstractGitMutator.java index e26a6488..a9655797 100644 --- a/src/main/java/org/gradle/profiler/mutations/AbstractGitMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/AbstractGitMutator.java @@ -6,15 +6,15 @@ import java.io.File; public abstract class AbstractGitMutator implements BuildMutator { - protected final File projectDir; + protected final File projectDir; - public AbstractGitMutator(File projectDir) { - this.projectDir = projectDir; - } + public AbstractGitMutator(File projectDir) { + this.projectDir = projectDir; + } - protected void resetGit() { - System.out.println("> Resetting Git hard"); - new CommandExec().inDir(projectDir).run("git", "reset", "--hard", "HEAD"); - new CommandExec().inDir(projectDir).run("git", "status"); - } + protected void resetGit() { + System.out.println("> Resetting Git hard"); + new CommandExec().inDir(projectDir).run("git", "reset", "--hard", "HEAD"); + new CommandExec().inDir(projectDir).run("git", "status"); + } } diff --git a/src/main/java/org/gradle/profiler/mutations/ApplyAbiChangeToKotlinSourceFileMutator.java b/src/main/java/org/gradle/profiler/mutations/ApplyAbiChangeToKotlinSourceFileMutator.java index 691d4e6e..09993ff3 100644 --- a/src/main/java/org/gradle/profiler/mutations/ApplyAbiChangeToKotlinSourceFileMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ApplyAbiChangeToKotlinSourceFileMutator.java @@ -12,8 +12,6 @@ public ApplyAbiChangeToKotlinSourceFileMutator(File sourceFile) { @Override protected void applyChangeTo(BuildContext context, StringBuilder text) { - text.append("fun _m") - .append(context.getUniqueBuildId()) - .append("() {}"); + text.append("fun _m").append(context.getUniqueBuildId()).append("() {}"); } } diff --git a/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidLayoutFileMutator.java b/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidLayoutFileMutator.java index 9aa18b16..0bb29398 100644 --- a/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidLayoutFileMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidLayoutFileMutator.java @@ -5,12 +5,13 @@ import java.io.File; /** - * This class applies a mutation to an Android layout file by adding an extra, hidden view at the bottom of the layout. - * It supports both DataBinding layouts (wrapped in tags) and traditional Android layouts. + * This class applies a mutation to an Android layout file by adding an extra, hidden view at the + * bottom of the layout. It supports both DataBinding layouts (wrapped in tags) + * and traditional Android layouts. * - * Note: This mutator does not support layouts with a single view in them - it requires a valid ViewGroup to contain the - * new view. Attempting to mutate a layout that does not have a ViewGroup as its root element will result in an - * invalid layout file. + *

Note: This mutator does not support layouts with a single view in them - it requires a valid + * ViewGroup to contain the new view. Attempting to mutate a layout that does not have a ViewGroup + * as its root element will result in an invalid layout file. */ public class ApplyChangeToAndroidLayoutFileMutator extends AbstractFileChangeMutator { public ApplyChangeToAndroidLayoutFileMutator(File sourceFile) { @@ -27,11 +28,16 @@ protected void applyChangeTo(BuildContext context, StringBuilder text) { } } - private void applyChangeToDataBindingLayout(BuildContext context, StringBuilder text, int tagEndPosition) { + private void applyChangeToDataBindingLayout( + BuildContext context, StringBuilder text, int tagEndPosition) { String substring = text.substring(0, tagEndPosition); int insertPos = substring.lastIndexOf("\n" + - "\n"; + return "\n" + + "\n"; } } diff --git a/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidManifestFileMutator.java b/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidManifestFileMutator.java index 8abafdfe..f2fc6851 100644 --- a/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidManifestFileMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidManifestFileMutator.java @@ -6,15 +6,20 @@ public class ApplyChangeToAndroidManifestFileMutator extends AbstractFileChangeMutator { public ApplyChangeToAndroidManifestFileMutator(File sourceFile) { - super( sourceFile ); + super(sourceFile); } @Override protected void applyChangeTo(BuildContext context, StringBuilder text) { int insertPos = text.lastIndexOf(""); if (insertPos < 0) { - throw new IllegalArgumentException("Cannot parse android manifest file " + sourceFile + " to apply changes"); + throw new IllegalArgumentException( + "Cannot parse android manifest file " + sourceFile + " to apply changes"); } - text.insert(insertPos, ""); + text.insert( + insertPos, + ""); } } diff --git a/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidResourceFileMutator.java b/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidResourceFileMutator.java index 74a8a968..159a19ab 100644 --- a/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidResourceFileMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ApplyChangeToAndroidResourceFileMutator.java @@ -13,8 +13,11 @@ public ApplyChangeToAndroidResourceFileMutator(File sourceFile) { protected void applyChangeTo(BuildContext context, StringBuilder text) { int insertPos = text.lastIndexOf(""); if (insertPos < 0) { - throw new IllegalArgumentException("Cannot parse source file " + sourceFile + " to apply changes"); + throw new IllegalArgumentException( + "Cannot parse source file " + sourceFile + " to apply changes"); } - text.insert(insertPos, "" + context.getUniqueBuildId() + ""); + text.insert( + insertPos, + "" + context.getUniqueBuildId() + ""); } } diff --git a/src/main/java/org/gradle/profiler/mutations/ApplyChangeToNativeSourceFileMutator.java b/src/main/java/org/gradle/profiler/mutations/ApplyChangeToNativeSourceFileMutator.java index 69a33310..3ded0130 100644 --- a/src/main/java/org/gradle/profiler/mutations/ApplyChangeToNativeSourceFileMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ApplyChangeToNativeSourceFileMutator.java @@ -8,7 +8,9 @@ public class ApplyChangeToNativeSourceFileMutator extends AbstractFileChangeMuta public ApplyChangeToNativeSourceFileMutator(File file) { super(file); - if (!sourceFile.getName().endsWith(".cpp") && !sourceFile.getName().endsWith(".h") && !sourceFile.getName().endsWith(".hpp")) { + if (!sourceFile.getName().endsWith(".cpp") + && !sourceFile.getName().endsWith(".h") + && !sourceFile.getName().endsWith(".hpp")) { throw new IllegalArgumentException("Can only modify C++ source or header files"); } } @@ -22,7 +24,8 @@ protected void applyChangeTo(BuildContext context, StringBuilder text) { } else { insertPos = text.lastIndexOf("#endif"); if (insertPos < 0) { - throw new IllegalArgumentException("Cannot parse header file " + sourceFile + " to apply changes"); + throw new IllegalArgumentException( + "Cannot parse header file " + sourceFile + " to apply changes"); } applyHeaderChangeAt(context, text, insertPos); } diff --git a/src/main/java/org/gradle/profiler/mutations/ApplyNonAbiChangeToJavaSourceFileMutator.java b/src/main/java/org/gradle/profiler/mutations/ApplyNonAbiChangeToJavaSourceFileMutator.java index c9bef1ef..bc5595c8 100644 --- a/src/main/java/org/gradle/profiler/mutations/ApplyNonAbiChangeToJavaSourceFileMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ApplyNonAbiChangeToJavaSourceFileMutator.java @@ -18,14 +18,18 @@ public ApplyNonAbiChangeToJavaSourceFileMutator(File sourceFile) { @Override protected void applyChangeTo(BuildContext context, CompilationUnit compilationUnit) { MethodDeclaration existingMethod = getExistingMethod(compilationUnit); - existingMethod.getBody() - .orElseThrow(() -> new RuntimeException("Method body not found")) - .addStatement(0, JavaParser.parseStatement("System.out.println(\"" + context.getUniqueBuildId() + "\");")); + existingMethod + .getBody() + .orElseThrow(() -> new RuntimeException("Method body not found")) + .addStatement( + 0, + JavaParser.parseStatement( + "System.out.println(\"" + context.getUniqueBuildId() + "\");")); } private MethodDeclaration getExistingMethod(CompilationUnit compilationUnit) { NodeList> types = compilationUnit.getTypes(); - if (types.isEmpty()){ + if (types.isEmpty()) { throw new IllegalArgumentException("No types to change in " + sourceFile); } TypeDeclaration type = types.get(0); diff --git a/src/main/java/org/gradle/profiler/mutations/ApplyNonAbiChangeToKotlinSourceFileMutator.java b/src/main/java/org/gradle/profiler/mutations/ApplyNonAbiChangeToKotlinSourceFileMutator.java index bdeb844a..cb0d7cc0 100644 --- a/src/main/java/org/gradle/profiler/mutations/ApplyNonAbiChangeToKotlinSourceFileMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ApplyNonAbiChangeToKotlinSourceFileMutator.java @@ -13,10 +13,10 @@ public ApplyNonAbiChangeToKotlinSourceFileMutator(File sourceFile) { @Override protected void applyChangeTo(BuildContext context, StringBuilder text) { text.append('\n') - .append("private fun _m") - .append(context.getUniqueScenarioId()) - .append("() {requireNotNull(\"") - .append(context.getUniqueBuildId()) - .append("\")}"); + .append("private fun _m") + .append(context.getUniqueScenarioId()) + .append("() {requireNotNull(\"") + .append(context.getUniqueBuildId()) + .append("\")}"); } } diff --git a/src/main/java/org/gradle/profiler/mutations/ApplyValueChangeToAndroidResourceFileMutator.java b/src/main/java/org/gradle/profiler/mutations/ApplyValueChangeToAndroidResourceFileMutator.java index 8373058a..f25ccb60 100644 --- a/src/main/java/org/gradle/profiler/mutations/ApplyValueChangeToAndroidResourceFileMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ApplyValueChangeToAndroidResourceFileMutator.java @@ -13,7 +13,8 @@ public ApplyValueChangeToAndroidResourceFileMutator(File sourceFile) { protected void applyChangeTo(BuildContext context, StringBuilder text) { int insertPos = text.lastIndexOf(""); if (insertPos < 0) { - throw new IllegalArgumentException("Cannot parse source file " + sourceFile + " to apply changes"); + throw new IllegalArgumentException( + "Cannot parse source file " + sourceFile + " to apply changes"); } text.insert(insertPos, context.getUniqueBuildId()); } diff --git a/src/main/java/org/gradle/profiler/mutations/BuildMutatorConfigurator.java b/src/main/java/org/gradle/profiler/mutations/BuildMutatorConfigurator.java index ce940fa5..61eab2f1 100644 --- a/src/main/java/org/gradle/profiler/mutations/BuildMutatorConfigurator.java +++ b/src/main/java/org/gradle/profiler/mutations/BuildMutatorConfigurator.java @@ -5,5 +5,6 @@ import org.gradle.profiler.InvocationSettings; public interface BuildMutatorConfigurator { - BuildMutator configure(Config scenario, String scenarioName, InvocationSettings settings, String key); + BuildMutator configure( + Config scenario, String scenarioName, InvocationSettings settings, String key); } diff --git a/src/main/java/org/gradle/profiler/mutations/ClearArtifactTransformCacheMutator.java b/src/main/java/org/gradle/profiler/mutations/ClearArtifactTransformCacheMutator.java index 886d8217..81ecb47c 100644 --- a/src/main/java/org/gradle/profiler/mutations/ClearArtifactTransformCacheMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ClearArtifactTransformCacheMutator.java @@ -19,7 +19,12 @@ protected void cleanupCacheDir(File cacheDir) { public static class Configurator extends AbstractCleanupMutator.Configurator { @Override - protected BuildMutator newInstance(Config scenario, String scenarioName, InvocationSettings settings, String key, CleanupSchedule schedule) { + protected BuildMutator newInstance( + Config scenario, + String scenarioName, + InvocationSettings settings, + String key, + CleanupSchedule schedule) { return new ClearArtifactTransformCacheMutator(settings.getGradleUserHome(), schedule); } } diff --git a/src/main/java/org/gradle/profiler/mutations/ClearBuildCacheMutator.java b/src/main/java/org/gradle/profiler/mutations/ClearBuildCacheMutator.java index cf00e6a4..31fff5e5 100644 --- a/src/main/java/org/gradle/profiler/mutations/ClearBuildCacheMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ClearBuildCacheMutator.java @@ -16,12 +16,20 @@ public ClearBuildCacheMutator(File gradleUserHome, CleanupSchedule schedule) { @Override protected void cleanupCacheDir(File cacheDir) { - Arrays.stream(Objects.requireNonNull(cacheDir.listFiles((file) -> file.getName().length() == 32))).forEach(AbstractCleanupMutator::delete); + Arrays.stream( + Objects.requireNonNull( + cacheDir.listFiles((file) -> file.getName().length() == 32))) + .forEach(AbstractCleanupMutator::delete); } public static class Configurator extends AbstractCleanupMutator.Configurator { @Override - protected BuildMutator newInstance(Config scenario, String scenarioName, InvocationSettings settings, String key, CleanupSchedule schedule) { + protected BuildMutator newInstance( + Config scenario, + String scenarioName, + InvocationSettings settings, + String key, + CleanupSchedule schedule) { return new ClearBuildCacheMutator(settings.getGradleUserHome(), schedule); } } diff --git a/src/main/java/org/gradle/profiler/mutations/ClearConfigurationCacheStateMutator.java b/src/main/java/org/gradle/profiler/mutations/ClearConfigurationCacheStateMutator.java index 4d1fce88..fd9ff0c9 100644 --- a/src/main/java/org/gradle/profiler/mutations/ClearConfigurationCacheStateMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ClearConfigurationCacheStateMutator.java @@ -40,7 +40,12 @@ private void cleanup(File dir) { public static class Configurator extends AbstractCleanupMutator.Configurator { @Override - protected BuildMutator newInstance(Config scenario, String scenarioName, InvocationSettings settings, String key, CleanupSchedule schedule) { + protected BuildMutator newInstance( + Config scenario, + String scenarioName, + InvocationSettings settings, + String key, + CleanupSchedule schedule) { return new ClearConfigurationCacheStateMutator(settings.getProjectDir(), schedule); } } diff --git a/src/main/java/org/gradle/profiler/mutations/ClearGradleUserHomeMutator.java b/src/main/java/org/gradle/profiler/mutations/ClearGradleUserHomeMutator.java index 61bf6b25..7ea2bc5d 100644 --- a/src/main/java/org/gradle/profiler/mutations/ClearGradleUserHomeMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ClearGradleUserHomeMutator.java @@ -19,18 +19,20 @@ public ClearGradleUserHomeMutator(File gradleUserHome, CleanupSchedule schedule) @Override protected void cleanup() { - System.out.println(String.format("> Cleaning Gradle user home: %s", gradleUserHome.getAbsolutePath())); + System.out.println( + String.format("> Cleaning Gradle user home: %s", gradleUserHome.getAbsolutePath())); if (!gradleUserHome.exists()) { - throw new IllegalArgumentException(String.format( - "Cannot delete Gradle user home directory (%s) since it does not exist", - gradleUserHome - )); + throw new IllegalArgumentException( + String.format( + "Cannot delete Gradle user home directory (%s) since it does not exist", + gradleUserHome)); } try { Files.list(gradleUserHome.toPath()) - // Don't delete the wrapper dir, since this is where the Gradle distribution we are going to run is located - .filter(path -> !path.getFileName().toString().equals("wrapper")) - .forEach(path -> delete(path.toFile())); + // Don't delete the wrapper dir, since this is where the Gradle distribution we + // are going to run is located + .filter(path -> !path.getFileName().toString().equals("wrapper")) + .forEach(path -> delete(path.toFile())); } catch (IOException e) { throw new UncheckedIOException(e); } @@ -38,7 +40,12 @@ protected void cleanup() { public static class Configurator extends AbstractCleanupMutator.Configurator { @Override - protected BuildMutator newInstance(Config scenario, String scenarioName, InvocationSettings settings, String key, CleanupSchedule schedule) { + protected BuildMutator newInstance( + Config scenario, + String scenarioName, + InvocationSettings settings, + String key, + CleanupSchedule schedule) { return new ClearGradleUserHomeMutator(settings.getGradleUserHome(), schedule); } } diff --git a/src/main/java/org/gradle/profiler/mutations/ClearJarsCacheMutator.java b/src/main/java/org/gradle/profiler/mutations/ClearJarsCacheMutator.java index 442c44f0..e22b3ff6 100644 --- a/src/main/java/org/gradle/profiler/mutations/ClearJarsCacheMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ClearJarsCacheMutator.java @@ -19,7 +19,12 @@ protected void cleanupCacheDir(File cacheDir) { public static class Configurator extends AbstractCleanupMutator.Configurator { @Override - protected BuildMutator newInstance(Config scenario, String scenarioName, InvocationSettings settings, String key, CleanupSchedule schedule) { + protected BuildMutator newInstance( + Config scenario, + String scenarioName, + InvocationSettings settings, + String key, + CleanupSchedule schedule) { return new ClearJarsCacheMutator(settings.getGradleUserHome(), schedule); } } diff --git a/src/main/java/org/gradle/profiler/mutations/ClearProjectCacheMutator.java b/src/main/java/org/gradle/profiler/mutations/ClearProjectCacheMutator.java index 2c379f66..16e33555 100644 --- a/src/main/java/org/gradle/profiler/mutations/ClearProjectCacheMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ClearProjectCacheMutator.java @@ -38,7 +38,12 @@ private void deleteGradleCache(String name, File baseDir) { public static class Configurator extends AbstractCleanupMutator.Configurator { @Override - protected BuildMutator newInstance(Config scenario, String scenarioName, InvocationSettings settings, String key, CleanupSchedule schedule) { + protected BuildMutator newInstance( + Config scenario, + String scenarioName, + InvocationSettings settings, + String key, + CleanupSchedule schedule) { return new ClearProjectCacheMutator(settings.getProjectDir(), schedule); } } diff --git a/src/main/java/org/gradle/profiler/mutations/FileChangeMutatorConfigurator.java b/src/main/java/org/gradle/profiler/mutations/FileChangeMutatorConfigurator.java index 41e5c473..b9146ac5 100644 --- a/src/main/java/org/gradle/profiler/mutations/FileChangeMutatorConfigurator.java +++ b/src/main/java/org/gradle/profiler/mutations/FileChangeMutatorConfigurator.java @@ -14,56 +14,64 @@ import java.util.stream.Collectors; public class FileChangeMutatorConfigurator implements BuildMutatorConfigurator { - private final Class mutatorClass; + private final Class mutatorClass; - public FileChangeMutatorConfigurator(Class mutatorClass) { - this.mutatorClass = mutatorClass; - } + public FileChangeMutatorConfigurator(Class mutatorClass) { + this.mutatorClass = mutatorClass; + } - @Override - public BuildMutator configure(Config scenario, String scenarioName, InvocationSettings settings, String key) { - List mutatorsForKey = new ArrayList<>(); - for (File sourceFileToChange : sourceFiles(scenario, scenarioName, settings.getProjectDir(), key)) { - mutatorsForKey.add(getBuildMutatorForFile(sourceFileToChange)); - } + @Override + public BuildMutator configure( + Config scenario, String scenarioName, InvocationSettings settings, String key) { + List mutatorsForKey = new ArrayList<>(); + for (File sourceFileToChange : + sourceFiles(scenario, scenarioName, settings.getProjectDir(), key)) { + mutatorsForKey.add(getBuildMutatorForFile(sourceFileToChange)); + } - return new CompositeBuildMutator(mutatorsForKey); - } + return new CompositeBuildMutator(mutatorsForKey); + } - private BuildMutator getBuildMutatorForFile(File sourceFileToChange) { - if (sourceFileToChange != null) { - try { - try { - return mutatorClass.getConstructor(File.class).newInstance(sourceFileToChange); - } catch (InvocationTargetException e) { - throw e.getCause(); - } - } catch (Throwable e) { - throw new RuntimeException("Could not create instance of mutator " + mutatorClass.getSimpleName(), e); - } + private BuildMutator getBuildMutatorForFile(File sourceFileToChange) { + if (sourceFileToChange != null) { + try { + try { + return mutatorClass.getConstructor(File.class).newInstance(sourceFileToChange); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } catch (Throwable e) { + throw new RuntimeException( + "Could not create instance of mutator " + mutatorClass.getSimpleName(), e); + } - } else { - return null; - } - } + } else { + return null; + } + } - private static List sourceFiles(Config config, String scenarioName, File projectDir, String key) { - return ConfigUtil.strings(config, key) - .stream() - .map(fileName -> openFile(fileName, projectDir, scenarioName)) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - } + private static List sourceFiles( + Config config, String scenarioName, File projectDir, String key) { + return ConfigUtil.strings(config, key).stream() + .map(fileName -> openFile(fileName, projectDir, scenarioName)) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } - private static File openFile(String fileName, File projectDir, String scenarioName) { - if (fileName == null) { - return null; - } else { - File file = new File(projectDir, fileName); - if (!file.isFile()) { - throw new IllegalArgumentException("Source file " + file.getName() + " specified for scenario " + scenarioName + " does not exist."); - } - return file; - } - } + private static File openFile(String fileName, File projectDir, String scenarioName) { + if (fileName == null) { + return null; + } else { + File file = new File(projectDir, fileName); + if (!file.isFile()) { + throw new IllegalArgumentException( + "Source file " + + file.getName() + + " specified for scenario " + + scenarioName + + " does not exist."); + } + return file; + } + } } diff --git a/src/main/java/org/gradle/profiler/mutations/GitCheckoutMutator.java b/src/main/java/org/gradle/profiler/mutations/GitCheckoutMutator.java index eb76edc9..1770b8f6 100644 --- a/src/main/java/org/gradle/profiler/mutations/GitCheckoutMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/GitCheckoutMutator.java @@ -12,69 +12,74 @@ public class GitCheckoutMutator extends AbstractGitMutator { - private final String cleanup; - private final String build; - private String original; + private final String cleanup; + private final String build; + private String original; - public GitCheckoutMutator(File projectDir, String cleanup, String build) { - super(projectDir); - this.cleanup = cleanup; - this.build = build; - } + public GitCheckoutMutator(File projectDir, String cleanup, String build) { + super(projectDir); + this.cleanup = cleanup; + this.build = build; + } - @Override - public void beforeScenario(ScenarioContext context) { - resetGit(); - original = getCurrentCommit(); - } + @Override + public void beforeScenario(ScenarioContext context) { + resetGit(); + original = getCurrentCommit(); + } - @Override - public void beforeCleanup(BuildContext context) { - if (cleanup != null) { - checkout(cleanup); - } - } + @Override + public void beforeCleanup(BuildContext context) { + if (cleanup != null) { + checkout(cleanup); + } + } - @Override - public void beforeBuild(BuildContext context) { - if (build != null) { - checkout(build); - } - } + @Override + public void beforeBuild(BuildContext context) { + if (build != null) { + checkout(build); + } + } - @Override - public void afterBuild(BuildContext context, Throwable error) { - if (error == null) { - checkout(original); - } else { - System.out.println("> Not checking out original Git commit because of error during build"); - } - } + @Override + public void afterBuild(BuildContext context, Throwable error) { + if (error == null) { + checkout(original); + } else { + System.out.println( + "> Not checking out original Git commit because of error during build"); + } + } - private String getCurrentCommit() { - return new CommandExec().inDir(projectDir).runAndCollectOutput("git", "rev-parse", "HEAD").trim(); - } + private String getCurrentCommit() { + return new CommandExec() + .inDir(projectDir) + .runAndCollectOutput("git", "rev-parse", "HEAD") + .trim(); + } - private void checkout(String target) { - System.out.println("> Checking out " + target); - new CommandExec().inDir(projectDir).run("git", "checkout", target); - } + private void checkout(String target) { + System.out.println("> Checking out " + target); + new CommandExec().inDir(projectDir).run("git", "checkout", target); + } - public static class Configurator implements BuildMutatorConfigurator { - @Override - public BuildMutator configure(Config scenario, String scenarioName, InvocationSettings settings, String key) { - Config config = scenario.getConfig(key); - String cleanup = ConfigUtil.string(config, "cleanup", null); - String build = ConfigUtil.string(config, "build", null); - if (build == null) { - throw new IllegalArgumentException("No git-checkout target specified for build"); - } - return new GitCheckoutMutator(settings.getProjectDir(), cleanup, build); - } - } + public static class Configurator implements BuildMutatorConfigurator { + @Override + public BuildMutator configure( + Config scenario, String scenarioName, InvocationSettings settings, String key) { + Config config = scenario.getConfig(key); + String cleanup = ConfigUtil.string(config, "cleanup", null); + String build = ConfigUtil.string(config, "build", null); + if (build == null) { + throw new IllegalArgumentException("No git-checkout target specified for build"); + } + return new GitCheckoutMutator(settings.getProjectDir(), cleanup, build); + } + } - @Override - public String toString() { - return getClass().getSimpleName() + "(cleanup: " + cleanup + ", build: " + build + ")"; - } + @Override + public String toString() { + return getClass().getSimpleName() + "(cleanup: " + cleanup + ", build: " + build + ")"; + } } diff --git a/src/main/java/org/gradle/profiler/mutations/GitRevertMutator.java b/src/main/java/org/gradle/profiler/mutations/GitRevertMutator.java index bc66acee..7d55c79b 100644 --- a/src/main/java/org/gradle/profiler/mutations/GitRevertMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/GitRevertMutator.java @@ -16,35 +16,36 @@ public class GitRevertMutator extends AbstractGitMutator { - private final List commits; + private final List commits; - public GitRevertMutator(File projectDir, List commits) { - super(projectDir); - this.commits = commits; - } + public GitRevertMutator(File projectDir, List commits) { + super(projectDir); + this.commits = commits; + } - @Override - public void beforeScenario(ScenarioContext context) { - resetGit(); - } + @Override + public void beforeScenario(ScenarioContext context) { + resetGit(); + } - @Override - public void beforeBuild(BuildContext context) { + @Override + public void beforeBuild(BuildContext context) { revertCommits(); - } + } - @Override - public void afterBuild(BuildContext context, Throwable error) { - if (error == null) { - abortRevert(); - resetGit(); - } else { - System.out.println("> Not resetting Git because of error during build"); - } - } + @Override + public void afterBuild(BuildContext context, Throwable error) { + if (error == null) { + abortRevert(); + resetGit(); + } else { + System.out.println("> Not resetting Git because of error during build"); + } + } - private void revertCommits() { - System.out.println("> Reverting Git commit(s) " + commits.stream().collect(Collectors.joining(", "))); + private void revertCommits() { + System.out.println( + "> Reverting Git commit(s) " + commits.stream().collect(Collectors.joining(", "))); new CommandExec().inDir(projectDir).run("git", "revert", "--quit"); List commandLine = new ArrayList<>(); commandLine.addAll(Arrays.asList("git", "revert", "--no-commit")); @@ -58,18 +59,22 @@ private void abortRevert() { } public static class Configurator implements BuildMutatorConfigurator { - @Override - public BuildMutator configure(Config scenario, String scenarioName, InvocationSettings settings, String key) { - List commits = ConfigUtil.strings(scenario, key); - if (commits.isEmpty()) { - throw new IllegalArgumentException("No commits specified for git-revert"); - } - return new GitRevertMutator(settings.getProjectDir(), commits); - } - } + @Override + public BuildMutator configure( + Config scenario, String scenarioName, InvocationSettings settings, String key) { + List commits = ConfigUtil.strings(scenario, key); + if (commits.isEmpty()) { + throw new IllegalArgumentException("No commits specified for git-revert"); + } + return new GitRevertMutator(settings.getProjectDir(), commits); + } + } - @Override - public String toString() { - return getClass().getSimpleName() + "(" + commits.stream().collect(Collectors.joining(", ")) + ")"; - } + @Override + public String toString() { + return getClass().getSimpleName() + + "(" + + commits.stream().collect(Collectors.joining(", ")) + + ")"; + } } diff --git a/src/main/java/org/gradle/profiler/mutations/ShowBuildCacheSizeMutator.java b/src/main/java/org/gradle/profiler/mutations/ShowBuildCacheSizeMutator.java index 74e13736..deb2c5bb 100644 --- a/src/main/java/org/gradle/profiler/mutations/ShowBuildCacheSizeMutator.java +++ b/src/main/java/org/gradle/profiler/mutations/ShowBuildCacheSizeMutator.java @@ -10,45 +10,49 @@ public class ShowBuildCacheSizeMutator extends AbstractBuildMutator { - private final File gradleUserHome; - - public ShowBuildCacheSizeMutator(File gradleUserHome) { - this.gradleUserHome = gradleUserHome; - } - - @Override - public void beforeScenario(ScenarioContext context) { - showCacheSize(); - } - - @Override - public void afterCleanup(BuildContext context, Throwable error) { - showCacheSize(); - } - - @Override - public void afterBuild(BuildContext context, Throwable error) { - showCacheSize(); - } - - private void showCacheSize() { - File cacheDir = new File(new File(gradleUserHome, "caches"), "build-cache-1"); - File[] cacheFiles = cacheDir.listFiles((file) -> file.getName().length() == 32); - if (cacheFiles == null) { - System.out.println("> Cannot list cache directory " + cacheDir); - } else { - long size = 0; - for (File cacheFile : cacheFiles) { - size += cacheFile.length(); - } - System.out.println(MessageFormat.format("> Build cache size: {0,number} bytes in {1,number} file(s)", size, cacheFiles.length)); - } - } - - public static class Configurator extends AbstractBuildMutatorWithoutOptionsConfigurator { + private final File gradleUserHome; + + public ShowBuildCacheSizeMutator(File gradleUserHome) { + this.gradleUserHome = gradleUserHome; + } + + @Override + public void beforeScenario(ScenarioContext context) { + showCacheSize(); + } + + @Override + public void afterCleanup(BuildContext context, Throwable error) { + showCacheSize(); + } + + @Override + public void afterBuild(BuildContext context, Throwable error) { + showCacheSize(); + } + + private void showCacheSize() { + File cacheDir = new File(new File(gradleUserHome, "caches"), "build-cache-1"); + File[] cacheFiles = cacheDir.listFiles((file) -> file.getName().length() == 32); + if (cacheFiles == null) { + System.out.println("> Cannot list cache directory " + cacheDir); + } else { + long size = 0; + for (File cacheFile : cacheFiles) { + size += cacheFile.length(); + } + System.out.println( + MessageFormat.format( + "> Build cache size: {0,number} bytes in {1,number} file(s)", + size, + cacheFiles.length)); + } + } + + public static class Configurator extends AbstractBuildMutatorWithoutOptionsConfigurator { @Override BuildMutator createBuildMutator(InvocationSettings settings) { return new ShowBuildCacheSizeMutator(settings.getGradleUserHome()); } - } + } } diff --git a/src/main/java/org/gradle/profiler/report/AbstractGenerator.java b/src/main/java/org/gradle/profiler/report/AbstractGenerator.java index 7b33719e..8271757b 100644 --- a/src/main/java/org/gradle/profiler/report/AbstractGenerator.java +++ b/src/main/java/org/gradle/profiler/report/AbstractGenerator.java @@ -21,7 +21,9 @@ public void write(InvocationSettings settings, BenchmarkResult result) throws IO } } - protected abstract void write(InvocationSettings settings, BenchmarkResult result, BufferedWriter writer) throws IOException; + protected abstract void write( + InvocationSettings settings, BenchmarkResult result, BufferedWriter writer) + throws IOException; public void summarizeResults(Consumer consumer) { consumer.accept(outputFile.getAbsolutePath()); diff --git a/src/main/java/org/gradle/profiler/report/BuildScenarioResult.java b/src/main/java/org/gradle/profiler/report/BuildScenarioResult.java index 5794f1ab..fdfc0035 100644 --- a/src/main/java/org/gradle/profiler/report/BuildScenarioResult.java +++ b/src/main/java/org/gradle/profiler/report/BuildScenarioResult.java @@ -9,13 +9,9 @@ public interface BuildScenarioResult { ScenarioDefinition getScenarioDefinition(); - /** - * Returns the names of the samples collected for each build invocation in this scenario. - */ + /** Returns the names of the samples collected for each build invocation in this scenario. */ List> getSamples(); - /** - * Returns all results, including warm-up builds. - */ + /** Returns all results, including warm-up builds. */ List getResults(); } diff --git a/src/main/java/org/gradle/profiler/report/CsvGenerator.java b/src/main/java/org/gradle/profiler/report/CsvGenerator.java index 27c128a7..a19ae76a 100644 --- a/src/main/java/org/gradle/profiler/report/CsvGenerator.java +++ b/src/main/java/org/gradle/profiler/report/CsvGenerator.java @@ -15,7 +15,8 @@ public class CsvGenerator extends AbstractGenerator { private final Format format; public enum Format { - LONG, WIDE; + LONG, + WIDE; public static Format parse(String name) { for (Format format : values()) { @@ -33,7 +34,9 @@ public CsvGenerator(File outputFile, Format format) { } @Override - protected void write(InvocationSettings settings, BenchmarkResult benchmarkResult, BufferedWriter writer) throws IOException { + protected void write( + InvocationSettings settings, BenchmarkResult benchmarkResult, BufferedWriter writer) + throws IOException { List> allScenarios = benchmarkResult.getScenarios(); switch (format) { case WIDE: @@ -47,7 +50,9 @@ protected void write(InvocationSettings settings, BenchmarkResult benchmarkResul } } - private void writeWide(BufferedWriter writer, List> allScenarios) throws IOException { + private void writeWide( + BufferedWriter writer, List> allScenarios) + throws IOException { writer.write("scenario"); for (BuildScenarioResult scenario : allScenarios) { for (int i = 0; i < scenario.getSamples().size(); i++) { @@ -102,22 +107,25 @@ private void writeWide(BufferedWriter writer, List void writeWideRow(BufferedWriter writer, int row, BuildScenarioResult scenario) throws IOException { + private void writeWideRow( + BufferedWriter writer, int row, BuildScenarioResult scenario) throws IOException { List results = scenario.getResults(); writer.write(","); if (row >= results.size()) { return; } T buildResult = results.get(row); - writer.write(scenario.getSamples().stream() - .map(sample -> sample.extractFrom(buildResult)) - .map(Duration::toMillis) - .map(Object::toString) - .collect(Collectors.joining(",")) - ); + writer.write( + scenario.getSamples().stream() + .map(sample -> sample.extractFrom(buildResult)) + .map(Duration::toMillis) + .map(Object::toString) + .collect(Collectors.joining(","))); } - private void writeLong(BufferedWriter writer, List> allScenarios) throws IOException { + private void writeLong( + BufferedWriter writer, List> allScenarios) + throws IOException { writer.write("Scenario,Tool,Tasks,Phase,Iteration,Sample,Duration"); writer.newLine(); for (BuildScenarioResult scenario : allScenarios) { @@ -125,7 +133,8 @@ private void writeLong(BufferedWriter writer, List void writeLongRow(BufferedWriter writer, BuildScenarioResult scenario) throws IOException { + private void writeLongRow( + BufferedWriter writer, BuildScenarioResult scenario) throws IOException { for (T result : scenario.getResults()) { for (Sample sample : scenario.getSamples()) { writer.write(scenario.getScenarioDefinition().getTitle()); diff --git a/src/main/java/org/gradle/profiler/report/HtmlGenerator.java b/src/main/java/org/gradle/profiler/report/HtmlGenerator.java index 98889ef3..e6b5675c 100644 --- a/src/main/java/org/gradle/profiler/report/HtmlGenerator.java +++ b/src/main/java/org/gradle/profiler/report/HtmlGenerator.java @@ -19,30 +19,38 @@ public HtmlGenerator(File outputFile) { } @Override - protected void write(InvocationSettings settings, BenchmarkResult benchmarkResult, BufferedWriter writer) throws IOException { - Resources.readLines(Resources.getResource(HtmlGenerator.class, "report-template.html"), StandardCharsets.UTF_8, new LineProcessor() { - @Override - public boolean processLine(String line) throws IOException { - if (line.equals(SCRIPT_PLACEHOLDER)) { - Resources.asCharSource(Resources.getResource(HtmlGenerator.class, "report.js"), StandardCharsets.UTF_8).copyTo(writer); - } else if (line.equals(JSON_PLACEHOLDER)) { - new JsonResultWriter(true).write( - settings.getBenchmarkTitle(), - Instant.now(), - benchmarkResult.getScenarios(), - writer - ); - } else { - writer.write(line); - } - writer.write("\n"); - return true; - } + protected void write( + InvocationSettings settings, BenchmarkResult benchmarkResult, BufferedWriter writer) + throws IOException { + Resources.readLines( + Resources.getResource(HtmlGenerator.class, "report-template.html"), + StandardCharsets.UTF_8, + new LineProcessor() { + @Override + public boolean processLine(String line) throws IOException { + if (line.equals(SCRIPT_PLACEHOLDER)) { + Resources.asCharSource( + Resources.getResource(HtmlGenerator.class, "report.js"), + StandardCharsets.UTF_8) + .copyTo(writer); + } else if (line.equals(JSON_PLACEHOLDER)) { + new JsonResultWriter(true) + .write( + settings.getBenchmarkTitle(), + Instant.now(), + benchmarkResult.getScenarios(), + writer); + } else { + writer.write(line); + } + writer.write("\n"); + return true; + } - @Override - public Void getResult() { - return null; - } - }); + @Override + public Void getResult() { + return null; + } + }); } } diff --git a/src/main/java/org/gradle/profiler/report/JsonResultWriter.java b/src/main/java/org/gradle/profiler/report/JsonResultWriter.java index 68a44f8a..bf95d504 100644 --- a/src/main/java/org/gradle/profiler/report/JsonResultWriter.java +++ b/src/main/java/org/gradle/profiler/report/JsonResultWriter.java @@ -16,6 +16,7 @@ import javax.annotation.Nullable; import javax.annotation.OverridingMethodsMustInvokeSuper; + import java.io.Writer; import java.lang.reflect.Type; import java.time.Duration; @@ -33,17 +34,31 @@ public JsonResultWriter(boolean pretty) { this.pretty = pretty; } - public void write(@Nullable String title, Temporal reportDate, List> scenarios, Writer writer) { + public void write( + @Nullable String title, + Temporal reportDate, + List> scenarios, + Writer writer) { GsonBuilder builder = new GsonBuilder(); if (pretty) { builder.setPrettyPrinting(); } - Gson gson = builder - .registerTypeHierarchyAdapter(BuildScenarioResult.class, (JsonSerializer>) this::serializeScenarioResult) - .registerTypeHierarchyAdapter(ScenarioDefinition.class, new ScenarioSerializer<>()) - .registerTypeHierarchyAdapter(GradleScenarioDefinition.class, new GradleScenarioSerializer()) - .registerTypeHierarchyAdapter(Temporal.class, (JsonSerializer) (date, type, context) -> new JsonPrimitive(DateTimeFormatter.ISO_INSTANT.format(date))) - .create(); + Gson gson = + builder.registerTypeHierarchyAdapter( + BuildScenarioResult.class, + (JsonSerializer>) + this::serializeScenarioResult) + .registerTypeHierarchyAdapter( + ScenarioDefinition.class, new ScenarioSerializer<>()) + .registerTypeHierarchyAdapter( + GradleScenarioDefinition.class, new GradleScenarioSerializer()) + .registerTypeHierarchyAdapter( + Temporal.class, + (JsonSerializer) + (date, type, context) -> + new JsonPrimitive( + DateTimeFormatter.ISO_INSTANT.format(date))) + .create(); gson.toJson(new Output(title, reportDate, new Environment(), scenarios), writer); } @@ -64,11 +79,10 @@ private static class Output { final List> scenarios; public Output( - String title, - Temporal date, - Environment environment, - List> scenarios - ) { + String title, + Temporal date, + Environment environment, + List> scenarios) { this.title = title; this.date = date; this.environment = environment; @@ -76,15 +90,16 @@ public Output( } } - private JsonObject serializeScenarioResult(BuildScenarioResult scenarioResult, Type type, JsonSerializationContext context) { + private JsonObject serializeScenarioResult( + BuildScenarioResult scenarioResult, Type type, JsonSerializationContext context) { JsonObject json = new JsonObject(); List results = scenarioResult.getResults(); // TODO Expose this in a less awkward way - JsonObject jsonDefinition = (JsonObject) context.serialize(scenarioResult.getScenarioDefinition()); - String scenarioId = results.isEmpty() - ? null - : results.get(0).getBuildContext().getUniqueScenarioId(); + JsonObject jsonDefinition = + (JsonObject) context.serialize(scenarioResult.getScenarioDefinition()); + String scenarioId = + results.isEmpty() ? null : results.get(0).getBuildContext().getUniqueScenarioId(); jsonDefinition.addProperty("id", scenarioId); json.add("definition", jsonDefinition); @@ -108,7 +123,8 @@ private JsonObject serializeSample(Sample sample) { return json; } - private JsonObject serializeIteration(T result, List> samples) { + private JsonObject serializeIteration( + T result, List> samples) { JsonObject json = new JsonObject(); json.addProperty("id", result.getBuildContext().getUniqueBuildId()); json.addProperty("phase", result.getBuildContext().getPhase().name()); @@ -123,7 +139,8 @@ private JsonObject serializeIteration(T result return json; } - private static class ScenarioSerializer implements JsonSerializer { + private static class ScenarioSerializer + implements JsonSerializer { @Override @OverridingMethodsMustInvokeSuper public JsonObject serialize(T scenario, Type typeOfSrc, JsonSerializationContext context) { @@ -137,20 +154,34 @@ public JsonObject serialize(T scenario, Type typeOfSrc, JsonSerializationContext } } - private static class GradleScenarioSerializer extends ScenarioSerializer { + private static class GradleScenarioSerializer + extends ScenarioSerializer { @Override - public JsonObject serialize(GradleScenarioDefinition scenario, Type typeOfSrc, JsonSerializationContext context) { + public JsonObject serialize( + GradleScenarioDefinition scenario, + Type typeOfSrc, + JsonSerializationContext context) { JsonObject json = super.serialize(scenario, typeOfSrc, context); - json.addProperty("version", scenario.getBuildConfiguration().getGradleVersion().getVersion()); - json.addProperty("gradleHome", scenario.getBuildConfiguration().getGradleHome().getAbsolutePath()); - json.addProperty("javaHome", scenario.getBuildConfiguration().getJavaHome().getAbsolutePath()); + json.addProperty( + "version", scenario.getBuildConfiguration().getGradleVersion().getVersion()); + json.addProperty( + "gradleHome", + scenario.getBuildConfiguration().getGradleHome().getAbsolutePath()); + json.addProperty( + "javaHome", scenario.getBuildConfiguration().getJavaHome().getAbsolutePath()); json.addProperty("usesScanPlugin", scenario.getBuildConfiguration().isUsesScanPlugin()); json.addProperty("action", scenario.getAction().getDisplayName()); json.addProperty("cleanup", scenario.getCleanupAction().getDisplayName()); json.addProperty("invoker", scenario.getInvoker().toString()); - json.add("mutators", toJson(scenario.getBuildMutators().stream().map(Object::toString))); + json.add( + "mutators", toJson(scenario.getBuildMutators().stream().map(Object::toString))); json.add("args", toJson(scenario.getGradleArgs().stream())); - json.add("jvmArgs", toJson(Stream.concat(scenario.getBuildConfiguration().getJvmArguments().stream(), scenario.getJvmArgs().stream()))); + json.add( + "jvmArgs", + toJson( + Stream.concat( + scenario.getBuildConfiguration().getJvmArguments().stream(), + scenario.getJvmArgs().stream()))); json.add("systemProperties", toJson(scenario.getSystemProperties())); return json; } diff --git a/src/main/java/org/gradle/profiler/result/BuildInvocationResult.java b/src/main/java/org/gradle/profiler/result/BuildInvocationResult.java index 5513cec9..bbf42272 100644 --- a/src/main/java/org/gradle/profiler/result/BuildInvocationResult.java +++ b/src/main/java/org/gradle/profiler/result/BuildInvocationResult.java @@ -8,17 +8,18 @@ public class BuildInvocationResult { private final BuildContext buildContext; private final Duration executionTime; - public static final Sample EXECUTION_TIME = new Sample() { - @Override - public String getName() { - return "execution"; - } - - @Override - public Duration extractFrom(BuildInvocationResult result) { - return result.getExecutionTime(); - } - }; + public static final Sample EXECUTION_TIME = + new Sample() { + @Override + public String getName() { + return "execution"; + } + + @Override + public Duration extractFrom(BuildInvocationResult result) { + return result.getExecutionTime(); + } + }; public BuildInvocationResult(BuildContext buildContext, Duration executionTime) { this.buildContext = buildContext; diff --git a/src/main/java/org/gradle/profiler/studio/LaunchConfiguration.java b/src/main/java/org/gradle/profiler/studio/LaunchConfiguration.java index f9bb01b4..c8e1cfa1 100644 --- a/src/main/java/org/gradle/profiler/studio/LaunchConfiguration.java +++ b/src/main/java/org/gradle/profiler/studio/LaunchConfiguration.java @@ -13,13 +13,14 @@ public class LaunchConfiguration { private final Path supportJar; private final List sharedJars; - public LaunchConfiguration(Path javaCommand, - List classPath, - Map systemProperties, - String mainClass, - Path agentJar, - Path supportJar, - List sharedJars) { + public LaunchConfiguration( + Path javaCommand, + List classPath, + Map systemProperties, + String mainClass, + Path agentJar, + Path supportJar, + List sharedJars) { this.javaCommand = javaCommand; this.classPath = classPath; this.systemProperties = systemProperties; diff --git a/src/main/java/org/gradle/profiler/studio/LauncherConfigurationParser.java b/src/main/java/org/gradle/profiler/studio/LauncherConfigurationParser.java index 1ec4fb7f..99b9d6d0 100644 --- a/src/main/java/org/gradle/profiler/studio/LauncherConfigurationParser.java +++ b/src/main/java/org/gradle/profiler/studio/LauncherConfigurationParser.java @@ -27,15 +27,34 @@ public LaunchConfiguration calculate(Path studioInstallDir) { actualInstallDir = studioInstallDir; } Dict jvmOptions = entries.dict("JVMOptions"); - List classPath = Arrays.stream(jvmOptions.string("ClassPath").split(":")).map(s -> FileSystems.getDefault().getPath(s.replace("$APP_PACKAGE", actualInstallDir.toString()))).collect(Collectors.toList()); + List classPath = + Arrays.stream(jvmOptions.string("ClassPath").split(":")) + .map( + s -> + FileSystems.getDefault() + .getPath( + s.replace( + "$APP_PACKAGE", + actualInstallDir.toString()))) + .collect(Collectors.toList()); String mainClass = jvmOptions.string("MainClass"); - Map systemProperties = mapValues(jvmOptions.dict("Properties").toMap(), v -> v.replace("$APP_PACKAGE", actualInstallDir.toString())); + Map systemProperties = + mapValues( + jvmOptions.dict("Properties").toMap(), + v -> v.replace("$APP_PACKAGE", actualInstallDir.toString())); Path javaCommand = actualInstallDir.resolve("Contents/jre/jdk/Contents/Home/bin/java"); Path agentJar = GradleInstrumentation.unpackPlugin("studio-agent").toPath(); Path asmJar = GradleInstrumentation.unpackPlugin("asm").toPath(); Path supportJar = GradleInstrumentation.unpackPlugin("instrumentation-support").toPath(); Path protocolJar = GradleInstrumentation.unpackPlugin("client-protocol").toPath(); - return new LaunchConfiguration(javaCommand, classPath, systemProperties, mainClass, agentJar, supportJar, Arrays.asList(asmJar, protocolJar)); + return new LaunchConfiguration( + javaCommand, + classPath, + systemProperties, + mainClass, + agentJar, + supportJar, + Arrays.asList(asmJar, protocolJar)); } private static Dict parse(Path infoFile) { @@ -76,7 +95,8 @@ Map toMap() { private NSObject getEntry(String key) { NSObject value = contents.get(key); if (value == null) { - throw new IllegalArgumentException(String.format("Dictionary does not contain entry '%s'.", key)); + throw new IllegalArgumentException( + String.format("Dictionary does not contain entry '%s'.", key)); } return value; } diff --git a/src/main/java/org/gradle/profiler/studio/StudioGradleClient.java b/src/main/java/org/gradle/profiler/studio/StudioGradleClient.java index 2cdcd58a..45db33c9 100644 --- a/src/main/java/org/gradle/profiler/studio/StudioGradleClient.java +++ b/src/main/java/org/gradle/profiler/studio/StudioGradleClient.java @@ -18,14 +18,17 @@ public class StudioGradleClient implements GradleClient { private final ServerConnection agentConnection; private boolean hasRun; - public StudioGradleClient(GradleBuildConfiguration buildConfiguration, InvocationSettings invocationSettings) { + public StudioGradleClient( + GradleBuildConfiguration buildConfiguration, InvocationSettings invocationSettings) { if (!OperatingSystem.isMacOS()) { - throw new IllegalArgumentException("Support for Android studio is currently only implemented on macOS."); + throw new IllegalArgumentException( + "Support for Android studio is currently only implemented on macOS."); } Path studioInstallDir = invocationSettings.getStudioInstallDir().toPath(); Logging.startOperation("Starting Android Studio at " + studioInstallDir); - LaunchConfiguration launchConfiguration = new LauncherConfigurationParser().calculate(studioInstallDir); + LaunchConfiguration launchConfiguration = + new LauncherConfigurationParser().calculate(studioInstallDir); System.out.println(); System.out.println("* Java command: " + launchConfiguration.getJavaCommand()); System.out.println("* Classpath:"); @@ -33,29 +36,44 @@ public StudioGradleClient(GradleBuildConfiguration buildConfiguration, Invocatio System.out.println(" " + entry); } System.out.println("* System properties:"); - for (Map.Entry entry : launchConfiguration.getSystemProperties().entrySet()) { + for (Map.Entry entry : + launchConfiguration.getSystemProperties().entrySet()) { System.out.println(" " + entry.getKey() + " -> " + entry.getValue()); } System.out.println("* Main class: " + launchConfiguration.getMainClass()); server = new Server("agent"); - studioProcess = startStudio(launchConfiguration, studioInstallDir, invocationSettings, server); + studioProcess = + startStudio(launchConfiguration, studioInstallDir, invocationSettings, server); agentConnection = server.waitForIncoming(Duration.ofMinutes(1)); agentConnection.send(new ConnectionParameters(buildConfiguration.getGradleHome())); } - private CommandExec.RunHandle startStudio(LaunchConfiguration launchConfiguration, Path studioInstallDir, InvocationSettings invocationSettings, Server server) { + private CommandExec.RunHandle startStudio( + LaunchConfiguration launchConfiguration, + Path studioInstallDir, + InvocationSettings invocationSettings, + Server server) { List commandLine = new ArrayList<>(); commandLine.add(launchConfiguration.getJavaCommand().toString()); commandLine.add("-cp"); commandLine.add(Joiner.on(File.pathSeparator).join(launchConfiguration.getClassPath())); - for (Map.Entry systemProperty : launchConfiguration.getSystemProperties().entrySet()) { + for (Map.Entry systemProperty : + launchConfiguration.getSystemProperties().entrySet()) { commandLine.add("-D" + systemProperty.getKey() + "=" + systemProperty.getValue()); } - commandLine.add("-javaagent:" + launchConfiguration.getAgentJar() + "=" + server.getPort() + "," + launchConfiguration.getSupportJar()); + commandLine.add( + "-javaagent:" + + launchConfiguration.getAgentJar() + + "=" + + server.getPort() + + "," + + launchConfiguration.getSupportJar()); commandLine.add("--add-exports"); commandLine.add("java.base/jdk.internal.misc=ALL-UNNAMED"); - commandLine.add("-Xbootclasspath/a:" + Joiner.on(File.pathSeparator).join(launchConfiguration.getSharedJars())); + commandLine.add( + "-Xbootclasspath/a:" + + Joiner.on(File.pathSeparator).join(launchConfiguration.getSharedJars())); commandLine.add(launchConfiguration.getMainClass()); commandLine.add(invocationSettings.getProjectDir().getAbsolutePath()); System.out.println("* Using command line: " + commandLine); @@ -74,13 +92,15 @@ public void close() throws IOException { public Duration sync(List gradleArgs, List jvmArgs) { if (!hasRun) { - System.out.println("* PLEASE RUN SYNC IN ANDROID STUDIO (once it has finished starting up)...."); + System.out.println( + "* PLEASE RUN SYNC IN ANDROID STUDIO (once it has finished starting up)...."); hasRun = true; } else { System.out.println("* PLEASE RUN SYNC IN ANDROID STUDIO...."); } - // Use a long time out because it can take quite some time between the tapi action completing and studio finishing the sync + // Use a long time out because it can take quite some time between the tapi action + // completing and studio finishing the sync SyncStarted started = agentConnection.receiveSyncStarted(Duration.ofMinutes(10)); agentConnection.send(new SyncParameters(gradleArgs, jvmArgs)); System.out.println("* Sync has started, waiting for it to complete..."); diff --git a/src/main/java/org/gradle/profiler/yourkit/YourKit.java b/src/main/java/org/gradle/profiler/yourkit/YourKit.java index 7d60b6d9..2cdb3006 100644 --- a/src/main/java/org/gradle/profiler/yourkit/YourKit.java +++ b/src/main/java/org/gradle/profiler/yourkit/YourKit.java @@ -6,9 +6,7 @@ public class YourKit { static final String ENIVONMENT_VARIABLE = "YOURKIT_HOME"; private static final String YOURKIT_HOME = System.getenv(ENIVONMENT_VARIABLE); - /** - * Locates the user's YourKit installation. Returns null when not found. - */ + /** Locates the user's YourKit installation. Returns null when not found. */ public static File findYourKitHome() { if (YOURKIT_HOME != null) { File ykHome = new File(YOURKIT_HOME); @@ -30,13 +28,20 @@ public static File findYourKitHome() { public static File findControllerJar() { File yourKitHome = findYourKitHome(); - return tryLocations(yourKitHome, "Contents/Resources/lib/yjp-controller-api-redist.jar", "lib/yjp-controller-api-redist.jar"); + return tryLocations( + yourKitHome, + "Contents/Resources/lib/yjp-controller-api-redist.jar", + "lib/yjp-controller-api-redist.jar"); } public static File findJniLib() { File yourKitHome = findYourKitHome(); String macLibLocationPrefix = "Contents/Resources/bin/mac/libyjpagent."; - return tryLocations(yourKitHome, macLibLocationPrefix + "jnilib", macLibLocationPrefix + "dylib", "bin/linux-x86-64/libyjpagent.so"); + return tryLocations( + yourKitHome, + macLibLocationPrefix + "jnilib", + macLibLocationPrefix + "dylib", + "bin/linux-x86-64/libyjpagent.so"); } private static File tryLocations(File baseDir, String... candidates) { diff --git a/src/main/java/org/gradle/profiler/yourkit/YourKitJvmArgsCalculator.java b/src/main/java/org/gradle/profiler/yourkit/YourKitJvmArgsCalculator.java index 59036011..f8d2de84 100644 --- a/src/main/java/org/gradle/profiler/yourkit/YourKitJvmArgsCalculator.java +++ b/src/main/java/org/gradle/profiler/yourkit/YourKitJvmArgsCalculator.java @@ -16,7 +16,11 @@ public class YourKitJvmArgsCalculator implements JvmArgsCalculator { private final boolean startRecordingOnStart; private final boolean captureSnapshotOnProcessExit; - public YourKitJvmArgsCalculator(ScenarioSettings settings, YourKitConfig yourKitConfig, boolean startRecordingOnStart, boolean captureSnapshotOnProcessExit) { + public YourKitJvmArgsCalculator( + ScenarioSettings settings, + YourKitConfig yourKitConfig, + boolean startRecordingOnStart, + boolean captureSnapshotOnProcessExit) { this.settings = settings; this.yourKitConfig = yourKitConfig; this.startRecordingOnStart = startRecordingOnStart; @@ -26,19 +30,30 @@ public YourKitJvmArgsCalculator(ScenarioSettings settings, YourKitConfig yourKit @Override public void calculateJvmArgs(List jvmArgs) { if (!OperatingSystem.isMacOS() && !OperatingSystem.isLinuxX86()) { - throw new IllegalArgumentException("YourKit is currently supported on OS X and Linux x64 only."); + throw new IllegalArgumentException( + "YourKit is currently supported on OS X and Linux x64 only."); } File yourKitHome = YourKit.findYourKitHome(); if (yourKitHome == null) { - throw new IllegalArgumentException("Could not locate YourKit installation. Try setting the " + ENIVONMENT_VARIABLE + " environment variable"); + throw new IllegalArgumentException( + "Could not locate YourKit installation. Try setting the " + + ENIVONMENT_VARIABLE + + " environment variable"); } File jnilib = YourKit.findJniLib(); if (!jnilib.isFile()) { - throw new IllegalArgumentException("Could not locate YourKit library in YourKit home directory " + yourKitHome); + throw new IllegalArgumentException( + "Could not locate YourKit library in YourKit home directory " + yourKitHome); } - String agentOptions = "-agentpath:" + jnilib.getAbsolutePath() + "=dir=" + settings.getScenario().getOutputDir().getAbsolutePath() - + ",sessionname=" + settings.getScenario().getProfileName() - + ",port=" + PORT; + String agentOptions = + "-agentpath:" + + jnilib.getAbsolutePath() + + "=dir=" + + settings.getScenario().getOutputDir().getAbsolutePath() + + ",sessionname=" + + settings.getScenario().getProfileName() + + ",port=" + + PORT; if (yourKitConfig.isMemorySnapshot() || yourKitConfig.isUseSampling()) { agentOptions += ",disabletracing,probe_disable=*"; } else { diff --git a/src/main/java/org/gradle/profiler/yourkit/YourKitProfiler.java b/src/main/java/org/gradle/profiler/yourkit/YourKitProfiler.java index 0b0ce528..daa2f95f 100644 --- a/src/main/java/org/gradle/profiler/yourkit/YourKitProfiler.java +++ b/src/main/java/org/gradle/profiler/yourkit/YourKitProfiler.java @@ -37,7 +37,14 @@ protected SnapshotCapturingProfilerController doNewController(ScenarioSettings s } @Override - protected JvmArgsCalculator jvmArgsWithInstrumentation(ScenarioSettings settings, boolean startRecordingOnProcessStart, boolean captureSnapshotOnProcessExit) { - return new YourKitJvmArgsCalculator(settings, yourKitConfig, startRecordingOnProcessStart, captureSnapshotOnProcessExit); + protected JvmArgsCalculator jvmArgsWithInstrumentation( + ScenarioSettings settings, + boolean startRecordingOnProcessStart, + boolean captureSnapshotOnProcessExit) { + return new YourKitJvmArgsCalculator( + settings, + yourKitConfig, + startRecordingOnProcessStart, + captureSnapshotOnProcessExit); } } diff --git a/src/main/java/org/gradle/profiler/yourkit/YourKitProfilerController.java b/src/main/java/org/gradle/profiler/yourkit/YourKitProfilerController.java index edf5f732..be368354 100644 --- a/src/main/java/org/gradle/profiler/yourkit/YourKitProfilerController.java +++ b/src/main/java/org/gradle/profiler/yourkit/YourKitProfilerController.java @@ -5,7 +5,8 @@ import java.io.File; -public class YourKitProfilerController implements InstrumentingProfiler.SnapshotCapturingProfilerController { +public class YourKitProfilerController + implements InstrumentingProfiler.SnapshotCapturingProfilerController { private final YourKitConfig options; public YourKitProfilerController(YourKitConfig options) { @@ -42,19 +43,26 @@ public void captureSnapshot(String pid) { } @Override - public void stopSession() { - } + public void stopSession() {} private void runYourKitCommand(String command) { File controllerJar = findControllerJar(); - new CommandExec().run(System.getProperty("java.home") + "/bin/java", "-jar", controllerJar.getAbsolutePath(), "localhost", String.valueOf(YourKitJvmArgsCalculator.PORT), command); + new CommandExec() + .run( + System.getProperty("java.home") + "/bin/java", + "-jar", + controllerJar.getAbsolutePath(), + "localhost", + String.valueOf(YourKitJvmArgsCalculator.PORT), + command); } private File findControllerJar() { File yourKitHome = YourKit.findYourKitHome(); File controllerJar = YourKit.findControllerJar(); if (!controllerJar.isFile()) { - throw new IllegalArgumentException("Could not locate YourKit library in YourKit home directory " + yourKitHome); + throw new IllegalArgumentException( + "Could not locate YourKit library in YourKit home directory " + yourKitHome); } return controllerJar; } diff --git a/subprojects/build-operations/src/main/java/org/gradle/trace/buildops/BuildOperationTrace.java b/subprojects/build-operations/src/main/java/org/gradle/trace/buildops/BuildOperationTrace.java index 7feb3bf8..65384a00 100644 --- a/subprojects/build-operations/src/main/java/org/gradle/trace/buildops/BuildOperationTrace.java +++ b/subprojects/build-operations/src/main/java/org/gradle/trace/buildops/BuildOperationTrace.java @@ -44,26 +44,41 @@ public BuildOperationTrace(GradleInternal gradle) { } public BuildOperationTrace measureGarbageCollection(File outFile) { - Provider listenerProvider = sharedServices.registerIfAbsent("gc-time", GcTimeCollectionService.class, spec -> { - spec.getParameters().getOutputFile().set(outFile); - }); - // Force the service to be instantiated so we actually get a close() call at the end of the build + Provider listenerProvider = + sharedServices.registerIfAbsent( + "gc-time", + GcTimeCollectionService.class, + spec -> { + spec.getParameters().getOutputFile().set(outFile); + }); + // Force the service to be instantiated so we actually get a close() call at the end of the + // build registry.onTaskCompletion(listenerProvider); return this; } public BuildOperationTrace measureConfigurationTime(File outFile) { - Provider listenerProvider = sharedServices.registerIfAbsent("time-to-first-task", TimeToFirstTaskRecordingListener.class, spec -> { - spec.getParameters().getOutputFile().set(outFile); - }); + Provider listenerProvider = + sharedServices.registerIfAbsent( + "time-to-first-task", + TimeToFirstTaskRecordingListener.class, + spec -> { + spec.getParameters().getOutputFile().set(outFile); + }); registry.onOperationCompletion(listenerProvider); return this; } public BuildOperationTrace measureBuildOperations(Map capturedBuildOperations) { - Provider listenerProvider = sharedServices.registerIfAbsent("measure-build-operations", BuildOperationDurationRecordingListener.class, spec -> { - spec.getParameters().getCapturedBuildOperations().set(new HashMap<>(capturedBuildOperations)); - }); + Provider listenerProvider = + sharedServices.registerIfAbsent( + "measure-build-operations", + BuildOperationDurationRecordingListener.class, + spec -> { + spec.getParameters() + .getCapturedBuildOperations() + .set(new HashMap<>(capturedBuildOperations)); + }); registry.onOperationCompletion(listenerProvider); return this; } @@ -74,7 +89,10 @@ private static void writeToFile(File outputFile, Object data) throws IOException } } - public static abstract class GcTimeCollectionService implements BuildService, OperationCompletionListener, AutoCloseable { + public abstract static class GcTimeCollectionService + implements BuildService, + OperationCompletionListener, + AutoCloseable { interface Params extends BuildServiceParameters { RegularFileProperty getOutputFile(); } @@ -86,13 +104,18 @@ public void onFinish(FinishEvent event) { @Override public void close() throws Exception { - writeToFile(getParameters().getOutputFile().getAsFile().get(), ManagementFactory.getGarbageCollectorMXBeans().stream() - .map(GarbageCollectorMXBean::getCollectionTime) - .reduce(0L, Long::sum)); + writeToFile( + getParameters().getOutputFile().getAsFile().get(), + ManagementFactory.getGarbageCollectorMXBeans().stream() + .map(GarbageCollectorMXBean::getCollectionTime) + .reduce(0L, Long::sum)); } } - public static abstract class TimeToFirstTaskRecordingListener implements BuildService, BuildOperationListener, AutoCloseable { + public abstract static class TimeToFirstTaskRecordingListener + implements BuildService, + BuildOperationListener, + AutoCloseable { interface Params extends BuildServiceParameters { RegularFileProperty getOutputFile(); } @@ -100,17 +123,24 @@ interface Params extends BuildServiceParameters { private final AtomicLong timeToFirstTask = new AtomicLong(0); @Override - public void started(BuildOperationDescriptor buildOperationDescriptor, OperationStartEvent operationStartEvent) { - } + public void started( + BuildOperationDescriptor buildOperationDescriptor, + OperationStartEvent operationStartEvent) {} @Override - public void progress(OperationIdentifier operationIdentifier, OperationProgressEvent operationProgressEvent) { - } + public void progress( + OperationIdentifier operationIdentifier, + OperationProgressEvent operationProgressEvent) {} @Override - public void finished(BuildOperationDescriptor buildOperationDescriptor, OperationFinishEvent operationFinishEvent) { - if (buildOperationDescriptor.getDetails() instanceof RunRootBuildWorkBuildOperationType.Details) { - RunRootBuildWorkBuildOperationType.Details details = (RunRootBuildWorkBuildOperationType.Details) buildOperationDescriptor.getDetails(); + public void finished( + BuildOperationDescriptor buildOperationDescriptor, + OperationFinishEvent operationFinishEvent) { + if (buildOperationDescriptor.getDetails() + instanceof RunRootBuildWorkBuildOperationType.Details) { + RunRootBuildWorkBuildOperationType.Details details = + (RunRootBuildWorkBuildOperationType.Details) + buildOperationDescriptor.getDetails(); long duration = operationFinishEvent.getStartTime() - details.getBuildStartTime(); timeToFirstTask.set(duration); } @@ -118,11 +148,15 @@ public void finished(BuildOperationDescriptor buildOperationDescriptor, Operatio @Override public void close() throws Exception { - writeToFile(getParameters().getOutputFile().getAsFile().get(), timeToFirstTask.longValue()); + writeToFile( + getParameters().getOutputFile().getAsFile().get(), timeToFirstTask.longValue()); } } - public static abstract class BuildOperationDurationRecordingListener implements BuildService, BuildOperationListener, AutoCloseable { + public abstract static class BuildOperationDurationRecordingListener + implements BuildService, + BuildOperationListener, + AutoCloseable { interface Params extends BuildServiceParameters { MapProperty getCapturedBuildOperations(); } @@ -131,14 +165,18 @@ interface Params extends BuildServiceParameters { public BuildOperationDurationRecordingListener() { this.collectors = new ArrayList<>(); - for (Map.Entry entry : getParameters().getCapturedBuildOperations().get().entrySet()) { + for (Map.Entry entry : + getParameters().getCapturedBuildOperations().get().entrySet()) { String operationType = entry.getKey(); File outputFile = entry.getValue(); Class detailsType; try { detailsType = Class.forName(operationType + "$Details"); } catch (ClassNotFoundException e) { - LOGGER.warn("Couldn't find Details subtype for operation type {}", operationType, e); + LOGGER.warn( + "Couldn't find Details subtype for operation type {}", + operationType, + e); continue; } @@ -147,15 +185,19 @@ public BuildOperationDurationRecordingListener() { } @Override - public void started(BuildOperationDescriptor buildOperationDescriptor, OperationStartEvent operationStartEvent) { - } + public void started( + BuildOperationDescriptor buildOperationDescriptor, + OperationStartEvent operationStartEvent) {} @Override - public void progress(OperationIdentifier operationIdentifier, OperationProgressEvent operationProgressEvent) { - } + public void progress( + OperationIdentifier operationIdentifier, + OperationProgressEvent operationProgressEvent) {} @Override - public void finished(BuildOperationDescriptor buildOperationDescriptor, OperationFinishEvent operationFinishEvent) { + public void finished( + BuildOperationDescriptor buildOperationDescriptor, + OperationFinishEvent operationFinishEvent) { Object details = buildOperationDescriptor.getDetails(); if (details == null) { return; @@ -185,7 +227,8 @@ public BuildOperationCollector(Class detailsType, File outputFile) { public void collect(Object details, OperationFinishEvent operationFinishEvent) { if (detailsType.isAssignableFrom(details.getClass())) { - buildOperationTime.addAndGet(operationFinishEvent.getEndTime() - operationFinishEvent.getStartTime()); + buildOperationTime.addAndGet( + operationFinishEvent.getEndTime() - operationFinishEvent.getStartTime()); } } diff --git a/subprojects/build-operations/src/main/java/org/gradle/trace/pid/AbstractPidCollectorBuildService.java b/subprojects/build-operations/src/main/java/org/gradle/trace/pid/AbstractPidCollectorBuildService.java index 95a538e1..1f61d454 100644 --- a/subprojects/build-operations/src/main/java/org/gradle/trace/pid/AbstractPidCollectorBuildService.java +++ b/subprojects/build-operations/src/main/java/org/gradle/trace/pid/AbstractPidCollectorBuildService.java @@ -12,13 +12,23 @@ import java.io.File; -public abstract class AbstractPidCollectorBuildService implements BuildService, OperationCompletionListener { - - public static void registerBuildService(Class buildServiceClass, GradleInternal gradle, File outFile) { - Provider pidCollectorService = gradle.getSharedServices().registerIfAbsent("pidCollector", buildServiceClass, spec -> spec.parameters( - params -> params.getPidFile().set(outFile) - )); - gradle.getServices().get(BuildEventsListenerRegistry.class).onTaskCompletion(pidCollectorService); +public abstract class AbstractPidCollectorBuildService + implements BuildService, + OperationCompletionListener { + + public static void registerBuildService( + Class buildServiceClass, GradleInternal gradle, File outFile) { + Provider pidCollectorService = + gradle.getSharedServices() + .registerIfAbsent( + "pidCollector", + buildServiceClass, + spec -> + spec.parameters( + params -> params.getPidFile().set(outFile))); + gradle.getServices() + .get(BuildEventsListenerRegistry.class) + .onTaskCompletion(pidCollectorService); } public interface Parameters extends BuildServiceParameters { @@ -32,6 +42,5 @@ protected AbstractPidCollectorBuildService() { protected abstract Long getPid(); @Override - public void onFinish(FinishEvent event) { - } + public void onFinish(FinishEvent event) {} } diff --git a/subprojects/build-operations/src/main/java/org/gradle/trace/pid/PidCollector.java b/subprojects/build-operations/src/main/java/org/gradle/trace/pid/PidCollector.java index 2b71d21d..1b5ef591 100644 --- a/subprojects/build-operations/src/main/java/org/gradle/trace/pid/PidCollector.java +++ b/subprojects/build-operations/src/main/java/org/gradle/trace/pid/PidCollector.java @@ -11,14 +11,17 @@ @SuppressWarnings("unused") public class PidCollector { public static void collect(GradleInternal gradle, File outFile) { - // Always write the file, whether we register a build service or not, so we also have a PID file for TAPI model requests. + // Always write the file, whether we register a build service or not, so we also have a PID + // file for TAPI model requests. ProcessEnvironment processEnvironment = gradle.getServices().get(ProcessEnvironment.class); GFileUtils.writeFile(processEnvironment.getPid().toString(), outFile); if (GradleVersion.current().compareTo(GradleVersion.version("6.1")) >= 0) { if (JavaVersion.current().isJava9Compatible()) { - AbstractPidCollectorBuildService.registerBuildService(PidCollectorBuildService.class, gradle, outFile); + AbstractPidCollectorBuildService.registerBuildService( + PidCollectorBuildService.class, gradle, outFile); } else { - AbstractPidCollectorBuildService.registerBuildService(PidCollectorJava8BuildService.class, gradle, outFile); + AbstractPidCollectorBuildService.registerBuildService( + PidCollectorJava8BuildService.class, gradle, outFile); } } } diff --git a/subprojects/build-operations/src/main/java/org/gradle/trace/pid/PidCollectorJava8BuildService.java b/subprojects/build-operations/src/main/java/org/gradle/trace/pid/PidCollectorJava8BuildService.java index e9b92e98..e0a79552 100644 --- a/subprojects/build-operations/src/main/java/org/gradle/trace/pid/PidCollectorJava8BuildService.java +++ b/subprojects/build-operations/src/main/java/org/gradle/trace/pid/PidCollectorJava8BuildService.java @@ -9,19 +9,21 @@ public abstract class PidCollectorJava8BuildService extends AbstractPidCollector @Override protected Long getPid() { try { - // With Gradle 6.6 we can't inject `ProcessEnvironment`, so that is why we access the runtime MXBean here. + // With Gradle 6.6 we can't inject `ProcessEnvironment`, so that is why we access the + // runtime MXBean here. // On Java 9 we use `ProcessHandle` via `PidCollectorBuildService`. RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm"); jvm.setAccessible(true); - sun.management.VMManagement mgmt = - (sun.management.VMManagement) jvm.get(runtime); - java.lang.reflect.Method pid_method = - mgmt.getClass().getDeclaredMethod("getProcessId"); + sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime); + java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId"); pid_method.setAccessible(true); return ((Integer) pid_method.invoke(mgmt)).longValue(); - } catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { + } catch (NoSuchFieldException + | IllegalAccessException + | NoSuchMethodException + | InvocationTargetException e) { throw new RuntimeException(e); } } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/AsynchronousTraceWriter.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/AsynchronousTraceWriter.java index 7a4050b7..a2a35aa9 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/AsynchronousTraceWriter.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/AsynchronousTraceWriter.java @@ -1,13 +1,14 @@ package org.gradle.trace; +import org.gradle.api.logging.Logging; +import org.gradle.internal.UncheckedException; +import org.gradle.trace.stream.AsyncWriter; + import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; -import org.gradle.api.logging.Logging; -import org.gradle.internal.UncheckedException; -import org.gradle.trace.stream.AsyncWriter; public class AsynchronousTraceWriter { @@ -19,11 +20,13 @@ public AsynchronousTraceWriter(File traceFile) { try { if (traceFile.exists()) { if (!traceFile.delete()) { - throw new RuntimeException("Unable to delete the old file " + traceFile.getAbsolutePath()); + throw new RuntimeException( + "Unable to delete the old file " + traceFile.getAbsolutePath()); } } if (!traceFile.createNewFile()) { - throw new RuntimeException("Unable to create a file " + traceFile.getAbsolutePath()); + throw new RuntimeException( + "Unable to create a file " + traceFile.getAbsolutePath()); } } catch (Exception e) { throw new RuntimeException(e); @@ -40,7 +43,8 @@ public void finish() { if (System.getProperty("trace") == null) { return; } - Logging.getLogger(AsynchronousTraceWriter.class).lifecycle("Trace written to file://" + traceFile.getAbsolutePath()); + Logging.getLogger(AsynchronousTraceWriter.class) + .lifecycle("Trace written to file://" + traceFile.getAbsolutePath()); } private void copyResourceToTraceFile(String resourcePath, PrintWriter writer) { @@ -64,8 +68,7 @@ private class TraceEventRenderer implements AsyncWriter.Renderer { @Override public void header(PrintWriter writer) { copyResourceToTraceFile("/trace-header.html", writer); - writer.println("{\n" + - " \"traceEvents\": [\n"); + writer.println("{\n" + " \"traceEvents\": [\n"); } @Override @@ -80,13 +83,14 @@ public void write(TraceEvent value, PrintWriter writer) { @Override public void footer(PrintWriter writer) { - writer.println("],\n" + - " \"displayTimeUnit\": \"ns\",\n" + - " \"systemTraceEvents\": \"SystemTraceData\",\n" + - " \"otherData\": {\n" + - " \"version\": \"My Application v1.0\"\n" + - " }\n" + - "}\n"); + writer.println( + "],\n" + + " \"displayTimeUnit\": \"ns\",\n" + + " \"systemTraceEvents\": \"SystemTraceData\",\n" + + " \"otherData\": {\n" + + " \"version\": \"My Application v1.0\"\n" + + " }\n" + + "}\n"); copyResourceToTraceFile("/trace-footer.html", writer); } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/CountEvent.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/CountEvent.java index 2fd84210..6fdcaeb8 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/CountEvent.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/CountEvent.java @@ -25,7 +25,11 @@ public String toString() { Iterator> itr = info.entrySet().iterator(); while (itr.hasNext()) { Map.Entry entry = itr.next(); - s.append("\"").append(entry.getKey()).append("\": ").append(entry.getValue()).append(""); + s.append("\"") + .append(entry.getKey()) + .append("\": ") + .append(entry.getValue()) + .append(""); s.append(itr.hasNext() ? "," : ""); } s.append("}"); @@ -36,6 +40,8 @@ public String toString() { cname = String.format(", \"cname\": \"%s\"", colorName); } - return String.format("{\"name\": \"%s\", \"ph\": \"C\", \"pid\": 0, \"tid\": %d, \"ts\": %d, \"args\": %s %s}", name, Thread.currentThread().getId(), timestamp, args, cname); + return String.format( + "{\"name\": \"%s\", \"ph\": \"C\", \"pid\": 0, \"tid\": %d, \"ts\": %d, \"args\": %s %s}", + name, Thread.currentThread().getId(), timestamp, args, cname); } } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/DurationEvent.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/DurationEvent.java index 4b1a96d1..75d8be80 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/DurationEvent.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/DurationEvent.java @@ -12,7 +12,12 @@ public class DurationEvent implements TraceEvent { private final Map info; private final String colorName; - public DurationEvent(String name, String category, long timestampNanos, Map info, String colorName) { + public DurationEvent( + String name, + String category, + long timestampNanos, + Map info, + String colorName) { this.name = name; this.category = category; this.threadId = Thread.currentThread().getId(); @@ -34,7 +39,11 @@ public String toString() { Iterator> itr = info.entrySet().iterator(); while (itr.hasNext()) { Map.Entry entry = itr.next(); - s.append("\"").append(entry.getKey()).append("\": \"").append(entry.getValue()).append("\""); + s.append("\"") + .append(entry.getKey()) + .append("\": \"") + .append(entry.getValue()) + .append("\""); s.append(itr.hasNext() ? "," : ""); } s.append("}"); @@ -45,11 +54,12 @@ public String toString() { cname = String.format(", \"cname\": \"%s\"", colorName); } - return String.format("{\"name\": \"%s\", \"cat\": \"%s\", \"ph\": \"X\", \"pid\": 0, \"tid\": %d, \"ts\": %d, \"dur\": %d, \"args\": %s %s}", name, category, threadId, startTimestamp, elapsed, args, cname); + return String.format( + "{\"name\": \"%s\", \"cat\": \"%s\", \"ph\": \"X\", \"pid\": 0, \"tid\": %d, \"ts\": %d, \"dur\": %d, \"args\": %s %s}", + name, category, threadId, startTimestamp, elapsed, args, cname); } public void finished(long timestampNanos) { this.endTimestamp = timestampNanos / 1000; } - } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/GradleTracingPlugin.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/GradleTracingPlugin.java index a313cebc..a321cbf4 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/GradleTracingPlugin.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/GradleTracingPlugin.java @@ -1,7 +1,5 @@ package org.gradle.trace; -import static org.gradle.trace.util.ReflectionUtil.invokerGetter; - import org.gradle.BuildAdapter; import org.gradle.BuildResult; import org.gradle.api.internal.GradleInternal; @@ -15,6 +13,8 @@ import java.io.File; import java.util.HashMap; +import static org.gradle.trace.util.ReflectionUtil.invokerGetter; + public class GradleTracingPlugin { private static final String CATEGORY_PHASE = "BUILD_PHASE"; private static final String PHASE_BUILD = "build duration"; @@ -63,7 +63,10 @@ private long getStartTime() { try { return buildRequestMetaData.getStartTime(); } catch (NoSuchMethodError e) { - return (long) invokerGetter(invokerGetter(buildRequestMetaData, "getBuildTimeClock"), "getStartTime"); + return (long) + invokerGetter( + invokerGetter(buildRequestMetaData, "getBuildTimeClock"), + "getStartTime"); } } } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/TraceEvent.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/TraceEvent.java index 25eb97af..ac85c241 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/TraceEvent.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/TraceEvent.java @@ -1,4 +1,3 @@ package org.gradle.trace; -public interface TraceEvent { -} +public interface TraceEvent {} diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/TraceResult.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/TraceResult.java index b3c55f08..c0ab03e3 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/TraceResult.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/TraceResult.java @@ -28,7 +28,9 @@ public void start(String name, String category, long timestampNanos) { } public void start(String name, String category, long timestampNanos, String colorName) { - events.put(name, new DurationEvent(name, category, timestampNanos, new HashMap<>(), colorName)); + events.put( + name, + new DurationEvent(name, category, timestampNanos, new HashMap<>(), colorName)); } public void finish(String name, long timestampNanos, Map info) { @@ -47,5 +49,4 @@ public void finalizeTraceFile() { traceWriter.finish(); } - } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/BuildOperationListenerAdapter.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/BuildOperationListenerAdapter.java index 46affec9..6e6f90ab 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/BuildOperationListenerAdapter.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/BuildOperationListenerAdapter.java @@ -1,37 +1,45 @@ package org.gradle.trace.listener; -import static org.gradle.util.GradleVersion.version; - import org.gradle.api.invocation.Gradle; import org.gradle.trace.TraceResult; import org.gradle.util.GradleVersion; +import static org.gradle.util.GradleVersion.version; + public interface BuildOperationListenerAdapter { static BuildOperationListenerAdapter create(Gradle gradle, TraceResult traceResult) { GradleVersion gradleVersion = version(gradle.getGradleVersion()).getBaseVersion(); if (inVersionRange(gradleVersion, "3.3", "3.5")) { - return new Gradle33BuildOperationListenerAdapter(gradle, new Gradle33BuildOperationListenerInvocationHandler(traceResult)); + return new Gradle33BuildOperationListenerAdapter( + gradle, new Gradle33BuildOperationListenerInvocationHandler(traceResult)); } if (inVersionRange(gradleVersion, "3.5", "4.0-milestone-2")) { - return new Gradle35BuildOperationListenerAdapter(gradle, new Gradle33BuildOperationListenerInvocationHandler(traceResult)); + return new Gradle35BuildOperationListenerAdapter( + gradle, new Gradle33BuildOperationListenerInvocationHandler(traceResult)); } if (gradleVersion.equals(version("4.0-milestone-2"))) { - return new Gradle35BuildOperationListenerAdapter(gradle, new Gradle40BuildOperationListenerInvocationHandler(traceResult)); + return new Gradle35BuildOperationListenerAdapter( + gradle, new Gradle40BuildOperationListenerInvocationHandler(traceResult)); } if (inVersionRange(gradleVersion, "4.0", "4.7")) { - return new Gradle40BuildOperationListenerAdapter(gradle, new Gradle40BuildOperationListenerInvocationHandler(traceResult)); + return new Gradle40BuildOperationListenerAdapter( + gradle, new Gradle40BuildOperationListenerInvocationHandler(traceResult)); } if (inVersionRange(gradleVersion, "4.7", "5.0")) { - return new Gradle47BuildOperationListenerAdapter(gradle, new Gradle47BuildOperationListenerInvocationHandler(traceResult)); + return new Gradle47BuildOperationListenerAdapter( + gradle, new Gradle47BuildOperationListenerInvocationHandler(traceResult)); } if (gradleVersion.compareTo(version("5.0")) >= 0) { - return new Gradle47BuildOperationListenerAdapter(gradle, new Gradle50BuildOperationListenerInvocationHandler(traceResult)); + return new Gradle47BuildOperationListenerAdapter( + gradle, new Gradle50BuildOperationListenerInvocationHandler(traceResult)); } - throw new IllegalStateException("Gradle version " + gradleVersion + " not supported, 3.3+ required"); + throw new IllegalStateException( + "Gradle version " + gradleVersion + " not supported, 3.3+ required"); } static boolean inVersionRange(GradleVersion gradleVersion, String lower, String upper) { - return gradleVersion.compareTo(version(lower)) >= 0 && gradleVersion.compareTo(version(upper)) < 0; + return gradleVersion.compareTo(version(lower)) >= 0 + && gradleVersion.compareTo(version(upper)) < 0; } void remove(); diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/BuildOperationListenerInvocationHandler.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/BuildOperationListenerInvocationHandler.java index 4a6b7b63..369e21c1 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/BuildOperationListenerInvocationHandler.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/BuildOperationListenerInvocationHandler.java @@ -1,7 +1,5 @@ package org.gradle.trace.listener; -import static org.gradle.trace.util.ReflectionUtil.invokerGetter; - import org.gradle.api.internal.TaskInternal; import org.gradle.trace.TraceResult; import org.gradle.trace.util.TimeUtil; @@ -12,6 +10,8 @@ import java.util.HashMap; import java.util.Map; +import static org.gradle.trace.util.ReflectionUtil.invokerGetter; + public abstract class BuildOperationListenerInvocationHandler implements InvocationHandler { private static final String CATEGORY_OPERATION = "BUILD_OPERATION"; @@ -24,20 +24,28 @@ public BuildOperationListenerInvocationHandler(TraceResult traceResult) { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { switch (method.getName()) { - case "started": { - Object operation = args[0]; - Object startEvent = args[1]; - traceResult.start(getName(operation), CATEGORY_OPERATION, TimeUtil.toNanoTime(getStartTime(startEvent))); - return null; - } - case "finished": { - Object operation = args[0]; - Object finishedEvent = args[1]; - Map info = new HashMap<>(); - withTaskInfo(info, getTask(operation), finishedEvent); - traceResult.finish(getName(operation), TimeUtil.toNanoTime(getEndTime(finishedEvent)), info); - return null; - } + case "started": + { + Object operation = args[0]; + Object startEvent = args[1]; + traceResult.start( + getName(operation), + CATEGORY_OPERATION, + TimeUtil.toNanoTime(getStartTime(startEvent))); + return null; + } + case "finished": + { + Object operation = args[0]; + Object finishedEvent = args[1]; + Map info = new HashMap<>(); + withTaskInfo(info, getTask(operation), finishedEvent); + traceResult.finish( + getName(operation), + TimeUtil.toNanoTime(getEndTime(finishedEvent)), + info); + return null; + } case "hashCode": return hashCode(); case "equals": diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle33BuildOperationListenerAdapter.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle33BuildOperationListenerAdapter.java index 1bcd575f..bcba80e2 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle33BuildOperationListenerAdapter.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle33BuildOperationListenerAdapter.java @@ -15,14 +15,21 @@ public class Gradle33BuildOperationListenerAdapter implements BuildOperationList private GradleInternal gradle; private Object listener; - public Gradle33BuildOperationListenerAdapter(Gradle gradle, InvocationHandler invocationHandler) { + public Gradle33BuildOperationListenerAdapter( + Gradle gradle, InvocationHandler invocationHandler) { this.gradle = (GradleInternal) gradle; register(invocationHandler); } private void register(InvocationHandler invocationHandler) { try { - listener = Proxy.newProxyInstance(gradle.getClass().getClassLoader(), new Class[]{Class.forName("org.gradle.internal.progress.InternalBuildListener")}, invocationHandler); + listener = + Proxy.newProxyInstance( + gradle.getClass().getClassLoader(), + new Class[] { + Class.forName("org.gradle.internal.progress.InternalBuildListener") + }, + invocationHandler); getGlobalListenerManager().addListener(listener); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle33BuildOperationListenerInvocationHandler.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle33BuildOperationListenerInvocationHandler.java index 7eac1ca1..8234ac3a 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle33BuildOperationListenerInvocationHandler.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle33BuildOperationListenerInvocationHandler.java @@ -1,11 +1,12 @@ package org.gradle.trace.listener; -import static org.gradle.trace.util.ReflectionUtil.invokerGetter; - import org.gradle.api.internal.TaskInternal; import org.gradle.trace.TraceResult; -public class Gradle33BuildOperationListenerInvocationHandler extends BuildOperationListenerInvocationHandler { +import static org.gradle.trace.util.ReflectionUtil.invokerGetter; + +public class Gradle33BuildOperationListenerInvocationHandler + extends BuildOperationListenerInvocationHandler { public Gradle33BuildOperationListenerInvocationHandler(TraceResult traceResult) { super(traceResult); @@ -13,16 +14,21 @@ public Gradle33BuildOperationListenerInvocationHandler(TraceResult traceResult) protected String getName(Object operation) { Object details = invokerGetter(operation, "getOperationDescriptor"); - if (details != null && details.getClass().getSimpleName().equals("TaskOperationDescriptor")) { + if (details != null + && details.getClass().getSimpleName().equals("TaskOperationDescriptor")) { return (String) invokerGetter(invokerGetter(details, "getTask"), "getPath"); } - return invokerGetter(operation, "getDisplayName") + " (" + invokerGetter(operation, "getId") + ")"; + return invokerGetter(operation, "getDisplayName") + + " (" + + invokerGetter(operation, "getId") + + ")"; } protected TaskInternal getTask(Object operation) { Object details = invokerGetter(operation, "getOperationDescriptor"); - if (details != null && details.getClass().getSimpleName().equals("TaskOperationDescriptor")) { - return (TaskInternal) invokerGetter(details, "getTask"); + if (details != null + && details.getClass().getSimpleName().equals("TaskOperationDescriptor")) { + return (TaskInternal) invokerGetter(details, "getTask"); } return null; } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle35BuildOperationListenerAdapter.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle35BuildOperationListenerAdapter.java index 49b732dd..19bac39d 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle35BuildOperationListenerAdapter.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle35BuildOperationListenerAdapter.java @@ -10,14 +10,21 @@ public class Gradle35BuildOperationListenerAdapter implements BuildOperationList private GradleInternal gradle; private Object listener; - public Gradle35BuildOperationListenerAdapter(Gradle gradle, InvocationHandler invocationHandler) { + public Gradle35BuildOperationListenerAdapter( + Gradle gradle, InvocationHandler invocationHandler) { this.gradle = (GradleInternal) gradle; register(invocationHandler); } private void register(InvocationHandler invocationHandler) { try { - listener = Proxy.newProxyInstance(gradle.getClass().getClassLoader(), new Class[]{Class.forName("org.gradle.internal.progress.BuildOperationListener")}, invocationHandler); + listener = + Proxy.newProxyInstance( + gradle.getClass().getClassLoader(), + new Class[] { + Class.forName("org.gradle.internal.progress.BuildOperationListener") + }, + invocationHandler); runBuildOperationServiceMethodForListener("addListener"); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); @@ -31,9 +38,15 @@ public void remove() { private void runBuildOperationServiceMethodForListener(String method) { try { - Class boServiceClass = Class.forName("org.gradle.internal.progress.BuildOperationService"); + Class boServiceClass = + Class.forName("org.gradle.internal.progress.BuildOperationService"); Object buildOperationService = gradle.getServices().get(boServiceClass); - buildOperationService.getClass().getMethod(method, Class.forName("org.gradle.internal.progress.BuildOperationListener")).invoke(buildOperationService, listener); + buildOperationService + .getClass() + .getMethod( + method, + Class.forName("org.gradle.internal.progress.BuildOperationListener")) + .invoke(buildOperationService, listener); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle40BuildOperationListenerAdapter.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle40BuildOperationListenerAdapter.java index a08b9f4a..083a5c62 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle40BuildOperationListenerAdapter.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle40BuildOperationListenerAdapter.java @@ -10,14 +10,21 @@ public class Gradle40BuildOperationListenerAdapter implements BuildOperationList private GradleInternal gradle; private Object listener; - public Gradle40BuildOperationListenerAdapter(Gradle gradle, InvocationHandler invocationHandler) { + public Gradle40BuildOperationListenerAdapter( + Gradle gradle, InvocationHandler invocationHandler) { this.gradle = (GradleInternal) gradle; register(invocationHandler); } private void register(InvocationHandler invocationHandler) { try { - listener = Proxy.newProxyInstance(gradle.getClass().getClassLoader(), new Class[]{Class.forName("org.gradle.internal.progress.BuildOperationListener")}, invocationHandler); + listener = + Proxy.newProxyInstance( + gradle.getClass().getClassLoader(), + new Class[] { + Class.forName("org.gradle.internal.progress.BuildOperationListener") + }, + invocationHandler); runBuildOperationServiceMethodForListener("addListener"); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); @@ -28,12 +35,18 @@ private void register(InvocationHandler invocationHandler) { public void remove() { runBuildOperationServiceMethodForListener("removeListener"); } - + private void runBuildOperationServiceMethodForListener(String method) { try { - Class boServiceClass = Class.forName("org.gradle.internal.progress.BuildOperationListenerManager"); + Class boServiceClass = + Class.forName("org.gradle.internal.progress.BuildOperationListenerManager"); Object buildOperationService = gradle.getServices().get(boServiceClass); - buildOperationService.getClass().getMethod(method, Class.forName("org.gradle.internal.progress.BuildOperationListener")).invoke(buildOperationService, listener); + buildOperationService + .getClass() + .getMethod( + method, + Class.forName("org.gradle.internal.progress.BuildOperationListener")) + .invoke(buildOperationService, listener); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle40BuildOperationListenerInvocationHandler.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle40BuildOperationListenerInvocationHandler.java index d5dd4151..bc541707 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle40BuildOperationListenerInvocationHandler.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle40BuildOperationListenerInvocationHandler.java @@ -1,11 +1,12 @@ package org.gradle.trace.listener; -import static org.gradle.trace.util.ReflectionUtil.invokerGetter; - import org.gradle.api.internal.TaskInternal; import org.gradle.trace.TraceResult; -public class Gradle40BuildOperationListenerInvocationHandler extends BuildOperationListenerInvocationHandler { +import static org.gradle.trace.util.ReflectionUtil.invokerGetter; + +public class Gradle40BuildOperationListenerInvocationHandler + extends BuildOperationListenerInvocationHandler { public Gradle40BuildOperationListenerInvocationHandler(TraceResult traceResult) { super(traceResult); @@ -14,7 +15,10 @@ public Gradle40BuildOperationListenerInvocationHandler(TraceResult traceResult) protected String getName(Object operation) { TaskInternal task = getTask(operation); if (task == null) { - return invokerGetter(operation, "getDisplayName") + " (" + invokerGetter(operation, "getId") + ")"; + return invokerGetter(operation, "getDisplayName") + + " (" + + invokerGetter(operation, "getId") + + ")"; } else { return task.getPath(); } @@ -22,13 +26,18 @@ protected String getName(Object operation) { protected TaskInternal getTask(Object operation) { Object details = invokerGetter(operation, "getDetails"); - if (details != null && details.getClass().getName().equals("org.gradle.api.execution.internal.ExecuteTaskBuildOperationDetails")) { + if (details != null + && details.getClass() + .getName() + .equals( + "org.gradle.api.execution.internal.ExecuteTaskBuildOperationDetails")) { return (TaskInternal) invokerGetter(details, "getTask"); } return null; } protected boolean isTaskCacheable(TaskInternal task, Object finishedEvent) { - return (boolean) invokerGetter(invokerGetter(task.getState(), "getTaskOutputCaching"), "isEnabled"); + return (boolean) + invokerGetter(invokerGetter(task.getState(), "getTaskOutputCaching"), "isEnabled"); } } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle47BuildOperationListenerAdapter.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle47BuildOperationListenerAdapter.java index 8fcaa454..af7abdbe 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle47BuildOperationListenerAdapter.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle47BuildOperationListenerAdapter.java @@ -12,13 +12,19 @@ public class Gradle47BuildOperationListenerAdapter implements BuildOperationList private GradleInternal gradle; private BuildOperationListener listener; - public Gradle47BuildOperationListenerAdapter(Gradle gradle, InvocationHandler invocationHandler) { + public Gradle47BuildOperationListenerAdapter( + Gradle gradle, InvocationHandler invocationHandler) { this.gradle = (GradleInternal) gradle; register(invocationHandler); } private void register(InvocationHandler invocationHandler) { - listener = (BuildOperationListener) Proxy.newProxyInstance(gradle.getClass().getClassLoader(), new Class[]{BuildOperationListener.class}, invocationHandler); + listener = + (BuildOperationListener) + Proxy.newProxyInstance( + gradle.getClass().getClassLoader(), + new Class[] {BuildOperationListener.class}, + invocationHandler); getListenerManager().addListener(listener); } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle47BuildOperationListenerInvocationHandler.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle47BuildOperationListenerInvocationHandler.java index c74b039c..b56246bd 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle47BuildOperationListenerInvocationHandler.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle47BuildOperationListenerInvocationHandler.java @@ -1,14 +1,15 @@ package org.gradle.trace.listener; -import static org.gradle.trace.util.ReflectionUtil.invokerGetter; - import org.gradle.api.internal.TaskInternal; import org.gradle.internal.operations.BuildOperationDescriptor; import org.gradle.internal.operations.OperationFinishEvent; import org.gradle.internal.operations.OperationStartEvent; import org.gradle.trace.TraceResult; -public class Gradle47BuildOperationListenerInvocationHandler extends BuildOperationListenerInvocationHandler { +import static org.gradle.trace.util.ReflectionUtil.invokerGetter; + +public class Gradle47BuildOperationListenerInvocationHandler + extends BuildOperationListenerInvocationHandler { public Gradle47BuildOperationListenerInvocationHandler(TraceResult traceResult) { super(traceResult); @@ -26,7 +27,11 @@ protected String getName(Object operation) { protected TaskInternal getTask(Object operation) { Object details = invokerGetter(operation, "getDetails"); - if (details != null && details.getClass().getName().equals("org.gradle.api.execution.internal.ExecuteTaskBuildOperationDetails")) { + if (details != null + && details.getClass() + .getName() + .equals( + "org.gradle.api.execution.internal.ExecuteTaskBuildOperationDetails")) { return (TaskInternal) invokerGetter(details, "getTask"); } return null; @@ -43,6 +48,7 @@ protected long getEndTime(Object result) { } protected boolean isTaskCacheable(TaskInternal task, Object finishedEvent) { - return (boolean) invokerGetter(invokerGetter(task.getState(), "getTaskOutputCaching"), "isEnabled"); + return (boolean) + invokerGetter(invokerGetter(task.getState(), "getTaskOutputCaching"), "isEnabled"); } } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle50BuildOperationListenerInvocationHandler.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle50BuildOperationListenerInvocationHandler.java index 407bd5ee..39bb4f7a 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle50BuildOperationListenerInvocationHandler.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/listener/Gradle50BuildOperationListenerInvocationHandler.java @@ -1,7 +1,5 @@ package org.gradle.trace.listener; -import static org.gradle.trace.util.ReflectionUtil.invokerGetter; - import org.gradle.api.internal.TaskInternal; import org.gradle.api.internal.tasks.execution.ExecuteTaskBuildOperationDetails; import org.gradle.api.internal.tasks.execution.ExecuteTaskBuildOperationType; @@ -10,7 +8,10 @@ import org.gradle.internal.operations.OperationStartEvent; import org.gradle.trace.TraceResult; -public class Gradle50BuildOperationListenerInvocationHandler extends BuildOperationListenerInvocationHandler { +import static org.gradle.trace.util.ReflectionUtil.invokerGetter; + +public class Gradle50BuildOperationListenerInvocationHandler + extends BuildOperationListenerInvocationHandler { public Gradle50BuildOperationListenerInvocationHandler(TraceResult traceResult) { super(traceResult); @@ -48,7 +49,9 @@ protected long getEndTime(Object result) { protected boolean isTaskCacheable(TaskInternal task, Object finishedEvent) { Object result = ((OperationFinishEvent) finishedEvent).getResult(); if (result instanceof ExecuteTaskBuildOperationType.Result) { - return ((ExecuteTaskBuildOperationType.Result) result).getCachingDisabledReasonCategory() == null; + return ((ExecuteTaskBuildOperationType.Result) result) + .getCachingDisabledReasonCategory() + == null; } throw new UnsupportedOperationException(); } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/monitoring/GCMonitoring.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/monitoring/GCMonitoring.java index e484863b..b981a090 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/monitoring/GCMonitoring.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/monitoring/GCMonitoring.java @@ -8,6 +8,7 @@ import javax.management.NotificationEmitter; import javax.management.NotificationListener; import javax.management.openmbean.CompositeData; + import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryUsage; @@ -23,7 +24,8 @@ public class GCMonitoring { private final long jvmStartTime; private final long maxHeap; - private final Map gcNotificationListeners = new HashMap<>(); + private final Map gcNotificationListeners = + new HashMap<>(); public GCMonitoring() { this.garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans(); @@ -34,35 +36,52 @@ public GCMonitoring() { public void start(TraceResult traceResult) { for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) { NotificationEmitter emitter = (NotificationEmitter) garbageCollectorMXBean; - NotificationListener gcNotificationListener = (notification, handback) -> { - if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) { - GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData()); - //get all the info and pretty print it - long duration = info.getGcInfo().getDuration(); - String gctype = info.getGcAction(); - Map args = new HashMap<>(); - args.put("type", gctype); + NotificationListener gcNotificationListener = + (notification, handback) -> { + if (notification + .getType() + .equals( + GarbageCollectionNotificationInfo + .GARBAGE_COLLECTION_NOTIFICATION)) { + GarbageCollectionNotificationInfo info = + GarbageCollectionNotificationInfo.from( + (CompositeData) notification.getUserData()); + // get all the info and pretty print it + long duration = info.getGcInfo().getDuration(); + String gctype = info.getGcAction(); + Map args = new HashMap<>(); + args.put("type", gctype); - String colorName = "good"; - if (gctype.equals("end of major GC")) { - colorName = "terrible"; - } + String colorName = "good"; + if (gctype.equals("end of major GC")) { + colorName = "terrible"; + } - traceResult.start("GC" + info.getGcInfo().getId(), GARBAGE_COLLECTION, TimeUtil.toNanoTime(jvmStartTime + info.getGcInfo().getStartTime()), colorName); - traceResult.finish("GC" + info.getGcInfo().getId(), TimeUtil.toNanoTime(jvmStartTime + info.getGcInfo().getEndTime()), args); - Map pools = info.getGcInfo().getMemoryUsageAfterGc(); - long unallocatedHeap = maxHeap; - HashMap gcInfo = new LinkedHashMap<>(); - for (String pool : pools.keySet()) { - MemoryUsage usage = pools.get(pool); - gcInfo.put(pool, (double) usage.getUsed()); - unallocatedHeap -= usage.getUsed(); - } - gcInfo.put("unallocated", (double) unallocatedHeap); + traceResult.start( + "GC" + info.getGcInfo().getId(), + GARBAGE_COLLECTION, + TimeUtil.toNanoTime( + jvmStartTime + info.getGcInfo().getStartTime()), + colorName); + traceResult.finish( + "GC" + info.getGcInfo().getId(), + TimeUtil.toNanoTime( + jvmStartTime + info.getGcInfo().getEndTime()), + args); + Map pools = + info.getGcInfo().getMemoryUsageAfterGc(); + long unallocatedHeap = maxHeap; + HashMap gcInfo = new LinkedHashMap<>(); + for (String pool : pools.keySet()) { + MemoryUsage usage = pools.get(pool); + gcInfo.put(pool, (double) usage.getUsed()); + unallocatedHeap -= usage.getUsed(); + } + gcInfo.put("unallocated", (double) unallocatedHeap); - traceResult.count("heap" + info.getGcInfo().getId(), "heap", gcInfo); - } - }; + traceResult.count("heap" + info.getGcInfo().getId(), "heap", gcInfo); + } + }; emitter.addNotificationListener(gcNotificationListener, null, null); gcNotificationListeners.put(garbageCollectorMXBean, gcNotificationListener); } @@ -72,7 +91,8 @@ public void stop() { for (GarbageCollectorMXBean garbageCollectorMXBean : gcNotificationListeners.keySet()) { NotificationEmitter emitter = (NotificationEmitter) garbageCollectorMXBean; try { - emitter.removeNotificationListener(gcNotificationListeners.get(garbageCollectorMXBean)); + emitter.removeNotificationListener( + gcNotificationListeners.get(garbageCollectorMXBean)); } catch (ListenerNotFoundException e) { } } diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/monitoring/SystemMonitoring.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/monitoring/SystemMonitoring.java index bf2a05e2..6a8351b6 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/monitoring/SystemMonitoring.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/monitoring/SystemMonitoring.java @@ -11,29 +11,35 @@ public class SystemMonitoring { - private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); + private final ScheduledExecutorService scheduledExecutorService = + Executors.newSingleThreadScheduledExecutor(); private final OperatingSystemMXBean operatingSystemMXBean; private int sysPollCount = 0; public SystemMonitoring() { - this.operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); + this.operatingSystemMXBean = + (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); } public void start(TraceResult traceResult) { - scheduledExecutorService.scheduleAtFixedRate(() -> { - HashMap cpuStats = new HashMap<>(); - double pcpu = operatingSystemMXBean.getProcessCpuLoad() * 100; - double scpu = operatingSystemMXBean.getSystemCpuLoad() * 100; - - if (!Double.isNaN(pcpu) && !Double.isNaN(scpu)) { - cpuStats.put("process_cpu_used", pcpu); - cpuStats.put("non_process_cpu_used", scpu - pcpu); - - traceResult.count("cpu" + sysPollCount, "cpu", cpuStats); - } - - sysPollCount++; - }, 0, 500, TimeUnit.MILLISECONDS); + scheduledExecutorService.scheduleAtFixedRate( + () -> { + HashMap cpuStats = new HashMap<>(); + double pcpu = operatingSystemMXBean.getProcessCpuLoad() * 100; + double scpu = operatingSystemMXBean.getSystemCpuLoad() * 100; + + if (!Double.isNaN(pcpu) && !Double.isNaN(scpu)) { + cpuStats.put("process_cpu_used", pcpu); + cpuStats.put("non_process_cpu_used", scpu - pcpu); + + traceResult.count("cpu" + sysPollCount, "cpu", cpuStats); + } + + sysPollCount++; + }, + 0, + 500, + TimeUnit.MILLISECONDS); } public void stop() { diff --git a/subprojects/chrome-trace/src/main/java/org/gradle/trace/stream/AsyncWriter.java b/subprojects/chrome-trace/src/main/java/org/gradle/trace/stream/AsyncWriter.java index 507c74d4..0d1f0b33 100644 --- a/subprojects/chrome-trace/src/main/java/org/gradle/trace/stream/AsyncWriter.java +++ b/subprojects/chrome-trace/src/main/java/org/gradle/trace/stream/AsyncWriter.java @@ -8,9 +8,7 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -/** - * Writes (immutable) values of type {@link T} to a file. - */ +/** Writes (immutable) values of type {@link T} to a file. */ public class AsyncWriter { private final Object EOS = new Object(); private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); @@ -48,7 +46,8 @@ public void stop() { private void run() { try { - try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(outPath, StandardCharsets.UTF_8))) { + try (PrintWriter writer = + new PrintWriter(Files.newBufferedWriter(outPath, StandardCharsets.UTF_8))) { renderer.header(writer); while (true) { Object next = eventQueue.take(); @@ -66,12 +65,10 @@ private void run() { } public interface Renderer { - default void header(PrintWriter writer) { - } + default void header(PrintWriter writer) {} void write(T value, PrintWriter writer); - default void footer(PrintWriter writer) { - } + default void footer(PrintWriter writer) {} } } diff --git a/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Client.java b/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Client.java index dc375f85..4c8243f8 100644 --- a/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Client.java +++ b/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Client.java @@ -5,9 +5,7 @@ import java.net.Socket; import java.time.Duration; -/** - * A singleton that runs inside a client process to communicate with the controller process. - */ +/** A singleton that runs inside a client process to communicate with the controller process. */ public class Client { public static final Client INSTANCE = new Client(); diff --git a/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Message.java b/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Message.java index 9a1b0d9d..b209ca93 100644 --- a/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Message.java +++ b/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Message.java @@ -1,4 +1,3 @@ package org.gradle.profiler.client.protocol; -public class Message { -} +public class Message {} diff --git a/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Serializer.java b/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Serializer.java index 090916ec..ea108870 100644 --- a/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Serializer.java +++ b/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Serializer.java @@ -67,26 +67,29 @@ private RuntimeException couldNotWrite(IOException e) { public T receive(Class type, Duration timeout) { BlockingQueue queue = new LinkedBlockingQueue<>(); - Thread reader = new Thread(() -> { - try { - Object result; - try { - result = receive(); - } catch (RuntimeException e) { - result = e; - } - queue.put(result); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - }); + Thread reader = + new Thread( + () -> { + try { + Object result; + try { + result = receive(); + } catch (RuntimeException e) { + result = e; + } + queue.put(result); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + }); reader.start(); Object result; try { result = queue.poll(timeout.toMillis(), TimeUnit.MILLISECONDS); if (result == null) { reader.interrupt(); - throw new IllegalStateException(String.format("Timeout waiting to receive message from %s.", peerName)); + throw new IllegalStateException( + String.format("Timeout waiting to receive message from %s.", peerName)); } reader.join(); } catch (InterruptedException e) { @@ -96,7 +99,8 @@ public T receive(Class type, Duration timeout) { throw (RuntimeException) result; } if (result == NULL) { - throw new IllegalStateException(String.format("Connection to %s has closed.", peerName)); + throw new IllegalStateException( + String.format("Connection to %s has closed.", peerName)); } return type.cast(result); } @@ -126,7 +130,8 @@ private Object receive() { String gradleHome = connection.readString(); return new ConnectionParameters(new File(gradleHome)); default: - throw new RuntimeException(String.format("Received unexpected message from %s.", peerName)); + throw new RuntimeException( + String.format("Received unexpected message from %s.", peerName)); } } catch (IOException e) { throw new RuntimeException(String.format("Could not read from %s.", peerName), e); diff --git a/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Server.java b/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Server.java index 4ebe6979..56fbb395 100644 --- a/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Server.java +++ b/subprojects/client-protocol/src/main/java/org/gradle/profiler/client/protocol/Server.java @@ -12,9 +12,7 @@ import java.util.ArrayList; import java.util.List; -/** - * An endpoint for communicating with a single client process. - */ +/** An endpoint for communicating with a single client process. */ public class Server implements Closeable { private final ServerSocketChannel serverSocketChannel; @@ -31,7 +29,10 @@ public Server(String peerName) { selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (IOException e) { - throw new RuntimeException(String.format("Could not start listening for incoming %s connections.", peerName), e); + throw new RuntimeException( + String.format( + "Could not start listening for incoming %s connections.", peerName), + e); } } @@ -47,14 +48,18 @@ public ServerConnection waitForIncoming(Duration timeout) { try { int keys = selector.select(timeout.toMillis()); if (keys != 1) { - throw new IllegalStateException(String.format("Timeout waiting for incoming connection from %s.", peerName)); + throw new IllegalStateException( + String.format( + "Timeout waiting for incoming connection from %s.", peerName)); } SocketChannel channel = serverSocketChannel.accept(); - ServerConnection connection = new ServerConnection(peerName, new Connection(channel.socket())); + ServerConnection connection = + new ServerConnection(peerName, new Connection(channel.socket())); connections.add(connection); return connection; } catch (IOException e) { - throw new RuntimeException(String.format("Could not receive incoming connection from %s.", peerName), e); + throw new RuntimeException( + String.format("Could not receive incoming connection from %s.", peerName), e); } } diff --git a/subprojects/heap-dump/src/main/java/org/gradle/trace/heapdump/HeapDump.java b/subprojects/heap-dump/src/main/java/org/gradle/trace/heapdump/HeapDump.java index 54f44879..7c1061a3 100644 --- a/subprojects/heap-dump/src/main/java/org/gradle/trace/heapdump/HeapDump.java +++ b/subprojects/heap-dump/src/main/java/org/gradle/trace/heapdump/HeapDump.java @@ -12,6 +12,7 @@ import org.gradle.tooling.events.OperationCompletionListener; import javax.management.MBeanServer; + import java.io.Closeable; import java.io.File; import java.io.IOException; @@ -20,17 +21,27 @@ public class HeapDump { public HeapDump(GradleInternal gradle, File baseFile) { - Provider listenerProvider = gradle.getSharedServices().registerIfAbsent("heap-dump-at-end", HeapDumpService.class, spec -> { - spec.getParameters().getBaseFile().set(baseFile.getAbsolutePath()); - }); - gradle.getServices().get(BuildEventsListenerRegistry.class).onTaskCompletion(listenerProvider); + Provider listenerProvider = + gradle.getSharedServices() + .registerIfAbsent( + "heap-dump-at-end", + HeapDumpService.class, + spec -> { + spec.getParameters() + .getBaseFile() + .set(baseFile.getAbsolutePath()); + }); + gradle.getServices() + .get(BuildEventsListenerRegistry.class) + .onTaskCompletion(listenerProvider); } interface Params extends BuildServiceParameters { Property getBaseFile(); } - public static abstract class HeapDumpService implements OperationCompletionListener, Closeable, BuildService { + public abstract static class HeapDumpService + implements OperationCompletionListener, Closeable, BuildService { static int counter = 0; @Override @@ -41,10 +52,19 @@ public void onFinish(FinishEvent event) { @Override public void close() { try { - File dumpFile = new File(getParameters().getBaseFile().get() + "-heap-" + (++counter) + ".hprof"); + File dumpFile = + new File( + getParameters().getBaseFile().get() + + "-heap-" + + (++counter) + + ".hprof"); dumpFile.getParentFile().mkdirs(); MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy(server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class); + HotSpotDiagnosticMXBean mxBean = + ManagementFactory.newPlatformMXBeanProxy( + server, + "com.sun.management:type=HotSpotDiagnostic", + HotSpotDiagnosticMXBean.class); mxBean.dumpHeap(dumpFile.getAbsolutePath(), true); } catch (IOException e) { throw UncheckedException.throwAsUncheckedException(e); diff --git a/subprojects/instrumentation-support/src/main/java/org/gradle/profiler/studio/instrumented/Interceptor.java b/subprojects/instrumentation-support/src/main/java/org/gradle/profiler/studio/instrumented/Interceptor.java index 6fb382c0..376a1471 100644 --- a/subprojects/instrumentation-support/src/main/java/org/gradle/profiler/studio/instrumented/Interceptor.java +++ b/subprojects/instrumentation-support/src/main/java/org/gradle/profiler/studio/instrumented/Interceptor.java @@ -11,30 +11,26 @@ import java.time.Duration; import java.util.concurrent.atomic.AtomicInteger; -/** - * Injected into Studio and called from instrumented classes. - */ +/** Injected into Studio and called from instrumented classes. */ public class Interceptor { private static final AtomicInteger COUNTER = new AtomicInteger(); static ConnectionParameters connectionParameters; - /** - * Called when creating a connection. - */ + /** Called when creating a connection. */ public static void onConnect(DefaultGradleConnector connector) { System.out.println("* Creating project connection"); if (connectionParameters == null) { - connectionParameters = Client.INSTANCE.receiveConnectionParameters(Duration.ofSeconds(60)); + connectionParameters = + Client.INSTANCE.receiveConnectionParameters(Duration.ofSeconds(60)); } System.out.println("* Using Gradle home: " + connectionParameters.getGradleInstallation()); connector.useInstallation(connectionParameters.getGradleInstallation()); } - /** - * Called immediately prior to starting an operation. - */ - public static ResultHandler onStartOperation(AbstractLongRunningOperation operation, ResultHandler handler) { + /** Called immediately prior to starting an operation. */ + public static ResultHandler onStartOperation( + AbstractLongRunningOperation operation, ResultHandler handler) { System.out.println("* Starting tooling API operation " + operation); int id = COUNTER.incrementAndGet(); diff --git a/subprojects/studio-agent/src/main/java/org/gradle/profiler/studio/agent/Agent.java b/subprojects/studio-agent/src/main/java/org/gradle/profiler/studio/agent/Agent.java index 15a16b8e..e8619817 100644 --- a/subprojects/studio-agent/src/main/java/org/gradle/profiler/studio/agent/Agent.java +++ b/subprojects/studio-agent/src/main/java/org/gradle/profiler/studio/agent/Agent.java @@ -29,8 +29,10 @@ public static void premain(String agentArgs, Instrumentation inst) { } private static class InstrumentingTransformer implements ClassFileTransformer { - static final Type INTERCEPTOR_TYPE = Type.getObjectType("org/gradle/profiler/studio/instrumented/Interceptor"); - static final Type DEFAULT_GRADLE_CONNECTOR = Type.getObjectType("org/gradle/tooling/internal/consumer/DefaultGradleConnector"); + static final Type INTERCEPTOR_TYPE = + Type.getObjectType("org/gradle/profiler/studio/instrumented/Interceptor"); + static final Type DEFAULT_GRADLE_CONNECTOR = + Type.getObjectType("org/gradle/tooling/internal/consumer/DefaultGradleConnector"); private boolean supportClassesInjected; private final Path supportClassesJar; @@ -40,8 +42,14 @@ public InstrumentingTransformer(Path supportClassesJar) { } @Override - public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] originalByteCode) { - if (className.equals("org/gradle/tooling/internal/consumer/DefaultPhasedBuildActionExecuter")) { + public byte[] transform( + ClassLoader loader, + String className, + Class classBeingRedefined, + ProtectionDomain protectionDomain, + byte[] originalByteCode) { + if (className.equals( + "org/gradle/tooling/internal/consumer/DefaultPhasedBuildActionExecuter")) { maybeInjectSupportClasses(loader); return instrumentBuildActionExecuter(originalByteCode); } @@ -57,32 +65,47 @@ private byte[] instrumentGradleConnector(byte[] originalByteCode) { Type projectConnection = Type.getObjectType("org/gradle/tooling/ProjectConnection"); String connectMethodDescriptor = Type.getMethodDescriptor(projectConnection); - String connectDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE, DEFAULT_GRADLE_CONNECTOR); + String connectDescriptor = + Type.getMethodDescriptor(Type.VOID_TYPE, DEFAULT_GRADLE_CONNECTOR); ClassReader reader = new ClassReader(originalByteCode); ClassWriter writer = new ClassWriter(0); - ClassVisitor visitor = new ClassVisitor(Opcodes.ASM8, writer) { - @Override - public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { - MethodVisitor methodVisitor = super.visitMethod(access, name, descriptor, signature, exceptions); - if (name.equals("connect") && descriptor.equals(connectMethodDescriptor)) { - return new MethodVisitor(Opcodes.ASM8, methodVisitor) { - @Override - public void visitCode() { - super.visitCode(); - visitVarInsn(Opcodes.ALOAD, 0); - visitMethodInsn(Opcodes.INVOKESTATIC, INTERCEPTOR_TYPE.getInternalName(), "onConnect", connectDescriptor, false); + ClassVisitor visitor = + new ClassVisitor(Opcodes.ASM8, writer) { + @Override + public MethodVisitor visitMethod( + int access, + String name, + String descriptor, + String signature, + String[] exceptions) { + MethodVisitor methodVisitor = + super.visitMethod( + access, name, descriptor, signature, exceptions); + if (name.equals("connect") + && descriptor.equals(connectMethodDescriptor)) { + return new MethodVisitor(Opcodes.ASM8, methodVisitor) { + @Override + public void visitCode() { + super.visitCode(); + visitVarInsn(Opcodes.ALOAD, 0); + visitMethodInsn( + Opcodes.INVOKESTATIC, + INTERCEPTOR_TYPE.getInternalName(), + "onConnect", + connectDescriptor, + false); + } + + @Override + public void visitMaxs(int maxStack, int maxLocals) { + super.visitMaxs(Math.max(1, maxStack), maxLocals); + } + }; } - - @Override - public void visitMaxs(int maxStack, int maxLocals) { - super.visitMaxs(Math.max(1, maxStack), maxLocals); - } - }; - } - return methodVisitor; - } - }; + return methodVisitor; + } + }; reader.accept(visitor, 0); return writer.toByteArray(); @@ -92,36 +115,52 @@ private byte[] instrumentBuildActionExecuter(byte[] originalByteCode) { System.out.println("* Instrumenting BuildExecuter"); Type resultHandler = Type.getObjectType("org/gradle/tooling/ResultHandler"); - Type abstractHandlerType = Type.getObjectType("org/gradle/tooling/internal/consumer/AbstractLongRunningOperation"); + Type abstractHandlerType = + Type.getObjectType( + "org/gradle/tooling/internal/consumer/AbstractLongRunningOperation"); String runMethodDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE, resultHandler); - String startOperationDescriptor = Type.getMethodDescriptor(resultHandler, abstractHandlerType, resultHandler); + String startOperationDescriptor = + Type.getMethodDescriptor(resultHandler, abstractHandlerType, resultHandler); ClassReader reader = new ClassReader(originalByteCode); ClassWriter writer = new ClassWriter(0); - ClassVisitor visitor = new ClassVisitor(Opcodes.ASM8, writer) { - @Override - public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { - MethodVisitor methodVisitor = super.visitMethod(access, name, descriptor, signature, exceptions); - if (name.equals("run") && descriptor.equals(runMethodDescriptor)) { - return new MethodVisitor(Opcodes.ASM8, methodVisitor) { - @Override - public void visitCode() { - super.visitCode(); - visitVarInsn(Opcodes.ALOAD, 0); - visitVarInsn(Opcodes.ALOAD, 1); - visitMethodInsn(Opcodes.INVOKESTATIC, INTERCEPTOR_TYPE.getInternalName(), "onStartOperation", startOperationDescriptor, false); - visitVarInsn(Opcodes.ASTORE, 1); + ClassVisitor visitor = + new ClassVisitor(Opcodes.ASM8, writer) { + @Override + public MethodVisitor visitMethod( + int access, + String name, + String descriptor, + String signature, + String[] exceptions) { + MethodVisitor methodVisitor = + super.visitMethod( + access, name, descriptor, signature, exceptions); + if (name.equals("run") && descriptor.equals(runMethodDescriptor)) { + return new MethodVisitor(Opcodes.ASM8, methodVisitor) { + @Override + public void visitCode() { + super.visitCode(); + visitVarInsn(Opcodes.ALOAD, 0); + visitVarInsn(Opcodes.ALOAD, 1); + visitMethodInsn( + Opcodes.INVOKESTATIC, + INTERCEPTOR_TYPE.getInternalName(), + "onStartOperation", + startOperationDescriptor, + false); + visitVarInsn(Opcodes.ASTORE, 1); + } + + @Override + public void visitMaxs(int maxStack, int maxLocals) { + super.visitMaxs(Math.max(2, maxStack), maxLocals); + } + }; } - - @Override - public void visitMaxs(int maxStack, int maxLocals) { - super.visitMaxs(Math.max(2, maxStack), maxLocals); - } - }; - } - return methodVisitor; - } - }; + return methodVisitor; + } + }; reader.accept(visitor, 0); return writer.toByteArray(); @@ -143,7 +182,11 @@ private synchronized void maybeInjectSupportClasses(ClassLoader loader) { break; } if (entry.getName().endsWith(".class")) { - injectClass(loader, entry.getName().substring(0, entry.getName().length() - 6), entry.getSize(), inputStream); + injectClass( + loader, + entry.getName().substring(0, entry.getName().length() - 6), + entry.getSize(), + inputStream); } } } @@ -154,7 +197,9 @@ private synchronized void maybeInjectSupportClasses(ClassLoader loader) { supportClassesInjected = true; } - private static void injectClass(ClassLoader loader, String internalName, long length, InputStream inputStream) throws IOException { + private static void injectClass( + ClassLoader loader, String internalName, long length, InputStream inputStream) + throws IOException { byte[] bytecode = new byte[(int) length]; int remaining = bytecode.length; while (remaining > 0) { @@ -164,7 +209,8 @@ private static void injectClass(ClassLoader loader, String internalName, long le } remaining -= nread; } - Unsafe.getUnsafe().defineClass(internalName, bytecode, 0, bytecode.length, loader, null); + Unsafe.getUnsafe() + .defineClass(internalName, bytecode, 0, bytecode.length, loader, null); } } } From 703406afabaa9b0cffed1f243e8af847793e2a3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=B3r=C3=A1nt=20Pint=C3=A9r?= Date: Mon, 8 Feb 2021 22:33:35 +0100 Subject: [PATCH 3/3] Format imports for Groovy --- build.gradle.kts | 2 +- buildSrc/src/main/kotlin/profiler.java-library.gradle.kts | 5 +++++ subprojects/client-protocol/build.gradle.kts | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 10dcd1af..8fa2341b 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -6,8 +6,8 @@ import io.sdkman.vendors.tasks.SdkmanVendorBaseTask import java.net.URI plugins { - id("profiler.java-library") groovy + id("profiler.java-library") application `maven-publish` id("profiler.publication") diff --git a/buildSrc/src/main/kotlin/profiler.java-library.gradle.kts b/buildSrc/src/main/kotlin/profiler.java-library.gradle.kts index fa0d6163..60c56f70 100644 --- a/buildSrc/src/main/kotlin/profiler.java-library.gradle.kts +++ b/buildSrc/src/main/kotlin/profiler.java-library.gradle.kts @@ -22,6 +22,11 @@ spotless { importOrder("", "javax", "java", "\\#") removeUnusedImports() } + pluginManager.withPlugin("groovy") { + groovy { + importOrder("", "groovy", "javax", "java", "\\#") + } + } } project.extensions.create("versions") diff --git a/subprojects/client-protocol/build.gradle.kts b/subprojects/client-protocol/build.gradle.kts index a132fb2a..3648685c 100644 --- a/subprojects/client-protocol/build.gradle.kts +++ b/subprojects/client-protocol/build.gradle.kts @@ -1,6 +1,6 @@ plugins { - id("profiler.embedded-library") id("groovy") + id("profiler.embedded-library") id("profiler.publication") }