1 /**
2 * Copyright 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
12 * the License.
13 */
14 package androidx.build
15
16 import java.io.File
17 import java.util.Collections
18 import java.util.concurrent.locks.ReentrantLock
19 import kotlin.concurrent.withLock
20 import org.gradle.api.Project
21 import org.gradle.api.Task
22 import org.gradle.api.provider.Provider
23 import org.gradle.api.tasks.TaskProvider
24
25 /** Holder class used for lazily registering tasks using the new Lazy task execution API. */
26 data class LazyTaskRegistry(
27 private val names: MutableSet<String> = Collections.synchronizedSet(mutableSetOf())
28 ) {
oncenull29 fun <T : Any?> once(name: String, f: () -> T): T? {
30 if (names.add(name)) {
31 return f()
32 }
33 return null
34 }
35
36 companion object {
37 private const val KEY = "AndroidXAutoRegisteredTasks"
38 private val lock = ReentrantLock()
39
getnull40 fun get(project: Project): LazyTaskRegistry {
41 val existing = project.extensions.findByName(KEY) as? LazyTaskRegistry
42 if (existing != null) {
43 return existing
44 }
45 return lock.withLock {
46 project.extensions.findByName(KEY) as? LazyTaskRegistry
47 ?: LazyTaskRegistry().also { project.extensions.add(KEY, it) }
48 }
49 }
50 }
51 }
52
maybeRegisternull53 inline fun <reified T : Task> Project.maybeRegister(
54 name: String,
55 crossinline onConfigure: (T) -> Unit,
56 crossinline onRegister: (TaskProvider<T>) -> Unit
57 ): TaskProvider<T> {
58 @Suppress("UNCHECKED_CAST")
59 return LazyTaskRegistry.get(project).once(name) {
60 tasks.register(name, T::class.java) { onConfigure(it) }.also(onRegister)
61 } ?: tasks.named(name) as TaskProvider<T>
62 }
63
lazyReadFilenull64 internal fun Project.lazyReadFile(fileName: String): Provider<String> {
65 val fileProperty = objects.fileProperty().fileValue(File(getSupportRootFolder(), fileName))
66 return providers.fileContents(fileProperty).asText
67 }
68