-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
AbstractGradleExecuter.java
1699 lines (1463 loc) · 58.7 KB
/
AbstractGradleExecuter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.integtests.fixtures.executer;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharSource;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import org.gradle.api.Action;
import org.gradle.api.JavaVersion;
import org.gradle.api.UncheckedIOException;
import org.gradle.api.internal.artifacts.ivyservice.ArtifactCachesProvider;
import org.gradle.api.internal.initialization.DefaultClassLoaderScope;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.logging.configuration.ConsoleOutput;
import org.gradle.api.logging.configuration.WarningMode;
import org.gradle.integtests.fixtures.RepoScriptBlockUtil;
import org.gradle.integtests.fixtures.daemon.DaemonLogsAnalyzer;
import org.gradle.integtests.fixtures.validation.ValidationServicesFixture;
import org.gradle.internal.ImmutableActionSet;
import org.gradle.internal.MutableActionSet;
import org.gradle.internal.UncheckedException;
import org.gradle.internal.featurelifecycle.LoggingDeprecatedFeatureHandler;
import org.gradle.internal.jvm.Jvm;
import org.gradle.internal.jvm.inspection.JvmVersionDetector;
import org.gradle.internal.logging.LoggingManagerInternal;
import org.gradle.internal.logging.services.DefaultLoggingManagerFactory;
import org.gradle.internal.logging.services.LoggingServiceRegistry;
import org.gradle.internal.nativeintegration.console.TestOverrideConsoleDetector;
import org.gradle.internal.nativeintegration.services.NativeServices;
import org.gradle.internal.service.ServiceRegistry;
import org.gradle.internal.service.ServiceRegistryBuilder;
import org.gradle.internal.service.scopes.GlobalScopeServices;
import org.gradle.launcher.cli.DefaultCommandLineActionFactory;
import org.gradle.launcher.daemon.configuration.DaemonBuildOptions;
import org.gradle.process.internal.streams.SafeStreams;
import org.gradle.test.fixtures.ResettableExpectations;
import org.gradle.test.fixtures.file.TestDirectoryProvider;
import org.gradle.test.fixtures.file.TestFile;
import org.gradle.testfixtures.internal.NativeServicesTestFixture;
import org.gradle.util.GradleVersion;
import org.gradle.util.internal.ClosureBackedAction;
import org.gradle.util.internal.CollectionUtils;
import org.gradle.util.internal.GFileUtils;
import org.gradle.util.internal.TextUtil;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.joining;
import static org.gradle.api.internal.artifacts.BaseRepositoryFactory.PLUGIN_PORTAL_OVERRIDE_URL_PROPERTY;
import static org.gradle.integtests.fixtures.RepoScriptBlockUtil.gradlePluginRepositoryMirrorUrl;
import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.DAEMON;
import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.FOREGROUND;
import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.NOT_DEFINED;
import static org.gradle.integtests.fixtures.executer.AbstractGradleExecuter.CliDaemonArgument.NO_DAEMON;
import static org.gradle.integtests.fixtures.executer.OutputScrapingExecutionResult.STACK_TRACE_ELEMENT;
import static org.gradle.internal.service.scopes.DefaultGradleUserHomeScopeServiceRegistry.REUSE_USER_HOME_SERVICES;
import static org.gradle.util.internal.CollectionUtils.collect;
import static org.gradle.util.internal.CollectionUtils.join;
public abstract class AbstractGradleExecuter implements GradleExecuter, ResettableExpectations {
protected static final ServiceRegistry GLOBAL_SERVICES = ServiceRegistryBuilder.builder()
.displayName("Global services")
.parent(newCommandLineProcessLogging())
.parent(NativeServicesTestFixture.getInstance())
.parent(ValidationServicesFixture.getServices())
.provider(new GlobalScopeServices(true))
.build();
private static final JvmVersionDetector JVM_VERSION_DETECTOR = GLOBAL_SERVICES.get(JvmVersionDetector.class);
protected final static Set<String> PROPAGATED_SYSTEM_PROPERTIES = Sets.newHashSet();
// TODO - don't use statics to communicate between the test runner and executer
public static void propagateSystemProperty(String name) {
PROPAGATED_SYSTEM_PROPERTIES.add(name);
}
public static void doNotPropagateSystemProperty(String name) {
PROPAGATED_SYSTEM_PROPERTIES.remove(name);
}
private static final String DEBUG_SYSPROP = "org.gradle.integtest.debug";
private static final String LAUNCHER_DEBUG_SYSPROP = "org.gradle.integtest.launcher.debug";
private static final String PROFILE_SYSPROP = "org.gradle.integtest.profile";
protected static final List<String> DEBUG_ARGS = ImmutableList.of(
"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005"
);
private final Logger logger;
protected final IntegrationTestBuildContext buildContext;
private final Set<File> isolatedDaemonBaseDirs = new HashSet<>();
private final Set<File> daemonCrashLogsBeforeTest;
private final Set<GradleHandle> running = new HashSet<>();
private final List<ExecutionResult> results = new ArrayList<>();
private final List<String> args = new ArrayList<>();
private final List<String> tasks = new ArrayList<>();
private boolean allowExtraLogging = true;
protected ConsoleAttachment consoleAttachment = ConsoleAttachment.NOT_ATTACHED;
private File workingDir;
private boolean quiet;
private boolean taskList;
private boolean dependencyList;
private final Map<String, String> environmentVars = new HashMap<>();
private final List<File> initScripts = new ArrayList<>();
private String executable;
private TestFile gradleUserHomeDir;
private File userHomeDir;
private File javaHome;
private File buildScript;
private File projectDir;
private File settingsFile;
private boolean ignoreMissingSettingsFile;
private boolean ignoreCleanupAssertions;
private PipedOutputStream stdinPipe;
private String defaultCharacterEncoding;
private Locale defaultLocale;
private int daemonIdleTimeoutSecs = 120;
private boolean requireDaemon;
private File daemonBaseDir;
private final List<String> buildJvmOpts = new ArrayList<>();
private final List<String> commandLineJvmOpts = new ArrayList<>();
private boolean useOnlyRequestedJvmOpts;
private boolean useOwnUserHomeServices;
private ConsoleOutput consoleType;
protected WarningMode warningMode = WarningMode.All;
private boolean showStacktrace = true;
private boolean renderWelcomeMessage;
private boolean disableToolchainDownload = true;
private boolean disableToolchainDetection = true;
private boolean disablePluginRepositoryMirror = false;
private int expectedGenericDeprecationWarnings;
private final List<String> expectedDeprecationWarnings = new ArrayList<>();
private boolean eagerClassLoaderCreationChecksOn = true;
private boolean stackTraceChecksOn = true;
private final MutableActionSet<GradleExecuter> beforeExecute = new MutableActionSet<>();
private ImmutableActionSet<GradleExecuter> afterExecute = ImmutableActionSet.empty();
protected final TestDirectoryProvider testDirectoryProvider;
protected final GradleVersion gradleVersion;
protected final GradleDistribution distribution;
private boolean debug = Boolean.getBoolean(DEBUG_SYSPROP);
private boolean debugLauncher = Boolean.getBoolean(LAUNCHER_DEBUG_SYSPROP);
private String profiler = System.getProperty(PROFILE_SYSPROP, "");
protected boolean interactive;
protected boolean noExplicitNativeServicesDir;
private boolean fullDeprecationStackTrace;
private boolean checkDeprecations = true;
private boolean checkDaemonCrash = true;
private TestFile tmpDir;
private DurationMeasurement durationMeasurement;
protected AbstractGradleExecuter(GradleDistribution distribution, TestDirectoryProvider testDirectoryProvider) {
this(distribution, testDirectoryProvider, GradleVersion.current());
}
protected AbstractGradleExecuter(GradleDistribution distribution, TestDirectoryProvider testDirectoryProvider, GradleVersion gradleVersion) {
this(distribution, testDirectoryProvider, gradleVersion, IntegrationTestBuildContext.INSTANCE);
}
protected AbstractGradleExecuter(GradleDistribution distribution, TestDirectoryProvider testDirectoryProvider, GradleVersion gradleVersion, IntegrationTestBuildContext buildContext) {
this.distribution = distribution;
this.testDirectoryProvider = testDirectoryProvider;
this.gradleVersion = gradleVersion;
this.logger = Logging.getLogger(getClass());
this.buildContext = buildContext;
this.gradleUserHomeDir = buildContext.getGradleUserHomeDir();
this.daemonBaseDir = buildContext.getDaemonBaseDir();
this.daemonCrashLogsBeforeTest = ImmutableSet.copyOf(DaemonLogsAnalyzer.findCrashLogs(daemonBaseDir));
}
protected Logger getLogger() {
return logger;
}
@Override
public GradleExecuter reset() {
args.clear();
tasks.clear();
initScripts.clear();
workingDir = null;
projectDir = null;
buildScript = null;
settingsFile = null;
ignoreMissingSettingsFile = false;
// ignoreCleanupAssertions is intentionally sticky
// ignoreCleanupAssertions = false;
quiet = false;
taskList = false;
dependencyList = false;
executable = null;
javaHome = null;
environmentVars.clear();
stdinPipe = null;
defaultCharacterEncoding = null;
defaultLocale = null;
commandLineJvmOpts.clear();
buildJvmOpts.clear();
useOnlyRequestedJvmOpts = false;
expectedGenericDeprecationWarnings = 0;
expectedDeprecationWarnings.clear();
stackTraceChecksOn = true;
renderWelcomeMessage = false;
disableToolchainDownload = true;
disableToolchainDetection = true;
debug = Boolean.getBoolean(DEBUG_SYSPROP);
debugLauncher = Boolean.getBoolean(LAUNCHER_DEBUG_SYSPROP);
profiler = System.getProperty(PROFILE_SYSPROP, "");
interactive = false;
checkDeprecations = true;
durationMeasurement = null;
consoleType = null;
warningMode = WarningMode.All;
return this;
}
@Override
public GradleDistribution getDistribution() {
return distribution;
}
@Override
public TestDirectoryProvider getTestDirectoryProvider() {
return testDirectoryProvider;
}
@Override
public void beforeExecute(Action<? super GradleExecuter> action) {
beforeExecute.add(action);
}
@Override
public void beforeExecute(@DelegatesTo(GradleExecuter.class) Closure action) {
beforeExecute.add(new ClosureBackedAction<>(action));
}
@Override
public void afterExecute(Action<? super GradleExecuter> action) {
afterExecute = afterExecute.add(action);
}
@Override
public void afterExecute(@DelegatesTo(GradleExecuter.class) Closure action) {
afterExecute(new ClosureBackedAction<>(action));
}
@Override
public GradleExecuter inDirectory(File directory) {
workingDir = directory;
return this;
}
public File getWorkingDir() {
return workingDir == null ? getTestDirectoryProvider().getTestDirectory() : workingDir;
}
@Override
public GradleExecuter copyTo(GradleExecuter executer) {
executer.withGradleUserHomeDir(gradleUserHomeDir);
executer.withDaemonIdleTimeoutSecs(daemonIdleTimeoutSecs);
executer.withDaemonBaseDir(daemonBaseDir);
if (workingDir != null) {
executer.inDirectory(workingDir);
}
if (projectDir != null) {
executer.usingProjectDirectory(projectDir);
}
if (buildScript != null) {
executer.usingBuildScript(buildScript);
}
if (settingsFile != null) {
executer.usingSettingsFile(settingsFile);
}
if (ignoreMissingSettingsFile) {
executer.ignoreMissingSettingsFile();
}
if (ignoreCleanupAssertions) {
executer.ignoreCleanupAssertions();
}
if (javaHome != null) {
executer.withJavaHome(javaHome);
}
for (File initScript : initScripts) {
executer.usingInitScript(initScript);
}
executer.withTasks(tasks);
executer.withArguments(args);
executer.withEnvironmentVars(environmentVars);
executer.usingExecutable(executable);
if (quiet) {
executer.withQuietLogging();
}
if (taskList) {
executer.withTaskList();
}
if (dependencyList) {
executer.withDependencyList();
}
if (userHomeDir != null) {
executer.withUserHomeDir(userHomeDir);
}
if (stdinPipe != null) {
executer.withStdinPipe(stdinPipe);
}
if (defaultCharacterEncoding != null) {
executer.withDefaultCharacterEncoding(defaultCharacterEncoding);
}
if (noExplicitNativeServicesDir) {
executer.withNoExplicitNativeServicesDir();
}
if (fullDeprecationStackTrace) {
executer.withFullDeprecationStackTraceEnabled();
}
if (defaultLocale != null) {
executer.withDefaultLocale(defaultLocale);
}
executer.withCommandLineGradleOpts(commandLineJvmOpts);
executer.withBuildJvmOpts(buildJvmOpts);
if (useOnlyRequestedJvmOpts) {
executer.useOnlyRequestedJvmOpts();
}
executer.noExtraLogging();
if (expectedGenericDeprecationWarnings > 0) {
executer.expectDeprecationWarnings(expectedGenericDeprecationWarnings);
}
expectedDeprecationWarnings.forEach(executer::expectDeprecationWarning);
if (!eagerClassLoaderCreationChecksOn) {
executer.withEagerClassLoaderCreationCheckDisabled();
}
if (!stackTraceChecksOn) {
executer.withStackTraceChecksDisabled();
}
if (useOwnUserHomeServices) {
executer.withOwnUserHomeServices();
}
if (requireDaemon) {
executer.requireDaemon();
}
if (!checkDaemonCrash) {
executer.noDaemonCrashChecks();
}
executer.startBuildProcessInDebugger(debug);
executer.startLauncherInDebugger(debugLauncher);
executer.withProfiler(profiler);
executer.withForceInteractive(interactive);
if (!checkDeprecations) {
executer.noDeprecationChecks();
}
if (durationMeasurement != null) {
executer.withDurationMeasurement(durationMeasurement);
}
if (consoleType != null) {
executer.withConsole(consoleType);
}
executer.withWarningMode(warningMode);
if (!showStacktrace) {
executer.withStacktraceDisabled();
}
if (renderWelcomeMessage) {
executer.withWelcomeMessageEnabled();
}
if (!disableToolchainDetection) {
executer.withToolchainDetectionEnabled();
}
if (!disableToolchainDownload) {
executer.withToolchainDownloadEnabled();
}
executer.withTestConsoleAttached(consoleAttachment);
if (disablePluginRepositoryMirror) {
executer.withPluginRepositoryMirrorDisabled();
}
return executer;
}
@Override
@Deprecated
public GradleExecuter usingBuildScript(File buildScript) {
this.buildScript = buildScript;
return this;
}
@Override
public GradleExecuter usingProjectDirectory(File projectDir) {
this.projectDir = projectDir;
return this;
}
@Override
@Deprecated
public GradleExecuter usingSettingsFile(File settingsFile) {
this.settingsFile = settingsFile;
return this;
}
@Override
public GradleExecuter usingInitScript(File initScript) {
initScripts.add(initScript);
return this;
}
@Override
public TestFile getGradleUserHomeDir() {
return gradleUserHomeDir;
}
@Override
public GradleExecuter withGradleUserHomeDir(File userHomeDir) {
this.gradleUserHomeDir = userHomeDir == null ? null : new TestFile(userHomeDir);
return this;
}
@Override
public GradleExecuter requireOwnGradleUserHomeDir() {
return withGradleUserHomeDir(testDirectoryProvider.getTestDirectory().file("user-home"));
}
public File getUserHomeDir() {
return userHomeDir;
}
protected GradleInvocation buildInvocation() {
validateDaemonVisibility();
GradleInvocation gradleInvocation = new GradleInvocation();
gradleInvocation.environmentVars.putAll(environmentVars);
if (!useOnlyRequestedJvmOpts) {
gradleInvocation.buildJvmArgs.addAll(getImplicitBuildJvmArgs());
}
gradleInvocation.buildJvmArgs.addAll(buildJvmOpts);
calculateLauncherJvmArgs(gradleInvocation);
gradleInvocation.args.addAll(getAllArgs());
transformInvocation(gradleInvocation);
if (!gradleInvocation.implicitLauncherJvmArgs.isEmpty()) {
throw new IllegalStateException("Implicit JVM args have not been handled.");
}
return gradleInvocation;
}
protected void validateDaemonVisibility() {
if (isUseDaemon() && isSharedDaemons()) {
throw new IllegalStateException("Daemon that will be visible to other tests has been requested.");
}
}
/**
* Adjusts the calculated invocation prior to execution. This method is responsible for handling the implicit launcher JVM args in some way, by mutating the invocation appropriately.
*/
protected void transformInvocation(GradleInvocation gradleInvocation) {
gradleInvocation.launcherJvmArgs.addAll(0, gradleInvocation.implicitLauncherJvmArgs);
gradleInvocation.implicitLauncherJvmArgs.clear();
}
/**
* Returns the JVM opts that should be used to start a forked JVM.
*/
private void calculateLauncherJvmArgs(GradleInvocation gradleInvocation) {
// Add JVM args that were explicitly requested
gradleInvocation.launcherJvmArgs.addAll(commandLineJvmOpts);
if (isUseDaemon() && !gradleInvocation.buildJvmArgs.isEmpty()) {
// Pass build JVM args through to daemon via system property on the launcher JVM
String quotedArgs = join(" ", collect(gradleInvocation.buildJvmArgs, input -> String.format("'%s'", input)));
gradleInvocation.implicitLauncherJvmArgs.add("-Dorg.gradle.jvmargs=" + quotedArgs);
} else {
// Have to pass build JVM args directly to launcher JVM
gradleInvocation.launcherJvmArgs.addAll(gradleInvocation.buildJvmArgs);
}
// Set the implicit system properties regardless of whether default JVM args are required or not, this should not interfere with tests' intentions
// These will also be copied across to any daemon used
for (Map.Entry<String, String> entry : getImplicitJvmSystemProperties().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
gradleInvocation.implicitLauncherJvmArgs.add(String.format("-D%s=%s", key, value));
}
if (isDebugLauncher()) {
gradleInvocation.implicitLauncherJvmArgs.addAll(DEBUG_ARGS);
}
gradleInvocation.implicitLauncherJvmArgs.add("-ea");
}
/**
* Returns additional JVM args that should be used to start the build JVM.
*/
protected List<String> getImplicitBuildJvmArgs() {
List<String> buildJvmOpts = new ArrayList<>();
buildJvmOpts.add("-ea");
if (isDebug()) {
buildJvmOpts.addAll(DEBUG_ARGS);
}
if (isProfile()) {
buildJvmOpts.add(profiler);
}
if (isSharedDaemons()) {
buildJvmOpts.add("-Xms256m");
buildJvmOpts.add("-Xmx1024m");
} else {
buildJvmOpts.add("-Xms256m");
buildJvmOpts.add("-Xmx512m");
}
if (JVM_VERSION_DETECTOR.getJavaVersion(Jvm.forHome(getJavaHome())).compareTo(JavaVersion.VERSION_1_8) < 0) {
// Although Gradle isn't supported on earlier versions, some tests do run it using Java 6 and 7 to verify it behaves well in this case
buildJvmOpts.add("-XX:MaxPermSize=320m");
} else {
buildJvmOpts.add("-XX:MaxMetaspaceSize=512m");
}
buildJvmOpts.add("-XX:+HeapDumpOnOutOfMemoryError");
buildJvmOpts.add("-XX:HeapDumpPath=" + buildContext.getGradleUserHomeDir());
return buildJvmOpts;
}
private boolean xmxSpecified() {
for (String arg : buildJvmOpts) {
if (arg.startsWith("-Xmx")) {
return true;
}
}
return false;
}
@Override
public GradleExecuter withUserHomeDir(File userHomeDir) {
this.userHomeDir = userHomeDir;
return this;
}
public File getJavaHome() {
return javaHome == null ? Jvm.current().getJavaHome() : javaHome;
}
@Override
public GradleExecuter withJavaHome(File javaHome) {
this.javaHome = javaHome;
return this;
}
@Override
public GradleExecuter usingExecutable(String script) {
this.executable = script;
return this;
}
public String getExecutable() {
return executable;
}
@Override
public GradleExecuter withStdinPipe() {
return withStdinPipe(new PipedOutputStream());
}
@Override
public GradleExecuter withStdinPipe(PipedOutputStream stdInPipe) {
this.stdinPipe = stdInPipe;
return this;
}
public InputStream connectStdIn() {
try {
return stdinPipe == null ? SafeStreams.emptyInput() : new PipedInputStream(stdinPipe);
} catch (IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
public PipedOutputStream getStdinPipe() {
return stdinPipe;
}
@Override
public GradleExecuter withDefaultCharacterEncoding(String defaultCharacterEncoding) {
this.defaultCharacterEncoding = defaultCharacterEncoding;
return this;
}
public String getDefaultCharacterEncoding() {
return defaultCharacterEncoding == null ? Charset.defaultCharset().name() : defaultCharacterEncoding;
}
@Override
public GradleExecuter withDefaultLocale(Locale defaultLocale) {
this.defaultLocale = defaultLocale;
return this;
}
public Locale getDefaultLocale() {
return defaultLocale;
}
public boolean isQuiet() {
return quiet;
}
@Override
public GradleExecuter withQuietLogging() {
quiet = true;
return this;
}
@Override
public GradleExecuter withTaskList() {
taskList = true;
return this;
}
@Override
public GradleExecuter withDependencyList() {
dependencyList = true;
return this;
}
@Override
public GradleExecuter withArguments(String... args) {
return withArguments(Arrays.asList(args));
}
@Override
public GradleExecuter withArguments(List<String> args) {
this.args.clear();
this.args.addAll(args);
return this;
}
@Override
public GradleExecuter withArgument(String arg) {
this.args.add(arg);
return this;
}
@Override
public GradleExecuter withEnvironmentVars(Map<String, ?> environment) {
environmentVars.clear();
for (Map.Entry<String, ?> entry : environment.entrySet()) {
environmentVars.put(entry.getKey(), entry.getValue().toString());
}
return this;
}
protected Map<String, String> getEnvironmentVars() {
return new HashMap<>(environmentVars);
}
protected String toJvmArgsString(Iterable<String> jvmArgs) {
StringBuilder result = new StringBuilder();
for (String jvmArg : jvmArgs) {
if (result.length() > 0) {
result.append(" ");
}
if (jvmArg.contains(" ")) {
assert !jvmArg.contains("\"") : "jvmArg '" + jvmArg + "' contains '\"'";
result.append('"');
result.append(jvmArg);
result.append('"');
} else {
result.append(jvmArg);
}
}
return result.toString();
}
@Override
public GradleExecuter withTasks(String... names) {
return withTasks(Arrays.asList(names));
}
@Override
public GradleExecuter withTasks(List<String> names) {
tasks.clear();
tasks.addAll(names);
return this;
}
@Override
public GradleExecuter withDaemonIdleTimeoutSecs(int secs) {
daemonIdleTimeoutSecs = secs;
return this;
}
@Override
public GradleExecuter useOnlyRequestedJvmOpts() {
useOnlyRequestedJvmOpts = true;
return this;
}
@Override
public GradleExecuter withDaemonBaseDir(File daemonBaseDir) {
this.daemonBaseDir = daemonBaseDir;
return this;
}
@Override
public GradleExecuter withReadOnlyCacheDir(File cacheDir) {
return withReadOnlyCacheDir(cacheDir.getAbsolutePath());
}
@Override
public GradleExecuter withReadOnlyCacheDir(String cacheDir) {
environmentVars.put(ArtifactCachesProvider.READONLY_CACHE_ENV_VAR, cacheDir);
return this;
}
@Override
public GradleExecuter requireIsolatedDaemons() {
return withDaemonBaseDir(testDirectoryProvider.getTestDirectory().file("daemon"));
}
@Override
public GradleExecuter withWorkerDaemonsExpirationDisabled() {
return withCommandLineGradleOpts("-Dorg.gradle.workers.internal.disable-daemons-expiration=true");
}
@Override
public boolean usesSharedDaemons() {
return isSharedDaemons();
}
@Override
public File getDaemonBaseDir() {
return daemonBaseDir;
}
@Override
public GradleExecuter requireDaemon() {
this.requireDaemon = true;
return this;
}
protected boolean isSharedDaemons() {
return daemonBaseDir.equals(buildContext.getDaemonBaseDir());
}
@Override
public boolean isUseDaemon() {
CliDaemonArgument cliDaemonArgument = resolveCliDaemonArgument();
if (cliDaemonArgument == NO_DAEMON || cliDaemonArgument == FOREGROUND) {
return false;
}
return requireDaemon || cliDaemonArgument == DAEMON;
}
@Override
public GradleExecuter withOwnUserHomeServices() {
useOwnUserHomeServices = true;
return this;
}
@Override
public GradleExecuter withWarningMode(WarningMode warningMode) {
this.warningMode = warningMode;
return this;
}
@Override
public GradleExecuter withConsole(ConsoleOutput consoleType) {
this.consoleType = consoleType;
return this;
}
@Override
public GradleExecuter withStacktraceDisabled() {
showStacktrace = false;
return this;
}
@Override
public GradleExecuter withWelcomeMessageEnabled() {
renderWelcomeMessage = true;
return this;
}
@Override
public GradleExecuter withToolchainDetectionEnabled() {
disableToolchainDetection = false;
return this;
}
@Override
public GradleExecuter withToolchainDownloadEnabled() {
withToolchainDetectionEnabled();
disableToolchainDownload = false;
return this;
}
@Override
public GradleExecuter withRepositoryMirrors() {
beforeExecute(gradleExecuter -> usingInitScript(RepoScriptBlockUtil.createMirrorInitScript()));
return this;
}
@Override
public GradleExecuter withGlobalRepositoryMirrors() {
beforeExecute(gradleExecuter -> {
TestFile userHome = testDirectoryProvider.getTestDirectory().file("user-home");
withGradleUserHomeDir(userHome);
userHome.file("init.d/mirrors.gradle").write(RepoScriptBlockUtil.mirrorInitScript());
});
return this;
}
@Override
public GradleExecuter withPluginRepositoryMirrorDisabled() {
disablePluginRepositoryMirror = true;
return this;
}
@Override
public GradleExecuter ignoreCleanupAssertions() {
this.ignoreCleanupAssertions = true;
return this;
}
@Override
public void resetExpectations() {
cleanup();
}
/**
* Performs cleanup at completion of the test.
*/
public void cleanup() {
stopRunningBuilds();
cleanupIsolatedDaemons();
checkForDaemonCrashesInSharedLocations();
assertVisitedExecutionResults();
}
private void stopRunningBuilds() {
for (GradleHandle handle : running) {
try {
handle.abort().waitForExit();
} catch (Exception e) {
getLogger().warn("Problem stopping running build", e);
}
}
}
private void cleanupIsolatedDaemons() {
List<DaemonLogsAnalyzer> analyzers = new ArrayList<>();
for (File dir : isolatedDaemonBaseDirs) {
try {
DaemonLogsAnalyzer analyzer = new DaemonLogsAnalyzer(dir, gradleVersion.getVersion());
analyzers.add(analyzer);
analyzer.killAll();
} catch (Exception e) {
getLogger().warn("Problem killing isolated daemons of Gradle version " + gradleVersion + " in " + dir, e);
}
}
if (checkDaemonCrash) {
analyzers.forEach(DaemonLogsAnalyzer::assertNoCrashedDaemon);
}
}
private void checkForDaemonCrashesInSharedLocations() {
checkForDaemonCrashes(getWorkingDir(), it -> true);
checkForDaemonCrashes(buildContext.getDaemonBaseDir(), crashLog -> !daemonCrashLogsBeforeTest.contains(crashLog));
}
private void checkForDaemonCrashes(File dirToSearch, Predicate<File> crashLogFilter) {
if (checkDaemonCrash) {
List<File> crashLogs = DaemonLogsAnalyzer.findCrashLogs(dirToSearch).stream()
.filter(crashLogFilter)
.collect(Collectors.toList());
if (!crashLogs.isEmpty()) {
throw new AssertionError(String.format(
"Found crash logs: '%s'",
crashLogs.stream().map(File::getAbsolutePath).collect(joining("', '"))
));
}
}
}
private void assertVisitedExecutionResults() {
if (!ignoreCleanupAssertions) {
for (ExecutionResult result : results) {
result.assertResultVisited();
}
}
}
enum CliDaemonArgument {
NOT_DEFINED,
DAEMON,
NO_DAEMON,
FOREGROUND
}
protected CliDaemonArgument resolveCliDaemonArgument() {
for (int i = args.size() - 1; i >= 0; i--) {
final String arg = args.get(i);
if (arg.equals("--daemon")) {
return DAEMON;
}
if (arg.equals("--no-daemon")) {
return NO_DAEMON;
}
if (arg.equals("--foreground")) {
return FOREGROUND;
}
}
return NOT_DEFINED;
}
private boolean noDaemonArgumentGiven() {
return resolveCliDaemonArgument() == NOT_DEFINED;
}
protected List<String> getAllArgs() {
List<String> allArgs = new ArrayList<>();
if (buildScript != null) {
allArgs.add("--build-file");
allArgs.add(buildScript.getAbsolutePath());
}
if (projectDir != null) {
allArgs.add("--project-dir");
allArgs.add(projectDir.getAbsolutePath());
}
for (File initScript : initScripts) {
allArgs.add("--init-script");
allArgs.add(initScript.getAbsolutePath());
}
if (settingsFile != null) {
allArgs.add("--settings-file");
allArgs.add(settingsFile.getAbsolutePath());
}
if (quiet) {
allArgs.add("--quiet");