-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbuild.gradle
More file actions
527 lines (422 loc) · 17.8 KB
/
build.gradle
File metadata and controls
527 lines (422 loc) · 17.8 KB
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
// -*- coding: utf-8; mode: conf-javaprop -*-
// SPDX-FileCopyrightText: 2016 ale5000
// SPDX-License-Identifier: GPL-3.0-or-later WITH LicenseRef-Archive-packaging-exception
buildscript {
apply from: 'dependencies.gradle'
}
plugins {
id 'base'
id 'maven-publish'
//id 'com.github.hierynomus.license-report' version '0.15.0'
//id 'com.github.spotbugs' version '4.7.6'
}
configure(project) {
defaultTasks 'tasks'
ext {
moduleProps = providers.fileContents(layout.projectDirectory.file('zip-content/module.prop'))
.asText
.map {
final Properties p = new Properties()
p.load(new StringReader(it))
p
} as Provider<Properties>
//moduleProps = providers.properties(layout.projectDirectory.file('zip-content/module.prop')) as Provider<Properties>
//lazyDescription = moduleProps.map { it.getProperty('description', 'Unknown flashable ZIP') }
lazyVersion = moduleProps.map { it.getProperty('version', 'v0.0.0-unknown').trim().toLowerCase(Locale.ROOT) }
//lazyGroup = moduleProps.map { it.getProperty('group', 'unknown') }
lazyProjectId = moduleProps.map { it.getProperty('id', '').trim() }
lazyOsName = providers.systemProperty('os.name')
}
if (!JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_17)) {
throw new GradleException('Java 17 or later is required.')
}
}
/* ===FUNCTIONS=== */
import groovy.transform.Memoized
@Memoized
private Provider<String> getProjectId() {
ext.lazyProjectId.map { it ?: { throw new InvalidUserDataException('id in "zip-content/module.prop" is empty or not set.') }() }
}
@Memoized
private Provider<String> getLazyAuthor() {
moduleProps.map { it.getProperty('author', 'unknown') }
}
@Memoized
private Provider<String> getLazyDescription() {
moduleProps.map { it.getProperty('description', 'Unknown flashable ZIP.') }
}
@Memoized
private Provider<String> getLazyGroup() {
moduleProps.map { it.getProperty('group', 'unknown') }
}
@Memoized
private Provider<String> getLazyOrg() {
moduleProps.map { it.getProperty('organization', 'unknown') }
}
@Memoized
private Provider<String> getLazyLicense() {
moduleProps.map { it.getProperty('license', 'unknown') }
}
@Memoized
private Provider<String> getScriptExt() {
ext.lazyOsName.map { it.toLowerCase(Locale.ROOT).contains('windows') ? '.bat' : '.sh' }
}
@Memoized
private Provider<String> getGitCommitHash() {
providers.provider { layout.projectDirectory.dir('.git').asFile.exists() }.flatMap { exists ->
if(!exists) {
return providers.provider { 'NOGIT' }
}
providers.exec {
commandLine 'git', 'rev-parse', '--short=8', 'HEAD'
}.standardOutput.asText.map { "g${ it.trim() }" }.orElse('unknown')
}
}
@Memoized
private Provider<String> getMavenVersion() {
ext.lazyVersion.map { it.endsWith('-alpha') ? "${it}-SNAPSHOT" : it }
}
private Provider<String> getZipName(String variant = '*') {
ext.lazyVersion.flatMap { v ->
getProjectId().zip(getGitCommitHash()) { id, hash ->
"${id}-${v}-${hash}-${variant}-by-ale5000-signed.zip"
}
}
}
/*private Provider<String> getZipName(String variant = '*') {
providers.zip(getProjectId(), getGitCommitHash(), ext.lazyVersion) { id, hash, v ->
"${id}-${v}-${hash}-${variant}-by-ale5000-signed.zip"
}
}*/
/*private void configureSigning(def android, File keystorePropsFile) {
if(!keystorePropsFile.exists()) return
if(android == null) throw new GradleException('android is null inside configureSigning()')
logger.lifecycle 'Signed build'
Properties keystoreProps = new Properties()
keystoreProps.load(new FileInputStream(keystorePropsFile))
String keyStorePassword
boolean fallbackToEnv = keystoreProps.containsKey('fallbackToEnv') && keystoreProps['fallbackToEnv'] == 'true'
if(keystoreProps.containsKey('keyStorePassword'))
keyStorePassword = keystoreProps['keyStorePassword']
else if(fallbackToEnv)
keyStorePassword = System.getenv('KEYSTORE_PASSWORD')
if(keyStorePassword == null || keyStorePassword.isEmpty())
throw new InvalidUserDataException('Keystore password is empty')
android.signingConfigs {
config {
storeFile = rootProject.file(keystoreProps['storeFile'])
storePassword = keyStorePassword
keyAlias = keystoreProps['keyAlias']
keyPassword = keyStorePassword
}
}
android.buildTypes.release.signingConfig android.signingConfigs.config
}*/
/* ===CLASSES=== */
import groovy.transform.PackageScope
@PackageScope
final class Bridge {
private static MavenPublication mavenPub
private Bridge() {}
private static void init(MavenPublication mavenPub) {
if(this.mavenPub == null) {
this.mavenPub = mavenPub
}
}
@PackageScope
static MavenPublication getMavenPub() {
return this.mavenPub
}
}
/* ===BLOCKS=== */
base {
archivesName.set getProjectId()
}
project.afterEvaluate {
// Keep it as lazy as possible while ensuring values show up correctly in 'gradlew properties',
// since these Gradle properties and the maven-publish plugin don't support Providers.
description = "${-> lazyDescription.get() }"
version = "${-> ext.lazyVersion.get() }"
group = "${-> lazyGroup.get() }"
publishing {
publications {
maven(MavenPublication) {
groupId = "com.github.${-> lazyOrg.get() }"
artifactId = "${-> getProjectId().get() }"
version = "${-> getMavenVersion().get() }"
pom {
name = "${-> project.name }"
packaging = 'zip'
licenses {
license {
name = "${-> lazyLicense.get() }"
url = 'https://www.gnu.org/licenses/gpl-3.0.txt'
distribution = 'repo'
comments = 'The full text of the licenses can be found in the LICENSES directory contained in the ZIP archive.'
}
}
developers {
developer {
id = "${-> lazyAuthor.get() }"
}
}
}
}
}
}
}
/* ===TASKS=== */
tasks.register('cleanRecoveryOutput', Delete) {
group = '- Cleanup'
description = 'Deletes the recovery simulator output directory.'
delete layout.projectDirectory.dir('recovery-simulator/output')
}
tasks.named('clean') {
group = '- Cleanup'
dependsOn 'cleanRecoveryOutput'
}
tasks.register('cleanCache', Delete) {
group = '- Cleanup'
description = 'Deletes the local cache directory.'
delete layout.projectDirectory.dir('cache')
}
tasks.register('cleanPubTmpFiles', Delete) {
group = '- Cleanup'
dependsOn 'cleanGeneratePomFileForMavenPublication'
delete layout.buildDirectory.dir('tmp/publishMavenPublicationToMavenLocal')
delete layout.buildDirectory.dir('tmp/generatedChecksums')
doLast {
['publications/maven', 'publications', 'tmp'].each {
if(layout.buildDirectory.dir(it).get().asFile?.delete()) {
logger.info "Removed empty temporary folder: ${-> it}"
}
}
}
}
tasks.register('distClean') {
group = '- Cleanup'
description = 'Cleans all build outputs, local caches, and removes all untracked/ignored files via Git.'
dependsOn 'clean', 'cleanCache', 'cleanPubTmpFiles'
doLast {
if (layout.projectDirectory.dir('.git').asFile.exists()) {
exec {
commandLine 'git', 'clean', '-xdf'
ignoreExitValue = true
}
} else {
logger.warn 'WARNING: Skipping git clean: .git directory not found.'
}
}
}
tasks.register('buildOta', Exec) {
group = '- Flashable ZIP'
description = 'Build the flashable zip [Full edition].'
outputs.cacheIf('Avoid caching large binary artifacts to save disk space and network bandwidth.') { false }
['LICENSES', 'conf', 'docs', 'lib', 'zip-content'].each { folder ->
inputs.dir(layout.projectDirectory.dir(folder)).withPropertyName("buildInputDir_${folder}")
}
inputs.files(
layout.projectDirectory.dir('tools').asFileTree.matching { include '*.jar' },
layout.projectDirectory.files('CHANGELOG.rst', 'build.sh'),
layout.projectDirectory.asFileTree.matching { include 'LICENSE*.rst' }
).withPropertyName('buildInputFiles')
outputs.file(layout.buildDirectory.file(getZipName('full'))).withPropertyName('buildOutputFileFull')
workingDir = layout.projectDirectory
executable = "${-> layout.projectDirectory.file("build${getScriptExt().get()}") }"
environment([
'BUILD_TYPE': 'full',
'NO_PAUSE' : '1'
])
doFirst {
logger.lifecycle 'Building the flashable zip with Gradle...'
}
}
tasks.register('buildOtaOSS', Exec) {
group = '- Flashable ZIP'
description = 'Build the flashable zip [OSS edition].'
outputs.cacheIf('Avoid caching large binary artifacts to save disk space and network bandwidth.') { false }
['LICENSES', 'conf', 'docs', 'lib', 'zip-content'].each { folder ->
inputs.dir(layout.projectDirectory.dir(folder)).withPropertyName("buildInputDir_${folder}")
}
inputs.files(
layout.projectDirectory.dir('tools').asFileTree.matching { include '*.jar' },
layout.projectDirectory.files('CHANGELOG.rst', 'build.sh'),
layout.projectDirectory.asFileTree.matching { include 'LICENSE*.rst' }
).withPropertyName('buildInputFiles')
outputs.file(layout.buildDirectory.file(getZipName('oss'))).withPropertyName('buildOutputFileOss')
workingDir = layout.projectDirectory
executable = "${-> layout.projectDirectory.file("build${getScriptExt().get()}") }"
environment([
'BUILD_TYPE': 'oss',
'NO_PAUSE' : '1'
])
doFirst {
logger.lifecycle 'Building the flashable zip (open-source components only) with Gradle...'
}
}
tasks.named('assemble') {
group = null
description = 'Alias of "buildOtaOSS" task.'
dependsOn 'buildOtaOSS'
}
tasks.named('build') {
group = null
description = 'Alias of "buildOtaOSS" task.'
}
tasks.register('installTest', Exec) {
group = 'verification'
description = 'Test the flashable zip in a simulated Android recovery environment on your PC.'
doNotTrackState('Force task execution by disabling up-to-date checks.')
mustRunAfter buildOta, buildOtaOSS
workingDir = layout.projectDirectory
executable = "${-> layout.projectDirectory.dir('recovery-simulator').file("recovery${ getScriptExt().get() }") }"
final Provider<RegularFile> outFilesProv = layout.buildDirectory.file('*.zip')
argumentProviders.add({ [outFilesProv.get().asFile.absolutePath] } as CommandLineArgumentProvider)
environment([
'LIVE_SETUP_ALLOWED': 'false', /* Live setup doesn't work when executed through Gradle */
'NO_PAUSE': '1',
'BB_GLOBBING': '1'
])
}
tasks.register('test') {
dependsOn installTest
}
tasks.named('wrapper') {
gradleVersion = "${-> targetGradleVersion}"
distributionSha256Sum = "${-> targetGradleSha256Sum}"
doFirst {
logger.lifecycle 'Gradle wrapper update status:'
logger.lifecycle "- Current version: ${-> gradle.gradleVersion}"
logger.lifecycle "- Target version: ${-> targetGradleVersion}"
}
}
/* === PUBLISHING === */
final Provider<FileTree> zipFilesTree = getZipName().map { name -> layout.buildDirectory.asFileTree.matching { include name } }
/*abstract class DynamicArtifactSource implements ValueSource<Integer, DynamicArtifactParams> {
private static final List<String> artifactTypes = ['oss', 'full'].asImmutable()
interface DynamicArtifactParams extends ValueSourceParameters {
@InputFiles ConfigurableFileCollection getZipFiles()
}
@Override
Integer obtain() {
final HashSet<String> seen = []
final MavenPublication mavenPub = Bridge.getMavenPub()
parameters.zipFiles.files.each { foundFile ->
String type = artifactTypes.find { foundFile.name.contains("-${it}-") } ?: { throw new GradleException("Publishing failed: File ${foundFile.name} is missing a valid build type.") }()
if(!seen.add(type)) throw new GradleException("Publishing failed: The type '${type}' already exists.")
String clsf = (type == 'oss' ? null : type)
mavenPub.artifact(foundFile) { extension = 'zip'; classifier = clsf; builtBy 'collectArtifacts' }
}
if(seen.isEmpty()) throw new GradleException("Publishing failed: No artifact found. Check if build tasks were executed.")
seen.size()
}
}
final Provider<Integer> artifactsProcessor = providers.of(DynamicArtifactSource) {
parameters.zipFiles.setFrom zipFilesTree
}*/
import java.security.MessageDigest
import java.security.DigestInputStream
File generateChecksum(targetFile, hashExt, checksumsDir) {
final MessageDigest md = MessageDigest.getInstance(hashExt.toUpperCase().replace('SHA256', 'SHA-256').replace('SHA1', 'SHA-1'))
final byte[] buffer = new byte[65536]
targetFile.withInputStream {
final DigestInputStream dis = new DigestInputStream(it, md)
while(dis.read(buffer) != -1) { }
}
final File chksumFile = new File(checksumsDir, "${targetFile.name}.${hashExt}")
chksumFile.text = md.digest().encodeHex().toString()
chksumFile
}
Integer processArtifacts(parameters, mavenPub) {
final Directory tmpDir = layout.buildDirectory.dir('tmp').get()
final File checksumsDir = tmpDir.dir('generatedChecksums').asFile
checksumsDir?.deleteDir()
checksumsDir.mkdirs()
tmpDir.asFile?.deleteOnExit()
final List<String> artifactTypes = ['oss', 'full'].asImmutable()
final HashSet<String> seen = []
final boolean isLocal = gradle.startParameter.taskNames.any { it == 'publishToMavenLocal' || it.endsWith(':publishToMavenLocal') }
parameters.zipFiles.files.each { foundFile ->
final String type = artifactTypes.find { foundFile.name.contains("-${it}-") } ?: { throw new GradleException("Publishing failed: File ${foundFile.name} is missing a valid build type.") }()
if(!seen.add(type)) throw new GradleException("Publishing failed: The type '${type}' already exists.")
final String clsf = (type == 'oss' ? null : type)
mavenPub.artifact(foundFile) { extension = 'zip'; classifier = clsf; builtBy 'collectArtifacts' }
if(isLocal) {
['sha256', 'sha1', 'md5'].each { hashExt ->
final File existChksumFile = file("${foundFile.absolutePath}.${hashExt}")
final File chksumFile = existChksumFile.exists() ? existChksumFile : generateChecksum(foundFile, hashExt, checksumsDir)
mavenPub.artifact(chksumFile) { extension = "zip.${hashExt}"; classifier = clsf; builtBy 'collectArtifacts' }
}
}
}
if(seen.isEmpty()) throw new GradleException("Publishing failed: No artifact found. Check if build tasks were executed.")
seen.size()
}
tasks.register('collectArtifacts') {
notCompatibleWithConfigurationCache('Dynamic artifact insertion is not compatible with Configuration Cache.')
outputs.cacheIf('Task is collection-only; caching is disabled.') { false }
mustRunAfter 'buildOta', 'buildOtaOSS'
inputs.files(zipFilesTree).withPropertyName('collectedZips')
outputs.upToDateWhen { false }
doLast {
//Bridge.init(publishing.publications.maven)
//final Integer count = artifactsProcessor.get()
final Map<String, Object> parameters = [
zipFiles: objects.fileCollection().tap {
setFrom( getZipName().map { name -> layout.buildDirectory.asFileTree.matching { include name } } )
}
].asImmutable()
final Integer count = processArtifacts(parameters, publishing.publications.maven)
logger.lifecycle "Successfully registered ${count} base artifact(s)."
}
}
tasks.register('showPublishedArtifacts') {
outputs.upToDateWhen { false }
def artifactData = provider {
publishing.publications.collectMany { pub ->
pub.artifacts?.collect { "Pub: ${pub.name} | File: ${it.file.name} | Ext: ${it.extension}${it.classifier ? " | Classifier: ${it.classifier}" : ""}" } ?: []
}
}
inputs.property('data', artifactData)
doLast {
artifactData.get().each { logger.lifecycle it }
}
}
tasks.named('publishToMavenLocal') {
finalizedBy 'cleanPubTmpFiles'
}
tasks.withType(GenerateMavenPom).configureEach {
dependsOn 'collectArtifacts'
}
[PublishToMavenRepository, PublishToMavenLocal].each { type ->
tasks.withType(type).configureEach {
dependsOn 'collectArtifacts'
finalizedBy 'showPublishedArtifacts'
}
}
/* ===HEADER=== */
abstract class HeaderPrinter implements ValueSource<String, HeaderParams> {
private static final log = Logging.getLogger(HeaderPrinter)
interface HeaderParams extends ValueSourceParameters {
@Input Property<String> getProjectName()
@Input Property<String> getVersion()
@Input Property<String> getOsName()
}
@Override
String obtain() {
log.lifecycle '=' * 36
log.lifecycle "Project: ${parameters.projectName.get()}"
log.lifecycle "Version: ${parameters.version.get()}"
log.lifecycle "OS: ${parameters.osName.get()}"
log.lifecycle '=' * 36
''
}
}
def headerTrigger = providers.of(HeaderPrinter) {
parameters.projectName.set provider { project.name }
parameters.version.set ext.lazyVersion
parameters.osName.set ext.lazyOsName
}
gradle.taskGraph.whenReady {
logger.info "${-> headerTrigger.get()}"
}