forked from line/armeria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.gradle
861 lines (733 loc) · 31.7 KB
/
build.gradle
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
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'io.spring.gradle:dependency-management-plugin:0.6.1.RELEASE'
classpath 'com.google.gradle:osdetector-gradle-plugin:1.4.0'
}
}
apply plugin: 'com.google.osdetector'
ext.javaProjects = subprojects.findAll { it.name != 'site' }
ext.publishedJavaProjects = javaProjects.findAll { it.name != 'it' }
ext.gitPath = getGitPath()
ext.repoStatus = getRepoStatus()
ext.versionOf = { project.property("${it}.version") }
ext.requestedTaskNames = gradle.startParameter.taskRequests.inject([]) { a, b -> a + b.args }
ext.isPublishing = {
gradle.taskGraph.allTasks.find { it.name =~ /(?:^|:)publish[^:]*ToMaven[^:]*$/ } != null
}
// Configure all projects
allprojects {
apply plugin: 'eclipse'
apply plugin: 'idea'
}
// Configure all Java projects
configure(javaProjects) {
// Apply common plugins and define repositories.
apply plugin: 'java'
apply plugin: 'jacoco'
apply plugin: 'checkstyle'
apply plugin: 'maven-publish'
apply plugin: 'signing'
apply plugin: 'io.spring.dependency-management'
repositories {
mavenLocal()
mavenCentral()
}
// Set the artifact ID.
if (project.name == 'core') {
project.archivesBaseName = 'armeria'
} else {
project.archivesBaseName = "armeria-$project.name"
}
// Common properties and functions.
ext {
pomFile = file("${project.buildDir}/generated-pom.xml")
isReleaseVersion = !(project.version =~ /-SNAPSHOT$/)
versionOf = rootProject.ext.versionOf
onIdeImport = { Closure action ->
if (!requestedTaskNames.empty) {
return
}
if (System.getProperty('idea.active') == 'true' ||
System.getProperty('eclipse.home.location') != null) {
project.afterEvaluate {
action.delegate = project
action()
}
}
}
}
// Use the dependency management plugin to keep the versions and exclusions in a single place.
dependencyManagement {
dependencies {
// AssertJ
dependency "org.assertj:assertj-core:${ext.versionOf('assertj')}"
// Completable-futures
dependency "com.spotify:completable-futures:${ext.versionOf('completable-futures')}"
// FastUtil
dependency "it.unimi.dsi:fastutil:${ext.versionOf('fastutil')}"
// gRPC
dependencySet(group: 'io.grpc', version: ext.versionOf('grpc')) {
entry('grpc-core') {
exclude 'com.google.code.findbugs:jsr305'
}
entry 'grpc-stub'
entry 'grpc-protobuf'
entry('grpc-interop-testing') {
exclude 'io.netty:netty-codec-http2'
exclude 'com.google.guava:guava-jdk5'
}
}
// Guava
dependencySet(group: 'com.google.guava', version: ext.versionOf('guava')) {
entry 'guava'
entry('guava-testlib') {
exclude 'com.google.code.findbugs:jsr305'
exclude 'com.google.errorprone:error_prone_annotations'
}
}
// Guava-helper
dependency "jp.skypencil.guava:helper:${ext.versionOf('guava-helper')}"
// Hamcrest
dependency "org.hamcrest:hamcrest-library:${ext.versionOf('hamcrest')}"
// HBase client
dependency("org.apache.hbase:hbase-shaded-client:${ext.versionOf('hbase-client')}") {
exclude 'org.slf4j:slf4j-log4j12'
}
// HttpClient
dependency("org.apache.httpcomponents:httpclient:${ext.versionOf('httpclient')}") {
exclude 'commons-logging:commons-logging'
}
// Jackson
dependencySet(group: 'com.fasterxml.jackson.core', version: ext.versionOf('jackson')) {
entry 'jackson-core'
entry 'jackson-annotations'
entry 'jackson-databind'
}
// Jetty
dependencySet(group: 'org.eclipse.jetty', version: ext.versionOf('jetty')) {
entry 'jetty-server'
entry 'jetty-webapp'
entry 'jetty-annotations'
entry 'apache-jsp'
entry 'apache-jstl'
}
dependency "org.eclipse.jetty.http2:http2-server:${ext.versionOf('jetty')}"
// Jetty ALPN support
dependency "org.eclipse.jetty.alpn:alpn-api:${ext.versionOf('jetty-alpn-api')}"
dependency "org.mortbay.jetty.alpn:jetty-alpn-agent:${ext.versionOf('jetty-alpn-agent')}"
// JSON-unit
dependencySet(group: 'net.javacrumbs.json-unit', version: ext.versionOf('jsonunit')) {
entry 'json-unit'
entry 'json-unit-fluent'
}
// JSR305
dependency 'com.google.code.findbugs:jsr305:3.0.1'
// jUnit
dependency "junit:junit:${ext.versionOf('junit')}"
// Logback
dependency "ch.qos.logback:logback-classic:${ext.versionOf('logback')}"
// Metrics
dependency "io.dropwizard.metrics:metrics-core:${ext.versionOf('metrics')}"
// Mockito
dependency "org.mockito:mockito-core:${ext.versionOf('mockito')}"
// Netty
dependencySet(group: 'io.netty', version: ext.versionOf('netty')) {
entry 'netty-transport'
entry 'netty-handler'
entry 'netty-codec-http2'
entry 'netty-resolver-dns'
}
dependency "io.netty:netty-tcnative-boringssl-static:${ext.versionOf('netty-tcnative')}"
dependency "org.javassist:javassist:${ext.versionOf('javassist')}"
// Reactive Streams
dependency "org.reactivestreams:reactive-streams:${ext.versionOf('reactive-streams')}"
// Reflections
dependency("org.reflections:reflections:${ext.versionOf('reflections')}") {
exclude 'com.google.code.findbugs:annotations'
}
// Retrofit2
dependencySet(group: 'com.squareup.retrofit2', version: ext.versionOf('retrofit2')) {
entry 'retrofit'
entry 'adapter-guava'
entry 'converter-jackson'
}
// SLF4J
dependencySet(group: 'org.slf4j', version: ext.versionOf('slf4j')) {
entry 'slf4j-api'
entry 'jul-to-slf4j'
entry 'jcl-over-slf4j'
entry 'log4j-over-slf4j'
}
// Thrift
dependency("org.apache.thrift:libthrift:${ext.versionOf('thrift')}") {
exclude 'org.apache.httpcomponents:httpcore'
exclude 'org.apache.httpcomponents:httpclient'
}
// Tomcat
dependencySet(group: 'org.apache.tomcat.embed', version: ext.versionOf('tomcat')) {
entry 'tomcat-embed-core'
entry 'tomcat-embed-jasper'
entry 'tomcat-embed-el'
}
// Zipkin
dependencySet(group: 'io.zipkin.brave', version: ext.versionOf('brave')) {
entry 'brave-core'
entry 'brave-http'
}
// ZooKeeper
dependency "org.apache.zookeeper:zookeeper:${ext.versionOf('zookeeper')}"
// ZooKeeper JUnit
dependency "org.dmonix.junit:zookeeper-junit:${ext.versionOf('zookeeper-junit')}"
// Kafka
dependency "org.apache.kafka:kafka-clients:${ext.versionOf('kafka')}"
}
}
// Common dependencies
configurations {
javaAgent
}
dependencies {
// All projects currently require ':core' (except itself)
if (project.name != 'core') {
compile project(':core')
}
// JSR305
compile 'com.google.code.findbugs:jsr305' // Can't use compileOnly due to Javadoc errors
// Jetty ALPN support
compileOnly('org.eclipse.jetty.alpn:alpn-api')
javaAgent 'org.mortbay.jetty.alpn:jetty-alpn-agent'
// Logging
compile 'org.slf4j:slf4j-api'
testCompile 'org.slf4j:jul-to-slf4j'
testRuntime 'ch.qos.logback:logback-classic'
['jcl-over-slf4j', 'log4j-over-slf4j'].each {
testRuntime "org.slf4j:$it"
}
// Test-time dependencies
testCompile 'junit:junit'
testCompile 'org.hamcrest:hamcrest-library'
testCompile 'org.assertj:assertj-core'
testCompile 'org.mockito:mockito-core'
testCompile 'org.apache.httpcomponents:httpclient'
testCompile 'net.javacrumbs.json-unit:json-unit'
testCompile 'net.javacrumbs.json-unit:json-unit-fluent'
}
// Copy test resources to the same directory with test classes, because some tests such as
// TomcatServiceTest assume so.
sourceSets {
test {
def testOutputDir = "${project.buildDir}/classes/test"
output.classesDir = testOutputDir
output.resourcesDir = testOutputDir
// Add shared logback configuration.
resources.srcDir "${rootProject.projectDir}/settings/logback"
// Add 'java-shared' directory to the source set, if exists.
def javaSharedDir = "${project.projectDir}/src/test/java-shared"
if (project.file(javaSharedDir).isDirectory()) {
java.srcDir javaSharedDir
}
// Add 'resources-shared' directory to the source set, if exists.
def resourcesSharedDir = "${project.projectDir}/src/test/resources-shared"
if (project.file(resourcesSharedDir).isDirectory()) {
resources.srcDir resourcesSharedDir
}
// Add the 'java-shared' directory of the 'core' project to the source set.
if (project.name != 'core') {
java.srcDir "${rootProject.projectDir}/core/src/test/java-shared"
}
}
}
// Enforce checkstyle rules.
checkstyle {
def checkstyleConfigDir = "${rootProject.projectDir}/settings/checkstyle"
configFile = project.file("${checkstyleConfigDir}/checkstyle.xml")
configProperties = [ 'checkstyleConfigDir': "$checkstyleConfigDir" ]
toolVersion = '7.1'
}
task checkstyle(group: 'Verification',
description: 'Runs the checkstyle rules.')
tasks.checkstyle.dependsOn 'checkstyleMain'
tasks.checkstyle.dependsOn 'checkstyleTest'
// Enable full exception logging for test failures.
test {
testLogging {
exceptionFormat = 'full'
}
}
// Enable JaCoCo test coverage when '-Pcoverage' option is specified.
def jacocoEnabled = project.hasProperty('coverage')
test {
jacoco {
enabled = jacocoEnabled
append = false
}
}
jacocoTestReport {
reports {
xml.enabled jacocoEnabled
}
}
if (jacocoEnabled) {
tasks.test.finalizedBy(jacocoTestReport)
}
// Require Java 8 to build the project.
tasks.withType(JavaCompile) {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
options.encoding = 'UTF-8'
options.warnings = false
options.debug = true
}
// Prepare the JVM agent that enables TLS ALPN extension.
task copyJavaAgents(type: Copy) {
from configurations.javaAgent
into "${rootProject.buildDir}"
rename { String fileName ->
fileName.replaceFirst("-[0-9]+\\.[0-9]+\\.[0-9]+(?:\\.[^\\.]+)?\\.jar", ".jar")
}
}
// Add common JVM options such as TLS ALPN agent, max memory and leak detection.
tasks.withType(JavaForkOptions) {
dependsOn 'copyJavaAgents'
// Use larger heap when test coverage is enabled.
maxHeapSize = jacocoEnabled ? '384m' : '128m'
// Enable leak detection when '-Pleak' option is specified.
if (project.hasProperty('leak')) {
systemProperties 'io.netty.leakDetectionLevel': 'paranoid'
}
jvmArgs "-javaagent:${rootProject.buildDir}/jetty-alpn-agent.jar"
}
// Delete the source files generated by the Thrift compiler.
clean {
[ 'main', 'test' ].each {
delete "${project.projectDir}/src/$it/gen-java"
}
}
// Compile the Thrift service definitions.
task compileThrift {
def thriftPath = "${rootProject.projectDir}/gradle/thrift/thrift.${osdetector.classifier}"
[ 'main', 'test' ].each { scope ->
def inputDir = "${project.projectDir}/src/${scope}/thrift"
def outputDir = "${project.projectDir}/src/${scope}/gen-java"
if (project.file(inputDir).isDirectory()) {
inputs.dir inputDir
outputs.dir outputDir
project.sourceSets[scope].java.srcDir outputDir
doLast {
project.fileTree(inputDir) {
include '**/*.thrift'
}.each { sourceFile ->
project.mkdir(outputDir)
project.exec {
commandLine thriftPath,
'-gen', 'java',
'-out', outputDir,
'-I', "${sourceFile.parentFile.absolutePath}",
sourceFile.absolutePath
}
}
}
}
}
}
// Ensure the generated Thrift source files are available during the build.
tasks.compileJava.dependsOn(tasks.compileThrift)
onIdeImport { tasks.compileThrift.execute() }
if (project in publishedJavaProjects) {
// Generate version.properties, similar to Netty.
task versionProperties {
doLast {
def artifactId = project.archivesBaseName
def propsFile = project.file(
"${project.sourceSets.main.output.resourcesDir}/META-INF/${project.group}.versions.properties")
logger.info("Generating versions.properties for ${artifactId} ..")
def props = new Properties()
rootProject.ext.repoStatus.each { k, v ->
props["${artifactId}.${k}"] = v
}
project.mkdir(propsFile.parent)
logger.info("Writing ${propsFile} ..")
propsFile.withOutputStream { props.store(it, null) }
}
}
// Ensure version.properties is available during the build.
tasks.processResources.dependsOn(tasks.versionProperties)
onIdeImport { tasks.versionProperties.execute() }
// Generate a source JAR.
task sourceJar(type: Jar) {
classifier = 'sources'
from sourceSets.main.allSource
}
// Generate a javadoc JAR.
javadoc {
options {
quiet()
addBooleanOption('Xdoclint:all').value = true
addBooleanOption('Xdoclint:-missing').value = true
}
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
// Generate source/javadoc JARs only when publishing.
tasks.sourceJar.onlyIf {
isPublishing() || requestedTaskNames.find { it =~ /(?:^|:)sourceJar$/ }
}
[tasks.javadoc, tasks.javadocJar].each {
it.onlyIf {
isPublishing() || requestedTaskNames.find { it =~ /(?:^|:)javadoc(?:Jar)?$/ }
}
}
// Sign and publish all artifacts.
artifacts {
archives jar
archives sourceJar
archives javadocJar
}
signing {
required { signatory != null && project.ext.isReleaseVersion }
sign configurations.archives
}
publishing {
repositories {
maven {
if (project.ext.isReleaseVersion) {
url 'https://oss.sonatype.org/service/local/staging/deploy/maven2/'
} else {
url 'https://oss.sonatype.org/content/repositories/snapshots/'
}
credentials {
username = project.properties.ossrhUsername
password = project.properties.ossrhPassword
}
}
}
publications {
jar(MavenPublication) {
artifactId "${project.archivesBaseName}"
pom.withXml {
NodeList children = asNode().children()
Node dependencies = children.find { it.name().localPart == 'dependencies' } as Node
// Insert the elements required by OSSRH.
children[children.indexOf(dependencies) - 1] + {
resolveStrategy = Closure.DELEGATE_FIRST
name "${project.archivesBaseName}"
description "Asynchronous RPC/API client/server library built on top of Java 8, " +
"Netty 4.1, HTTP/2, and Thrift (${project.archivesBaseName})"
url 'http://line.github.io/armeria/'
licenses {
license {
name 'The Apache License, Version 2.0'
url 'http://www.apache.org/license/LICENSE-2.0.txt'
distribution 'repo'
}
}
inceptionYear 2015
organization {
name 'LINE Corporation'
url 'http://linecorp.com/en/'
}
developers {
developer {
id 'linecorp.com'
name 'LINE Corporation'
url 'http://linecorp.com/en/'
}
}
scm {
url 'https://github.com/line/armeria'
connection 'scm:git:https://github.com/line/armeria.git'
developerConnection 'scm:git:ssh://[email protected]/line/armeria.git'
}
}
// Remove:
// - the compileOnly dependencies
// - the dependencies provided by the platform
// - the dependencies in the 'javaAgent' configuration
dependencies.children().removeAll {
it.artifactId.text() in ['jsr305', 'alpn-api', 'jetty-alpn-agent']
}
// Work around the bug where the maven-publish plugin sets the scope of all
// dependencies to 'runtime'.
// https://discuss.gradle.org/t/maven-publish-plugin-generated-pom-making-dependency-scope-runtime/7494
def compileDeps = configurations.compile.dependencies.collectEntries { [it.name, it] } +
configurations.compileOnly.dependencies.collectEntries { [it.name, it] }
def allDeps = compileDeps +
configurations.runtime.dependencies.collectEntries { [it.name, it] }
dependencies.children().each {
if (compileDeps.containsKey(it.artifactId.text())) {
it.scope*.value = 'compile'
}
// Add <optional>true</optional> to optional dependencies.
def dep = allDeps[it.artifactId.text()]
if (dep.hasProperty('optional') && dep.optional) {
if (it.optional) {
it.optional.value = true
} else {
it.appendNode('optional', 'true')
}
}
}
}
from components.java
artifact(sourceJar) {
classifier = 'sources'
}
artifact(javadocJar) {
classifier = 'javadoc'
}
// Sign the pom.xml and artifacts.
if (signing.required) {
// Sign the pom.xml.
pom.withXml {
writeTo(project.ext.pomFile)
def pomAscFile = signing.sign(project.ext.pomFile).signatureFiles[0]
artifact(pomAscFile) {
classifier = null
extension = 'pom.asc'
}
project.ext.pomFile.delete()
}
// Sign the artifacts.
project.tasks.signArchives.signatureFiles.each {
artifact(it) {
def matcher = it.file =~ /-(sources|javadoc)\.jar\.asc$/
if (matcher.find()) {
classifier = matcher.group(1)
} else {
classifier = null
}
extension = 'jar.asc'
}
}
}
}
}
}
model {
tasks.publishJarPublicationToMavenLocal {
dependsOn(project.tasks.signArchives)
}
tasks.publishJarPublicationToMavenRepository {
dependsOn(project.tasks.signArchives)
}
tasks.signArchives {
onlyIf { isPublishing() }
}
}
task install(dependsOn: publishToMavenLocal,
group: 'Publishing',
description: 'An alias of publishToMavenLocal')
}
// Print only interesting test results and progress, except when running from IntelliJ IDEA which has
// its own output listener.
if (System.getProperty('idea.no.launcher') == null) {
test {
def buf = new StringBuilder()
def printedProgress = false
// Record the test output.
onOutput { TestDescriptor td, TestOutputEvent toe ->
buf << toe.message
}
// Print the test output when the test failed or the test output contains an Exception or an Error.
afterTest { TestDescriptor td, TestResult tr ->
if (tr.resultType == TestResult.ResultType.FAILURE || buf =~ /(?:Exception|Error|Throwable):/) {
def simpleClassName = td.className.substring(td.className.lastIndexOf('.') + 1)
// Add an empty line if the test progress dots were printed.
if (printedProgress) {
println()
println()
printedProgress = false
}
def subject = "${simpleClassName}.${td.name}: ${tr.resultType}"
println subject
if (buf.length() != 0) {
println '-' * subject.length()
println buf
if (buf[buf.length() - 1] != '\n') {
println()
}
}
} else {
// Print the progress dots.
print '.'
System.out.flush()
printedProgress = true
}
buf.length = 0
}
afterSuite { TestDescriptor td, TestResult tr ->
if (printedProgress) {
print ' '
System.out.flush()
}
}
doLast {
if (printedProgress) {
println()
}
}
}
}
}
task release(group: 'Publishing',
description: 'Releases a new version.') {
doLast {
if (gitPath == null) {
throw new InvalidUserDataException('Git is not available.')
}
if (!project.hasProperty('releaseVersion') || !project.hasProperty('nextVersion')) {
throw new InvalidUserDataException(
"Specify 'releaseVersion' and 'nextVersion' properties.${System.lineSeparator()}" +
'e.g. ./gradlew release -PreleaseVersion=0.1.2 -PnextVersion=0.1.3-SNAPSHOT')
}
def releaseVersion = project.property('releaseVersion')
def nextVersion = project.property('nextVersion')
// Validate the specified version numbers.
if (!(releaseVersion =~ /^[0-9]+\.[0-9]+\.[0-9]+$/)) {
throw new InvalidUserDataException("invalid release version: ${releaseVersion}")
}
if (!(nextVersion =~ /^[0-9]+\.[0-9]+\.[0-9]+-SNAPSHOT$/)) {
throw new InvalidUserDataException("invalid next version: ${nextVersion}")
}
// Ensure the repository is upstream.
def repoUrl = executeCommand(gitPath, 'config', '--get', 'remote.origin.url').trim()
if (!(repoUrl =~ /github.com:line\/armeria\.git$/)) {
throw new InvalidUserDataException('Release must be performed at the upstream repository.')
}
// Ensure the repository is clean.
def gitStatusOut = executeCommand(gitPath, 'status', '--porcelain')
if (!gitStatusOut.empty) {
throw new InvalidUserDataException(
"Git repository is not clean:${System.lineSeparator()}${gitStatusOut}")
}
def tag = "$rootProject.name-$releaseVersion"
def gradlePropsFile = project.file("${project.projectDir}/gradle.properties")
def gradlePropsContent = gradlePropsFile.getText('ISO-8859-1')
def versionPattern = /\nversion=[0-9]+\.[0-9]+\.[0-9]+-SNAPSHOT(\r?\n)/
assert gradlePropsContent =~ versionPattern
// Update the version to the release version, commit and tag.
gradlePropsFile.write(gradlePropsContent.replaceFirst(versionPattern, "\nversion=${releaseVersion}\$1"),
'ISO-8859-1')
executeCommand(gitPath, 'add', gradlePropsFile.toString())
executeCommand(gitPath, 'commit', '-m', "Release $tag")
executeCommand(gitPath, 'tag', tag)
// Update the version to the next version.
executeCommand(gitPath, 'reset', '--hard', 'HEAD^')
gradlePropsFile.write(gradlePropsContent.replaceFirst(versionPattern, "\nversion=${nextVersion}\$1"),
'ISO-8859-1')
executeCommand(gitPath, 'add', gradlePropsFile.toString())
// Update the version in the Sphinx conf.py as well.
def sphinxConfFile = project.file("${project.projectDir}/site/src/sphinx/conf.py")
def sphinxConfContent = sphinxConfFile.getText('UTF-8')
def sphinxConfVersionPattern = /\n( *)release = '[0-9]+\.[0-9]+\.[0-9]+'(\r?\n)/
assert sphinxConfContent =~ sphinxConfVersionPattern
sphinxConfFile.write(sphinxConfContent.replaceFirst(sphinxConfVersionPattern, "\n\$1release = '${releaseVersion}'\$2"))
executeCommand(gitPath, 'add', sphinxConfFile.toString())
// Commit.
executeCommand(gitPath, 'commit', '-m', "Update the project version to ${nextVersion}")
// Push the commits and tags.
executeCommand(gitPath, 'push', 'origin')
executeCommand(gitPath, 'push', 'origin', tag)
println()
println "Tagged: ${tag}"
println '-' * (tag.length() + 8)
println "1. Upload the artifacts to the staging repository and prepare the web site:"
println()
println " git checkout $tag"
println " ./gradlew clean publish site"
println()
println '2. Close and release the staging repository at:'
println()
println ' https://oss.sonatype.org/'
println()
println '3. Close the milestone and set its release date at:'
println()
println ' https://github.com/line/armeria/milestones'
println()
println '4. Update the release note at:'
println()
println " https://github.com/line/armeria/releases/tag/${tag}"
println()
println "5. Copy the web site generated to the 'gh-pages' branch. e.g."
println()
println ' cd ../site-armeria'
println ' rm -fr .[bd]* *'
println ' rsync -aiP ../upstream-armeria/site/build/site/ .'
println ' git add -A .'
println " git commit --amend -m 'Deploy the web site'"
println ' git push --force'
}
}
private def getGitPath() {
if (rootProject.hasProperty('gitPath')) {
return rootProject.property('gitPath')
}
// Find the location of the 'git' command.
try {
if (osdetector.os == 'windows') {
return executeCommand('where.exe', 'git.exe')
} else {
return executeCommand('which', 'git')
}
} catch (e) {
logger.debug('Git not available:', e)
return null
}
}
private def getRepoStatus() {
// Make sure this method is executed only once during the build.
assert !rootProject.hasProperty('repoStatus')
// The default values taken from Netty.
def result = [
version : project.version,
buildDate : new Date().format('yyyy-MM-dd HH:mm:ss Z'), // same with git log date format
longCommitHash : '0000000000000000000000000000000000000000',
shortCommitHash : '0000000',
commitDate : '1970-01-01 00:00:00 +0000',
repoStatus : 'unknown'
]
// Make sure 'git' is available.
if (gitPath == null) {
return result
}
// Do not run 'git' if the project is not from a Git repository.
if (!rootProject.file("${rootProject.projectDir}/.git").isDirectory()) {
return result
}
// Retrieve the repository status from the Git repository.
try {
def gitLogOut = executeCommand(gitPath, 'log', '-1', '--format=format:%h%x20%H%x20%cd', '--date=iso')
if (gitLogOut) {
logger.info("Latest commit: ${gitLogOut}")
def tokens = gitLogOut.tokenize(' ')
result.shortCommitHash = tokens[0]
result.longCommitHash = tokens[1]
result.commitDate = tokens[2..4].join(' ')
}
def gitStatusOut = executeCommand(gitPath, 'status', '--porcelain')
if (!gitStatusOut.empty) {
result.repoStatus = 'dirty'
logger.info("Repository is dirty:${System.lineSeparator()}${gitStatusOut}")
} else {
result.repoStatus = 'clean'
}
} catch (e) {
logger.warn('Failed to retrieve the repository status:', e)
}
return result
}
private static String executeCommand(String[] command) {
def proc = command.execute()
proc.waitFor()
if (proc.exitValue() != 0) {
throw new IOException(
"'${command}' exited with a non-zero exit code: ${proc.exitValue()}:" +
"${System.lineSeparator()}${proc.err.text}")
}
return proc.in.text.trim()
}