-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdevelocity-gradle.yml
672 lines (602 loc) · 32.4 KB
/
develocity-gradle.yml
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
spec:
inputs:
# Develocity server URL
url:
default: 'https://scans.gradle.com'
# Develocity Plugin version
# Allow untrusted server
allowUntrustedServer:
default: 'false'
# Short-lived tokens expiry in hours
shortLivedTokensExpiry:
default: '2'
gradlePluginVersion:
default: '3.19.1'
# Common Custom User Data Gradle Plugin version (see https://github.com/gradle/common-custom-user-data-gradle-plugin/)
ccudPluginVersion:
default: '2.0.2'
# Develocity Gradle plugin repository URL, defaults in the init script to https://plugins.gradle.org/m2
gradlePluginRepositoryUrl:
default: ''
# Develocity Gradle plugin repository username
gradlePluginRepositoryUsername:
default: ''
# Develocity Gradle plugin repository password, strongly advised to pass a protected and masked variable
gradlePluginRepositoryPassword:
default: ''
# Capture file fingerprints, only set if no Develocity plugin is already present
captureFileFingerprints:
default: 'true'
# Enforce the url over any defined locally to the project
enforceUrl:
default: 'false'
---
.build_scan_links_report:
artifacts:
reports:
annotations: $CI_PROJECT_DIR/build-scan-links.json
.injectDevelocityForGradle: |
function createGradleInit() {
local initScript="${CI_PROJECT_DIR}/init-script.gradle"
cat > $initScript <<'EOF'
/*
* Initscript for injection of Develocity into Gradle builds.
* Version: v1.1
*/
import org.gradle.util.GradleVersion
initscript {
// NOTE: there is no mechanism to share code between the initscript{} block and the main script, so some logic is duplicated
def isTopLevelBuild = !gradle.parent
if (!isTopLevelBuild) {
return
}
def getInputParam = { Gradle gradle, String name ->
def ENV_VAR_PREFIX = ''
def envVarName = ENV_VAR_PREFIX + name.toUpperCase().replace('.', '_').replace('-', '_')
return gradle.startParameter.systemPropertiesArgs[name] ?: System.getProperty(name) ?: System.getenv(envVarName)
}
def requestedInitScriptName = getInputParam(gradle, 'develocity.injection.init-script-name')
def initScriptName = buildscript.sourceFile.name
if (requestedInitScriptName != initScriptName) {
return
}
// Plugin loading is only required for Develocity injection. Abort early if not enabled.
def develocityInjectionEnabled = Boolean.parseBoolean(getInputParam(gradle, "develocity.injection-enabled"))
if (!develocityInjectionEnabled) {
return
}
def pluginRepositoryUrl = getInputParam(gradle, 'gradle.plugin-repository.url')
def pluginRepositoryUsername = getInputParam(gradle, 'gradle.plugin-repository.username')
def pluginRepositoryPassword = getInputParam(gradle, 'gradle.plugin-repository.password')
def develocityPluginVersion = getInputParam(gradle, 'develocity.plugin.version')
def ccudPluginVersion = getInputParam(gradle, 'develocity.ccud-plugin.version')
def atLeastGradle5 = GradleVersion.current() >= GradleVersion.version('5.0')
def atLeastGradle4 = GradleVersion.current() >= GradleVersion.version('4.0')
if (develocityPluginVersion || ccudPluginVersion && atLeastGradle4) {
pluginRepositoryUrl = pluginRepositoryUrl ?: 'https://plugins.gradle.org/m2'
logger.lifecycle("Develocity plugins resolution: $pluginRepositoryUrl")
repositories {
maven {
url pluginRepositoryUrl
if (pluginRepositoryUsername && pluginRepositoryPassword) {
logger.lifecycle("Using credentials for plugin repository")
credentials {
username(pluginRepositoryUsername)
password(pluginRepositoryPassword)
}
authentication {
basic(BasicAuthentication)
}
}
}
}
}
dependencies {
if (develocityPluginVersion) {
if (atLeastGradle5) {
if (GradleVersion.version(develocityPluginVersion) >= GradleVersion.version("3.17")) {
classpath "com.gradle:develocity-gradle-plugin:$develocityPluginVersion"
} else {
classpath "com.gradle:gradle-enterprise-gradle-plugin:$develocityPluginVersion"
}
} else {
classpath "com.gradle:build-scan-plugin:1.16"
}
}
if (ccudPluginVersion && atLeastGradle4) {
classpath "com.gradle:common-custom-user-data-gradle-plugin:$ccudPluginVersion"
}
}
}
static getInputParam(Gradle gradle, String name) {
def ENV_VAR_PREFIX = ''
def envVarName = ENV_VAR_PREFIX + name.toUpperCase().replace('.', '_').replace('-', '_')
return gradle.startParameter.systemPropertiesArgs[name] ?: System.getProperty(name) ?: System.getenv(envVarName)
}
def isTopLevelBuild = !gradle.parent
if (!isTopLevelBuild) {
return
}
def requestedInitScriptName = getInputParam(gradle, 'develocity.injection.init-script-name')
def initScriptName = buildscript.sourceFile.name
if (requestedInitScriptName != initScriptName) {
logger.quiet("Ignoring init script '${initScriptName}' as requested name '${requestedInitScriptName}' does not match")
return
}
def develocityInjectionEnabled = Boolean.parseBoolean(getInputParam(gradle, "develocity.injection-enabled"))
if (develocityInjectionEnabled) {
enableDevelocityInjection()
}
// To enable build-scan capture, a `captureBuildScanLink(String)` method must be added to `BuildScanCollector`.
def buildScanCollector = new BuildScanCollector()
def buildScanCaptureEnabled = buildScanCollector.metaClass.respondsTo(buildScanCollector, 'captureBuildScanLink', String)
if (buildScanCaptureEnabled) {
enableBuildScanLinkCapture(buildScanCollector)
}
void enableDevelocityInjection() {
def BUILD_SCAN_PLUGIN_ID = 'com.gradle.build-scan'
def BUILD_SCAN_PLUGIN_CLASS = 'com.gradle.scan.plugin.BuildScanPlugin'
def GRADLE_ENTERPRISE_PLUGIN_ID = 'com.gradle.enterprise'
def GRADLE_ENTERPRISE_PLUGIN_CLASS = 'com.gradle.enterprise.gradleplugin.GradleEnterprisePlugin'
def DEVELOCITY_PLUGIN_ID = 'com.gradle.develocity'
def DEVELOCITY_PLUGIN_CLASS = 'com.gradle.develocity.agent.gradle.DevelocityPlugin'
def CI_AUTO_INJECTION_CUSTOM_VALUE_NAME = 'CI auto injection'
def CCUD_PLUGIN_ID = 'com.gradle.common-custom-user-data-gradle-plugin'
def CCUD_PLUGIN_CLASS = 'com.gradle.CommonCustomUserDataGradlePlugin'
def develocityUrl = getInputParam(gradle, 'develocity.url')
def develocityAllowUntrustedServer = Boolean.parseBoolean(getInputParam(gradle, 'develocity.allow-untrusted-server'))
def develocityEnforceUrl = Boolean.parseBoolean(getInputParam(gradle, 'develocity.enforce-url'))
def buildScanUploadInBackground = Boolean.parseBoolean(getInputParam(gradle, 'develocity.build-scan.upload-in-background'))
def develocityCaptureFileFingerprints = getInputParam(gradle, 'develocity.capture-file-fingerprints') ? Boolean.parseBoolean(getInputParam(gradle, 'develocity.capture-file-fingerprints')) : true
def develocityPluginVersion = getInputParam(gradle, 'develocity.plugin.version')
def ccudPluginVersion = getInputParam(gradle, 'develocity.ccud-plugin.version')
def buildScanTermsOfUseUrl = getInputParam(gradle, 'develocity.terms-of-use.url')
def buildScanTermsOfUseAgree = getInputParam(gradle, 'develocity.terms-of-use.agree')
def ciAutoInjectionCustomValueValue = getInputParam(gradle, 'develocity.auto-injection.custom-value')
def atLeastGradle5 = GradleVersion.current() >= GradleVersion.version('5.0')
def atLeastGradle4 = GradleVersion.current() >= GradleVersion.version('4.0')
def shouldApplyDevelocityPlugin = atLeastGradle5 && develocityPluginVersion && isAtLeast(develocityPluginVersion, '3.17')
def dvOrGe = { def dvValue, def geValue ->
if (shouldApplyDevelocityPlugin) {
return dvValue instanceof Closure<?> ? dvValue() : dvValue
}
return geValue instanceof Closure<?> ? geValue() : geValue
}
def printEnforcingDevelocityUrl = {
logger.lifecycle("Enforcing Develocity: $develocityUrl, allowUntrustedServer: $develocityAllowUntrustedServer")
}
def printAcceptingGradleTermsOfUse = {
logger.lifecycle("Accepting Gradle Terms of Use: $buildScanTermsOfUseUrl")
}
// finish early if configuration parameters passed in via system properties are not valid/supported
if (ccudPluginVersion && isNotAtLeast(ccudPluginVersion, '1.7')) {
logger.warn("Common Custom User Data Gradle plugin must be at least 1.7. Configured version is $ccudPluginVersion.")
return
}
// Conditionally apply and configure the Develocity plugin
if (GradleVersion.current() < GradleVersion.version('6.0')) {
rootProject {
buildscript.configurations.getByName("classpath").incoming.afterResolve { ResolvableDependencies incoming ->
def resolutionResult = incoming.resolutionResult
if (develocityPluginVersion) {
def scanPluginComponent = resolutionResult.allComponents.find {
it.moduleVersion.with { group == "com.gradle" && ['build-scan-plugin', 'gradle-enterprise-gradle-plugin', 'develocity-gradle-plugin'].contains(name) }
}
if (!scanPluginComponent) {
def pluginClass = dvOrGe(DEVELOCITY_PLUGIN_CLASS, BUILD_SCAN_PLUGIN_CLASS)
def pluginVersion = atLeastGradle5 ? develocityPluginVersion : "1.16"
applyPluginExternally(pluginManager, pluginClass, pluginVersion)
def rootExtension = dvOrGe(
{ develocity },
{ buildScan }
)
def buildScanExtension = dvOrGe(
{ rootExtension.buildScan },
{ rootExtension }
)
if (develocityUrl) {
logger.lifecycle("Connection to Develocity: $develocityUrl, allowUntrustedServer: $develocityAllowUntrustedServer, captureFileFingerprints: $develocityCaptureFileFingerprints")
rootExtension.server = develocityUrl
rootExtension.allowUntrustedServer = develocityAllowUntrustedServer
}
if (!shouldApplyDevelocityPlugin) {
// Develocity plugin publishes scans by default
buildScanExtension.publishAlways()
}
// uploadInBackground not available for build-scan-plugin 1.16
if (buildScanExtension.metaClass.respondsTo(buildScanExtension, 'setUploadInBackground', Boolean)) buildScanExtension.uploadInBackground = buildScanUploadInBackground
buildScanExtension.value CI_AUTO_INJECTION_CUSTOM_VALUE_NAME, ciAutoInjectionCustomValueValue
if (isAtLeast(develocityPluginVersion, '2.1') && atLeastGradle5) {
logger.lifecycle("Setting captureFileFingerprints: $develocityCaptureFileFingerprints")
if (isAtLeast(develocityPluginVersion, '3.17')) {
buildScanExtension.capture.fileFingerprints.set(develocityCaptureFileFingerprints)
} else if (isAtLeast(develocityPluginVersion, '3.7')) {
buildScanExtension.capture.taskInputFiles = develocityCaptureFileFingerprints
} else {
buildScanExtension.captureTaskInputFiles = develocityCaptureFileFingerprints
}
}
}
}
eachDevelocityProjectExtension(project,
{ develocity ->
afterEvaluate {
if (develocityUrl && develocityEnforceUrl) {
printEnforcingDevelocityUrl()
develocity.server = develocityUrl
develocity.allowUntrustedServer = develocityAllowUntrustedServer
}
}
if (buildScanTermsOfUseUrl && buildScanTermsOfUseAgree) {
printAcceptingGradleTermsOfUse()
develocity.buildScan.termsOfUseUrl = buildScanTermsOfUseUrl
develocity.buildScan.termsOfUseAgree = buildScanTermsOfUseAgree
}
},
{ buildScan ->
afterEvaluate {
if (develocityUrl && develocityEnforceUrl) {
printEnforcingDevelocityUrl()
buildScan.server = develocityUrl
buildScan.allowUntrustedServer = develocityAllowUntrustedServer
}
}
if (buildScanTermsOfUseUrl && buildScanTermsOfUseAgree) {
printAcceptingGradleTermsOfUse()
if (buildScan.metaClass.respondsTo(buildScan, 'setTermsOfServiceUrl', String)) {
buildScan.termsOfServiceUrl = buildScanTermsOfUseUrl
buildScan.termsOfServiceAgree = buildScanTermsOfUseAgree
} else {
buildScan.licenseAgreementUrl = buildScanTermsOfUseUrl
buildScan.licenseAgree = buildScanTermsOfUseAgree
}
}
}
)
if (ccudPluginVersion && atLeastGradle4) {
def ccudPluginComponent = resolutionResult.allComponents.find {
it.moduleVersion.with { group == "com.gradle" && name == "common-custom-user-data-gradle-plugin" }
}
if (!ccudPluginComponent) {
logger.lifecycle("Applying $CCUD_PLUGIN_CLASS with version $ccudPluginVersion via init script")
pluginManager.apply(initscript.classLoader.loadClass(CCUD_PLUGIN_CLASS))
}
}
}
}
} else {
gradle.settingsEvaluated { settings ->
if (develocityPluginVersion) {
if (!settings.pluginManager.hasPlugin(GRADLE_ENTERPRISE_PLUGIN_ID) && !settings.pluginManager.hasPlugin(DEVELOCITY_PLUGIN_ID)) {
def pluginClass = dvOrGe(DEVELOCITY_PLUGIN_CLASS, GRADLE_ENTERPRISE_PLUGIN_CLASS)
applyPluginExternally(settings.pluginManager, pluginClass, develocityPluginVersion)
if (develocityUrl) {
logger.lifecycle("Connection to Develocity: $develocityUrl, allowUntrustedServer: $develocityAllowUntrustedServer, captureFileFingerprints: $develocityCaptureFileFingerprints")
eachDevelocitySettingsExtension(settings) { ext ->
// server and allowUntrustedServer must be configured via buildScan extension for gradle-enterprise-plugin 3.1.1 and earlier
if (ext.metaClass.respondsTo(ext, 'getServer')) {
ext.server = develocityUrl
ext.allowUntrustedServer = develocityAllowUntrustedServer
} else {
ext.buildScan.server = develocityUrl
ext.buildScan.allowUntrustedServer = develocityAllowUntrustedServer
}
}
}
eachDevelocitySettingsExtension(settings) { ext ->
ext.buildScan.uploadInBackground = buildScanUploadInBackground
ext.buildScan.value CI_AUTO_INJECTION_CUSTOM_VALUE_NAME, ciAutoInjectionCustomValueValue
}
eachDevelocitySettingsExtension(settings,
{ develocity ->
logger.lifecycle("Setting captureFileFingerprints: $develocityCaptureFileFingerprints")
develocity.buildScan.capture.fileFingerprints = develocityCaptureFileFingerprints
},
{ gradleEnterprise ->
gradleEnterprise.buildScan.publishAlways()
if (isAtLeast(develocityPluginVersion, '2.1')) {
logger.lifecycle("Setting captureFileFingerprints: $develocityCaptureFileFingerprints")
if (isAtLeast(develocityPluginVersion, '3.7')) {
gradleEnterprise.buildScan.capture.taskInputFiles = develocityCaptureFileFingerprints
} else {
gradleEnterprise.buildScan.captureTaskInputFiles = develocityCaptureFileFingerprints
}
}
}
)
}
}
eachDevelocitySettingsExtension(settings,
{ develocity ->
if (develocityUrl && develocityEnforceUrl) {
printEnforcingDevelocityUrl()
develocity.server = develocityUrl
develocity.allowUntrustedServer = develocityAllowUntrustedServer
}
if (buildScanTermsOfUseUrl && buildScanTermsOfUseAgree) {
printAcceptingGradleTermsOfUse()
develocity.buildScan.termsOfUseUrl = buildScanTermsOfUseUrl
develocity.buildScan.termsOfUseAgree = buildScanTermsOfUseAgree
}
},
{ gradleEnterprise ->
if (develocityUrl && develocityEnforceUrl) {
printEnforcingDevelocityUrl()
// server and allowUntrustedServer must be configured via buildScan extension for gradle-enterprise-plugin 3.1.1 and earlier
if (gradleEnterprise.metaClass.respondsTo(gradleEnterprise, 'getServer')) {
gradleEnterprise.server = develocityUrl
gradleEnterprise.allowUntrustedServer = develocityAllowUntrustedServer
} else {
gradleEnterprise.buildScan.server = develocityUrl
gradleEnterprise.buildScan.allowUntrustedServer = develocityAllowUntrustedServer
}
}
if (buildScanTermsOfUseUrl && buildScanTermsOfUseAgree) {
printAcceptingGradleTermsOfUse()
gradleEnterprise.buildScan.termsOfServiceUrl = buildScanTermsOfUseUrl
gradleEnterprise.buildScan.termsOfServiceAgree = buildScanTermsOfUseAgree
}
}
)
if (ccudPluginVersion) {
if (!settings.pluginManager.hasPlugin(CCUD_PLUGIN_ID)) {
logger.lifecycle("Applying $CCUD_PLUGIN_CLASS with version $ccudPluginVersion via init script")
settings.pluginManager.apply(initscript.classLoader.loadClass(CCUD_PLUGIN_CLASS))
}
}
}
}
}
void applyPluginExternally(def pluginManager, String pluginClassName, String pluginVersion) {
logger.lifecycle("Applying $pluginClassName with version $pluginVersion via init script")
def externallyApplied = 'develocity.externally-applied'
def externallyAppliedDeprecated = 'gradle.enterprise.externally-applied'
def oldValue = System.getProperty(externallyApplied)
def oldValueDeprecated = System.getProperty(externallyAppliedDeprecated)
System.setProperty(externallyApplied, 'true')
System.setProperty(externallyAppliedDeprecated, 'true')
try {
pluginManager.apply(initscript.classLoader.loadClass(pluginClassName))
} finally {
if (oldValue == null) {
System.clearProperty(externallyApplied)
} else {
System.setProperty(externallyApplied, oldValue)
}
if (oldValueDeprecated == null) {
System.clearProperty(externallyAppliedDeprecated)
} else {
System.setProperty(externallyAppliedDeprecated, oldValueDeprecated)
}
}
}
/**
* Apply the `dvAction` to all 'develocity' extensions.
* If no 'develocity' extensions are found, apply the `geAction` to all 'gradleEnterprise' extensions.
* (The develocity plugin creates both extensions, and we want to prefer configuring 'develocity').
*/
static def eachDevelocitySettingsExtension(def settings, def dvAction, def geAction = dvAction) {
def GRADLE_ENTERPRISE_EXTENSION_CLASS = 'com.gradle.enterprise.gradleplugin.GradleEnterpriseExtension'
def DEVELOCITY_CONFIGURATION_CLASS = 'com.gradle.develocity.agent.gradle.DevelocityConfiguration'
def dvExtensions = settings.extensions.extensionsSchema.elements
.findAll { it.publicType.concreteClass.name == DEVELOCITY_CONFIGURATION_CLASS }
.collect { settings[it.name] }
if (!dvExtensions.empty) {
dvExtensions.each(dvAction)
} else {
def geExtensions = settings.extensions.extensionsSchema.elements
.findAll { it.publicType.concreteClass.name == GRADLE_ENTERPRISE_EXTENSION_CLASS }
.collect { settings[it.name] }
geExtensions.each(geAction)
}
}
/**
* Apply the `dvAction` to the 'develocity' extension.
* If no 'develocity' extension is found, apply the `bsAction` to the 'buildScan' extension.
* (The develocity plugin creates both extensions, and we want to prefer configuring 'develocity').
*/
static def eachDevelocityProjectExtension(def project, def dvAction, def bsAction = dvAction) {
def BUILD_SCAN_PLUGIN_ID = 'com.gradle.build-scan'
def DEVELOCITY_PLUGIN_ID = 'com.gradle.develocity'
def configureDvOrBsExtension = {
if (project.extensions.findByName("develocity")) {
dvAction(project.develocity)
} else {
bsAction(project.buildScan)
}
}
project.pluginManager.withPlugin(BUILD_SCAN_PLUGIN_ID, configureDvOrBsExtension)
project.pluginManager.withPlugin(DEVELOCITY_PLUGIN_ID) {
// Proper extension will be configured by the build-scan callback.
if (project.pluginManager.hasPlugin(BUILD_SCAN_PLUGIN_ID)) return
configureDvOrBsExtension()
}
}
static boolean isAtLeast(String versionUnderTest, String referenceVersion) {
GradleVersion.version(versionUnderTest) >= GradleVersion.version(referenceVersion)
}
static boolean isNotAtLeast(String versionUnderTest, String referenceVersion) {
!isAtLeast(versionUnderTest, referenceVersion)
}
void enableBuildScanLinkCapture(BuildScanCollector collector) {
// Conditionally apply and configure the Develocity plugin
if (GradleVersion.current() < GradleVersion.version('6.0')) {
rootProject {
eachDevelocityProjectExtension(project,
{ develocity -> buildScanPublishedAction(develocity.buildScan, collector) },
{ buildScan -> buildScanPublishedAction(buildScan, collector) }
)
}
} else {
gradle.settingsEvaluated { settings ->
eachDevelocitySettingsExtension(settings) { ext ->
buildScanPublishedAction(ext.buildScan, collector)
}
}
}
}
// Action will only be called if a `BuildScanCollector.captureBuildScanLink` method is present.
// Add `void captureBuildScanLink(String) {}` to the `BuildScanCollector` class to respond to buildScanPublished events
static buildScanPublishedAction(def buildScanExtension, BuildScanCollector collector) {
if (buildScanExtension.metaClass.respondsTo(buildScanExtension, 'buildScanPublished', Action)) {
buildScanExtension.buildScanPublished { scan ->
collector.captureBuildScanLink(scan.buildScanUri.toString())
}
}
}
// Custom implementation of BuildScanCollector for GitLab integration
class BuildScanCollector {
def captureBuildScanLink(String buildScanLink) {
if (System.getenv("BUILD_SCAN_REPORT_PATH")) {
def reportFile = new File(System.getenv("BUILD_SCAN_REPORT_PATH"))
def report
// This might have been created by a previous Gradle invocation in the same GitLab job
// Note that we do not handle parallel Gradle scripts invocation, which should be a very edge case in context of a GitLab job
if (reportFile.exists()) {
report = new groovy.json.JsonSlurper().parseText(reportFile.text) as Report
} else {
report = new Report()
}
report.addLink(buildScanLink)
def generator = new groovy.json.JsonGenerator.Options()
.excludeFieldsByName('contentHash', 'originalClassName')
.build()
reportFile.text = generator.toJson(report)
}
}
}
class Report {
List<Link> build_scans = []
void addLink(String url) {
build_scans << new Link(url)
}
}
class Link {
Map external_link
Link(String url) {
external_link = [ 'label': url, 'url': url ]
}
}
EOF
export DEVELOCITY_INIT_SCRIPT_PATH="${initScript}"
export BUILD_SCAN_REPORT_PATH="${CI_PROJECT_DIR}/build-scan-links.json"
}
function createShortLivedToken() {
local allKeys="${GRADLE_ENTERPRISE_ACCESS_KEY:-${DEVELOCITY_ACCESS_KEY}}"
if [ -z "${allKeys}" ]
then
return 0
fi
local serverUrl=${1}
local expiry="${2}"
local newAccessKey=""
if [[ "${enforceUrl}" == "true" || $(singleKey "${allKeys}") == "true" ]]
then
local hostname=$(extractHostname "${serverUrl}")
local accessKey=$(extractAccessKey "${allKeys}" "${hostname}")
local tokenUrl="${serverUrl}/api/auth/token"
if [ ! -z "${accessKey}" ]
then
local token=$(getShortLivedToken $tokenUrl $expiry $accessKey)
if [ ! -z "${token}" ]
then
newAccessKey="${hostname}=${token}"
fi
else
>&2 echo "Could not create short lived access token, no access key matching given Develocity server hostname ${hostname}"
fi
else
local separator=";"
IFS="${separator}" read -ra pairs <<< "${allKeys}"
for pair in "${pairs[@]}"; do
IFS='=' read -r host key <<< "$pair"
local tokenUrl="https://${host}/api/auth/token"
local token=$(getShortLivedToken $tokenUrl $expiry $key)
if [ ! -z "${token}" ]
then
if [ -z "${newAccessKey}" ]
then
newAccessKey="${host}=${token}"
else
newAccessKey="${newAccessKey}${separator}${host}=${token}"
fi
fi
done
fi
export DEVELOCITY_ACCESS_KEY="${newAccessKey}"
export GRADLE_ENTERPRISE_ACCESS_KEY="${DEVELOCITY_ACCESS_KEY}"
}
function singleKey() {
local allKeys=$1
local separator=";"
IFS="${separator}" read -ra pairs <<< "${allKeys}"
if [ "${#pairs[@]}" -eq 1 ]
then
echo "true"
else
echo "false"
fi
}
function extractHostname() {
local url=$1
echo "${url}" | cut -d'/' -f3 | cut -d':' -f1
}
function extractAccessKey() {
local allKeys=$1
local hostname=$2
key="${allKeys#*$hostname=}" # Remove everything before the host name and '='
if [ "${key}" == "${allKeys}" ] # if nothing has changed, it's not a match
then
echo ""
else
key="${key%%;*}" # Remove everything after the first ';'
echo "$key"
fi
}
function getShortLivedToken() {
local tokenUrl=$1
local expiry=$2
local accessKey=$3
local maxRetries=3
local retryInterval=1
local attempt=0
if [ ! -z "${expiry}" ]
then
tokenUrl="${tokenUrl}?expiresInHours=${expiry}"
fi
while [ ${attempt} -le ${maxRetries} ]
do
local response=$(curl -s -w "\n%{http_code}" -X POST "${tokenUrl}" -H "Authorization: Bearer ${accessKey}")
local status_code=$(tail -n1 <<< "${response}")
local shortLivedToken=$(head -n -1 <<< "${response}")
if [[ "${status_code}" == "200" && ! -z "${shortLivedToken}" ]]
then
echo "${shortLivedToken}"
return
elif [ "${status_code}" == "401" ]
then
>&2 echo "Develocity short lived token request failed ${serverUrl} with status code 401"
return
else
((attempt++))
sleep ${retryInterval}
fi
done
}
function injectDevelocityForGradle() {
export "DEVELOCITY_INJECTION_ENABLED=true"
export "DEVELOCITY_INJECTION_INIT_SCRIPT_NAME=init-script.gradle"
export "DEVELOCITY_AUTO_INJECTION_CUSTOM_VALUE=GitLab"
export "DEVELOCITY_URL=$[[ inputs.url ]]"
export "DEVELOCITY_PLUGIN_VERSION=$[[ inputs.gradlePluginVersion ]]"
export "DEVELOCITY_CCUD_PLUGIN_VERSION=$[[ inputs.ccudPluginVersion ]]"
export "DEVELOCITY_ALLOW_UNTRUSTED_SERVER=$[[ inputs.allowUntrustedServer ]]"
export "DEVELOCITY_ENFORCE_URL=$[[ inputs.enforceUrl ]]"
export "DEVELOCITY_CAPTURE_FILE_FINGERPRINTS=$[[ inputs.captureFileFingerprints ]]"
export "GRADLE_PLUGIN_REPOSITORY_URL=$[[ inputs.gradlePluginRepositoryUrl ]]"
export "GRADLE_PLUGIN_REPOSITORY_USERNAME=$[[ inputs.gradlePluginRepositoryUsername ]]"
export "GRADLE_PLUGIN_REPOSITORY_PASSWORD=$[[ inputs.gradlePluginRepositoryPassword ]]"
}
createGradleInit
createShortLivedToken "$[[ inputs.url ]]" "$[[ inputs.shortLivedTokensExpiry ]]"
injectDevelocityForGradle