1/* 2 * Copyright 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package androidx.build 18 19import com.android.build.gradle.LibraryExtension 20import org.gradle.api.DefaultTask 21import org.gradle.api.Project 22import org.gradle.api.tasks.Input 23import org.gradle.api.tasks.OutputFile 24import org.gradle.api.tasks.TaskAction 25import java.io.File 26import java.io.PrintWriter 27 28/** 29 * Task that allows to write a version to a given output file. 30 */ 31open class VersionFileWriterTask : DefaultTask() { 32 @get:Input 33 lateinit var version: String 34 @get:OutputFile 35 lateinit var outputFile: File 36 37 /** 38 * The main method for actually writing out the file. 39 */ 40 @TaskAction 41 fun run() { 42 val writer = PrintWriter(outputFile) 43 writer.println(version) 44 writer.close() 45 } 46 47 companion object { 48 val RESOURCE_DIRECTORY = "generatedResources" 49 val VERSION_FILE_PATH = RESOURCE_DIRECTORY + "/META-INF/%s_%s.version" 50 51 /** 52 * Sets up Android Library project to have a task that generates a version file. 53 * It must be called after [LibraryExtension] has been resolved. 54 * 55 * @param project an Android Library project. 56 */ 57 fun setUpAndroidLibrary(project: Project, library: LibraryExtension) { 58 val group = project.properties["group"] as String 59 val artifactId = project.properties["name"] as String 60 val version = project.properties["version"] as String 61 62 // Add a java resource file to the library jar for version tracking purposes. 63 val artifactName = File( 64 project.buildDir, 65 String.format(VERSION_FILE_PATH, group, artifactId)) 66 67 val writeVersionFile = project.tasks.create("writeVersionFile", 68 VersionFileWriterTask::class.java) 69 writeVersionFile.version = version 70 writeVersionFile.outputFile = artifactName 71 72 library.libraryVariants.all { 73 it.processJavaResources.dependsOn(writeVersionFile) 74 } 75 76 val resources = library.sourceSets.getByName("main").resources 77 resources.srcDir(File(project.buildDir, RESOURCE_DIRECTORY)) 78 if (!resources.includes.isEmpty()) { 79 val includes = resources.includes 80 includes.add("META-INF/*.version") 81 resources.setIncludes(includes) 82 } 83 } 84 } 85} 86