Debian Codegraph @

build-system/gradle-experimental/src/main/java/com/android/build/gradle/model/AndroidComponentModelPlugin.java

raw
1 /*
2 * Copyright (C) 2015 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
17 package com.android.build.gradle.model;
18
19 import static com.android.builder.core.VariantType.ANDROID_TEST;
20 import static com.android.builder.core.VariantType.UNIT_TEST;
21
22 import com.android.build.gradle.internal.ProductFlavorCombo;
23 import com.android.build.gradle.managed.AndroidConfig;
24 import com.android.build.gradle.managed.BuildType;
25 import com.android.build.gradle.managed.ProductFlavor;
26 import com.android.build.gradle.model.internal.AndroidBinaryInternal;
27 import com.android.build.gradle.model.internal.AndroidComponentSpecInternal;
28 import com.android.build.gradle.model.internal.DefaultAndroidBinary;
29 import com.android.build.gradle.model.internal.DefaultAndroidComponentSpec;
30 import com.android.build.gradle.model.internal.DefaultAndroidLanguageSourceSet;
31 import com.android.build.gradle.model.internal.DefaultJniLibsSourceSet;
32 import com.android.builder.Version;
33 import com.android.builder.core.BuilderConstants;
34 import com.android.repository.Revision;
35 import com.android.utils.StringHelper;
36 import com.google.common.collect.Lists;
37 import com.google.common.primitives.Ints;
38
39 import org.gradle.api.Plugin;
40 import org.gradle.api.Project;
41 import org.gradle.api.file.SourceDirectorySet;
42 import org.gradle.language.base.FunctionalSourceSet;
43 import org.gradle.language.base.ProjectSourceSet;
44 import org.gradle.language.base.plugins.ComponentModelBasePlugin;
45 import org.gradle.model.Defaults;
46 import org.gradle.model.Finalize;
47 import org.gradle.model.Model;
48 import org.gradle.model.ModelMap;
49 import org.gradle.model.Mutate;
50 import org.gradle.model.Path;
51 import org.gradle.model.RuleSource;
52 import org.gradle.platform.base.BinarySpec;
53 import org.gradle.platform.base.ComponentBinaries;
54 import org.gradle.platform.base.ComponentType;
55 import org.gradle.platform.base.TypeBuilder;
56 import org.gradle.tooling.BuildException;
57 import org.gradle.tooling.UnsupportedVersionException;
58
59 import java.io.File;
60 import java.util.List;
61 import java.util.Set;
62 import java.util.stream.Collectors;
63
64 /**
65 * Plugin to set up infrastructure for other android plugins.
66 */
67 public class AndroidComponentModelPlugin implements Plugin<Project> {
68
69 /**
70 * The name of ComponentSpec created with android component model plugin.
71 */
72 public static final String COMPONENT_NAME = "android";
73
74 public static final String GRADLE_ACCEPTABLE_VERSION = "2.14.1";
75
76 private static final String GRADLE_VERSION_CHECK_OVERRIDE_PROPERTY =
77 "com.android.build.gradle.overrideVersionCheck";
78
79 @Override
80 public void apply(Project project) {
81 checkPluginVersion();
82 checkGradleVersion(project);
83 project.getPlugins().apply(ComponentModelBasePlugin.class);
84 }
85
86 /**
87 * Verify the plugin version. If a newer version of gradle plugin is applied, then builder.jar
88 * module will be resolved to a different version than the one this gradle-experimental plugin
89 * is compiled with. Throw an error and suggest to update this plugin.
90 */
91 public static void checkPluginVersion() {
92 String actualGradlePluginVersion = Version.getAndroidGradleComponentPluginVersion();
93 if(!actualGradlePluginVersion.equals(
94 com.android.build.gradle.model.Version.ANDROID_GRADLE_COMPONENT_PLUGIN_VERSION)) {
95 throw new UnsupportedVersionException(String.format("Plugin version mismatch. "
96 + "'com.android.tools.build:gradle:%s' was applied, and it "
97 + "requires 'com.android.tools.build:gradle-experimental:%s'. Current "
98 + "version is '%s'. Please update to version '%s'.",
99 Version .getAndroidGradlePluginVersion(),
100 Version .getAndroidGradleComponentPluginVersion(),
101 com.android.build.gradle.model.Version.ANDROID_GRADLE_COMPONENT_PLUGIN_VERSION,
102 Version .getAndroidGradleComponentPluginVersion()));
103 }
104 }
105
106 private static void checkGradleVersion(Project project) {
107 String gradleVersion = project.getGradle().getGradleVersion();
108 if (!gradleVersion.startsWith(GRADLE_ACCEPTABLE_VERSION)) {
109 boolean allowNonMatching = Boolean.getBoolean(GRADLE_VERSION_CHECK_OVERRIDE_PROPERTY);
110 File file = new File("gradle" + File.separator + "wrapper" + File.separator +
111 "gradle-wrapper.properties");
112 String errorMessage = String.format(
113 "Gradle version %s is required. Current version is %s. " +
114 "If using the gradle wrapper, try editing the distributionUrl in %s " +
115 "to gradle-%s-all.zip",
116 GRADLE_ACCEPTABLE_VERSION, gradleVersion, file.getAbsolutePath(),
117 GRADLE_ACCEPTABLE_VERSION);
118 if (allowNonMatching) {
119 project.getLogger().warn(errorMessage);
120 project.getLogger().warn("As %s is set, continuing anyways.",
121 GRADLE_VERSION_CHECK_OVERRIDE_PROPERTY);
122 } else {
123 throw new BuildException(errorMessage, null);
124 }
125 }
126 }
127
128 public static class Rules extends RuleSource {
129
130 /**
131 * Create "android" model block.
132 */
133 @Model("android")
134 public void android(AndroidConfig androidModel) {
135 }
136
137 @Finalize
138 public static void finalizeAndroidModel(AndroidConfig androidModel) {
139 if (androidModel.getBuildToolsRevision() == null
140 && androidModel.getBuildToolsVersion() != null) {
141 //The underlying Revision class has the maven artifact semantic,
142 // so 20 is not the same as 20.0. For the build tools revision this
143 // is not the desired behavior, so normalize e.g. to 20.0.0.
144 androidModel.setBuildToolsRevision(
145 Revision.parseRevision(
146 androidModel.getBuildToolsVersion(),
147 Revision.Precision.MICRO));
148 }
149
150 if (androidModel.getCompileSdkVersion() != null
151 && !androidModel.getCompileSdkVersion().startsWith("android-")
152 && Ints.tryParse(androidModel.getCompileSdkVersion()) != null) {
153 androidModel.setCompileSdkVersion("android-" + androidModel.getCompileSdkVersion());
154 }
155
156 }
157
158 @Defaults
159 public static void createDefaultBuildTypes(
160 @Path("android.buildTypes") ModelMap<BuildType> buildTypes) {
161 buildTypes.create(BuilderConstants.DEBUG, buildType -> {
162 buildType.setDebuggable(true);
163 buildType.setEmbedMicroApp(false);
164 });
165 buildTypes.create(BuilderConstants.RELEASE);
166 }
167
168 @Model
169 public static List<ProductFlavorCombo<ProductFlavor>> createProductFlavorCombo(
170 @Path("android.productFlavors") ModelMap<ProductFlavor> productFlavors) {
171 // TODO: Create custom product flavor container to manually configure flavor dimensions.
172 Set<String> flavorDimensionList = productFlavors.values().stream()
173 .filter(flavor -> flavor.getDimension() != null)
174 .map(ProductFlavor::getDimension).collect(Collectors.toSet());
175
176 return ProductFlavorCombo.createCombinations(
177 Lists.newArrayList(flavorDimensionList),
178 productFlavors.values());
179 }
180
181 @ComponentType
182 public static void defineComponentType(TypeBuilder<AndroidComponentSpec> builder) {
183 builder.defaultImplementation(DefaultAndroidComponentSpec.class);
184 builder.internalView(AndroidComponentSpecInternal.class);
185 }
186
187 @Mutate
188 public static void createAndroidComponents(
189 ModelMap<AndroidComponentSpec> androidComponents) {
190 androidComponents.create(COMPONENT_NAME);
191 }
192
193 /**
194 * Create all source sets for each AndroidBinary.
195 */
196 @Mutate
197 public static void createVariantSourceSet(
198 @Path("android.sources") final ModelMap<FunctionalSourceSet> sources,
199 @Path("android.buildTypes") final ModelMap<BuildType> buildTypes,
200 @Path("android.productFlavors") ModelMap<ProductFlavor> flavors,
201 List<ProductFlavorCombo<ProductFlavor>> flavorGroups,
202 ProjectSourceSet projectSourceSet) {
203
204 // Create main source set.
205 sources.create("main");
206 sources.create(ANDROID_TEST.getPrefix());
207 sources.create(UNIT_TEST.getPrefix());
208
209 for (BuildType buildType : buildTypes.values()) {
210 sources.create(buildType.getName());
211
212 if (!flavors.isEmpty()) {
213 for (ProductFlavorCombo group : flavorGroups) {
214 if (!group.getFlavorList().isEmpty()) {
215 sources.create(
216 group.getName() + StringHelper.capitalize(buildType.getName()));
217 }
218 }
219 }
220 }
221 for (ProductFlavorCombo group: flavorGroups) {
222 sources.create(group.getName());
223 }
224 if (flavorGroups.size() != flavors.size()) {
225 // If flavorGroups and flavors are the same size, there is at most 1 flavor
226 // dimension. So we don't need to reconfigure the source sets for flavorGroups.
227 for (ProductFlavor flavor: flavors.values()) {
228 sources.create(flavor.getName());
229 }
230 }
231 sources.afterEach(functionalSourceSet -> functionalSourceSet.afterEach(
232 languageSourceSet -> {
233 SourceDirectorySet source = languageSourceSet.getSource();
234 if (source.getSrcDirs().isEmpty()) {
235 source.srcDir("src/" + languageSourceSet.getParentName()
236 + "/" + languageSourceSet.getName());
237 }
238 }));
239
240 }
241
242 @ComponentType
243 public static void defineBinaryType(TypeBuilder<AndroidBinary> builder) {
244 builder.defaultImplementation(DefaultAndroidBinary.class);
245 builder.internalView(AndroidBinaryInternal.class);
246 }
247
248 @ComponentBinaries
249 public static void createBinaries(
250 final ModelMap<AndroidBinary> binaries,
251 @Path("android") final AndroidConfig androidConfig,
252 @Path("android.buildTypes") final ModelMap<BuildType> buildTypes,
253 final List<ProductFlavorCombo<ProductFlavor>> flavorCombos,
254 @Path("android.sources") final ModelMap<FunctionalSourceSet> sources,
255 final AndroidComponentSpec spec) {
256 if (flavorCombos.isEmpty()) {
257 flavorCombos.add(new ProductFlavorCombo<>());
258 }
259
260 for (final BuildType buildType : buildTypes.values()) {
261 for (final ProductFlavorCombo<ProductFlavor> flavorCombo : flavorCombos) {
262 binaries.create(getBinaryName(buildType, flavorCombo),
263 androidBinary -> {
264 AndroidBinaryInternal binary = (AndroidBinaryInternal) androidBinary;
265 binary.setBuildType(buildType);
266 binary.setProductFlavors(flavorCombo.getFlavorList());
267
268 sourceBinary(binary, sources, "main");
269 sourceBinary(binary, sources, buildType.getName());
270 for (ProductFlavor flavor : flavorCombo.getFlavorList()) {
271 sourceBinary(binary, sources, flavor.getName());
272 }
273 if (flavorCombo.getFlavorList().size() > 1) {
274 sourceBinary(binary, sources, flavorCombo.getName());
275 }
276 });
277 }
278 }
279 }
280
281 /**
282 * Add sources to the specified binary.
283 */
284 private static void sourceBinary(
285 BinarySpec binary,
286 ModelMap<FunctionalSourceSet> projectSourceSet,
287 final String sourceSetName) {
288 FunctionalSourceSet sourceSet = projectSourceSet.get(sourceSetName);
289 if (sourceSet != null) {
290 binary.getInputs().addAll(sourceSet.values());
291 }
292 }
293
294 private static String getBinaryName(BuildType buildType, ProductFlavorCombo flavorCombo) {
295 if (flavorCombo.getFlavorList().isEmpty()) {
296 return buildType.getName();
297 } else {
298 return flavorCombo.getName() + StringHelper.capitalize(buildType.getName());
299 }
300
301 }
302 }
303 }