aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/rules/android/ApplicationManifest.java
blob: 3c14b8ec6e8b1d28453c85d17cab31b364c644d2 (plain)
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
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.android;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.actions.FileWriteAction;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.config.CompilationMode;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.rules.android.AndroidResourcesProvider.ResourceContainer;
import com.google.devtools.build.lib.rules.android.AndroidResourcesProvider.ResourceType;
import com.google.devtools.build.lib.rules.android.LocalResourceContainer.Builder.InvalidAssetPath;
import com.google.devtools.build.lib.rules.android.LocalResourceContainer.Builder.InvalidResourcePath;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.vfs.PathFragment;

import java.util.List;

/** Represents a AndroidManifest, that may have been merged from dependencies. */
public final class ApplicationManifest {
  public static ApplicationManifest fromResourcesRule(RuleContext ruleContext) {
    final AndroidResourcesProvider resources = AndroidCommon.getAndroidResources(ruleContext);
    if (resources == null) {
      ruleContext.attributeError("manifest",
          "a resources or manifest attribute is mandatory.");
      throw new RuleConfigurationException();
    }
    return new ApplicationManifest(Iterables.getOnlyElement(
        resources.getTransitiveAndroidResources())
        .getManifest());
  }

  public ApplicationManifest createSplitManifest(
      RuleContext ruleContext, String splitName, boolean hasCode) {
    // aapt insists that manifests be called AndroidManifest.xml, even though they have to be
    // explicitly designated as manifests on the command line
    Artifact result = AndroidBinary.getDxArtifact(
        ruleContext, "split_" + splitName + "/AndroidManifest.xml");
    SpawnAction.Builder builder = new SpawnAction.Builder()
        .setExecutable(ruleContext.getExecutablePrerequisite("$build_split_manifest", Mode.HOST))
        .setProgressMessage("Creating manifest for split " + splitName)
        .setMnemonic("AndroidBuildSplitManifest")
        .addArgument("--main_manifest")
        .addInputArgument(manifest)
        .addArgument("--split_manifest")
        .addOutputArgument(result)
        .addArgument("--split")
        .addArgument(splitName)
        .addArgument(hasCode ? "--hascode" : "--nohascode");

    String overridePackage = getOverridePackage(ruleContext);
    if (overridePackage != null) {
      builder
          .addArgument("--override_package")
          .addArgument(overridePackage);
    }

    ruleContext.registerAction(builder.build(ruleContext));
    return new ApplicationManifest(result);
  }

  private String getOverridePackage(RuleContext ruleContext) {
    // It seems that we sometimes rename the app for God-knows-what reason. If that is the case,
    // pass this information to the stubifier script.
    if (ruleContext.attributes().isAttributeValueExplicitlySpecified("application_id")) {
      return ruleContext.attributes().get("application_id", Type.STRING);
    }

    AndroidResourcesProvider resourcesProvider = AndroidCommon.getAndroidResources(ruleContext);
    if (resourcesProvider != null) {
      ResourceContainer resourceContainer = Iterables.getOnlyElement(
          resourcesProvider.getTransitiveAndroidResources());
      return resourceContainer.getRenameManifestPackage();
    } else {
      return null;
    }
  }

  public ApplicationManifest addStubApplication(RuleContext ruleContext)
      throws InterruptedException {

    Artifact stubManifest =
        ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.STUB_APPLICATON_MANIFEST);

    SpawnAction.Builder builder = new SpawnAction.Builder()
        .setExecutable(ruleContext.getExecutablePrerequisite("$stubify_manifest", Mode.HOST))
        .setProgressMessage("Injecting stub application")
        .setMnemonic("InjectStubApplication")
        .addArgument("--input_manifest")
        .addInputArgument(manifest)
        .addArgument("--output_manifest")
        .addOutputArgument(stubManifest)
        .addArgument("--output_datafile")
        .addOutputArgument(
            ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.STUB_APPLICATION_DATA));

    String overridePackage = getOverridePackage(ruleContext);
    if (overridePackage != null) {
      builder.addArgument("--override_package");
      builder.addArgument(overridePackage);
    }

    ruleContext.registerAction(builder.build(ruleContext));

    return new ApplicationManifest(stubManifest);
  }

  public static ApplicationManifest fromRule(RuleContext ruleContext) {
    return new ApplicationManifest(ruleContext.getPrerequisiteArtifact("manifest", Mode.TARGET));
  }

  public static ApplicationManifest fromExplicitManifest(Artifact manifest) {
    return new ApplicationManifest(manifest);
  }

  /**
   * Generates an empty manifest for a rule that does not directly specify resources.
   *
   * <p><strong>Note:</strong> This generated manifest can then be used as the primary manifest
   * when merging with dependencies.
   *
   * @return the generated ApplicationManifest
   */
  public static ApplicationManifest generatedManifest(RuleContext ruleContext) {
    Artifact generatedManifest = ruleContext.getUniqueDirectoryArtifact(
        ruleContext.getRule().getName() + "_generated", new PathFragment("AndroidManifest.xml"),
        ruleContext.getBinOrGenfilesDirectory());

    String manifestPackage = AndroidCommon.getJavaPackage(ruleContext);
    String contents = Joiner.on("\n").join(
        "<?xml version=\"1.0\" encoding=\"utf-8\"?>",
        "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"",
        "          package=\"" + manifestPackage + "\">",
        "   <application>",
        "   </application>",
        "</manifest>");
    ruleContext.getAnalysisEnvironment().registerAction(new FileWriteAction(
        ruleContext.getActionOwner(), generatedManifest, contents, false /* makeExecutable */));
    return new ApplicationManifest(generatedManifest);
  }

  private final Artifact manifest;

  private ApplicationManifest(Artifact manifest) {
    this.manifest = manifest;
  }

  public ApplicationManifest mergeWith(RuleContext ruleContext,
      Iterable<ResourceContainer> resourceContainers) {
    if (!Iterables.isEmpty(getMergeeManifests(resourceContainers))) {
      Iterable<Artifact> exportedManifests = getMergeeManifests(resourceContainers);
      Artifact outputManifest = ruleContext.getUniqueDirectoryArtifact(
          ruleContext.getRule().getName() + "_merged", "AndroidManifest.xml",
          ruleContext.getBinOrGenfilesDirectory());
      AndroidManifestMergeHelper.createMergeManifestAction(ruleContext, getManifest(),
          exportedManifests, ImmutableList.of("all"), outputManifest);
      return new ApplicationManifest(outputManifest);
    }
    return this;
  }

  private static Iterable<Artifact> getMergeeManifests(
      Iterable<ResourceContainer> resourceContainers) {
    ImmutableSortedSet.Builder<Artifact> builder =
        ImmutableSortedSet.orderedBy(Artifact.EXEC_PATH_COMPARATOR);
    for (ResourceContainer r : resourceContainers) {
      if (r.isManifestExported()) {
        builder.add(r.getManifest());
      }
    }
    return builder.build();
  }

  /** Packages up the manifest with assets from the rule and dependent resources. 
   * @throws InterruptedException */
  public ResourceApk packWithAssets(
      Artifact resourceApk,
      RuleContext ruleContext,
      NestedSet<ResourceContainer> resourceContainers,
      Artifact rTxt,
      boolean incremental,
      Artifact proguardCfg) throws InterruptedException {
    try {
      LocalResourceContainer data = new LocalResourceContainer.Builder()
          .withAssets(
              AndroidCommon.getAssetDir(ruleContext),
              ruleContext.getPrerequisites(
                  // TODO(bazel-team): Remove the ResourceType construct.
                  ResourceType.ASSETS.getAttribute(),
                  Mode.TARGET,
                  FileProvider.class)).build();

      return createApk(resourceApk,
          ruleContext,
          resourceContainers,
          rTxt,
          null, /* configurationFilters */
          ImmutableList.<String>of(), /* uncompressedExtensions */
          ImmutableList.<String>of(), /* densities */
          ImmutableList.<String>of(), /* String applicationId */
          null, /* String versionCode */
          null, /* String versionName */
          null, /* Artifact symbolsTxt */ 
          incremental,
          data,
          proguardCfg);
    } catch (InvalidAssetPath e) {
      ruleContext.attributeError(ResourceType.ASSETS.getAttribute(), e.getMessage());
      throw new RuleConfigurationException();
    }
  }

  /** Packages up the manifest with resource and assets from the rule and dependent resources. 
   * @throws InterruptedException */
  public ResourceApk packWithDataAndResources(
      Artifact resourceApk,
      RuleContext ruleContext,
      NestedSet<ResourceContainer> resourceContainers,
      Artifact rTxt,
      Artifact symbolsTxt,
      List<String> configurationFilters,
      List<String> uncompressedExtensions,
      List<String> densities,
      String applicationId,
      String versionCode,
      String versionName,
      boolean incremental, Artifact proguardCfg) throws InterruptedException {
    try {
      LocalResourceContainer data = new LocalResourceContainer.Builder()
          .withAssets(
              AndroidCommon.getAssetDir(ruleContext),
              ruleContext.getPrerequisites(
                  // TODO(bazel-team): Remove the ResourceType construct.
                  ResourceType.ASSETS.getAttribute(),
                  Mode.TARGET,
                  FileProvider.class))
          .withResources(
              ruleContext.getPrerequisites(
                  "resource_files",
                  Mode.TARGET,
                  FileProvider.class)).build();

      return createApk(resourceApk,
          ruleContext,
          resourceContainers,
          rTxt,
          symbolsTxt,
          configurationFilters,
          uncompressedExtensions,
          densities,
          applicationId,
          versionCode,
          versionName,
          incremental,
          data,
          proguardCfg);
    } catch (InvalidAssetPath e) {
      ruleContext.attributeError(ResourceType.ASSETS.getAttribute(), e.getMessage());
      throw new RuleConfigurationException();
    } catch (InvalidResourcePath e) {
      ruleContext.attributeError("resource_files", e.getMessage());
      throw new RuleConfigurationException();
    }
  }

  private ResourceApk createApk(Artifact resourceApk,
      RuleContext ruleContext,
      NestedSet<ResourceContainer> resourceContainers,
      Artifact rTxt,
      Artifact symbolsTxt,
      List<String> configurationFilters,
      List<String> uncompressedExtensions,
      List<String> densities,
      String applicationId,
      String versionCode,
      String versionName,
      boolean incremental,
      LocalResourceContainer data, Artifact proguardCfg) throws InterruptedException {
    ResourceContainer resourceContainer = checkForInlinedResources(
        new AndroidResourceContainerBuilder()
            .withData(data)
            .withManifest(getManifest())
            .withROutput(rTxt)
            .withSymbolsFile(symbolsTxt)
            .buildFromRule(ruleContext, resourceApk),
        resourceContainers,
        ruleContext);

    AndroidResourcesProcessorBuilder builder =
        new AndroidResourcesProcessorBuilder(ruleContext)
            .setApkOut(resourceContainer.getApk())
            .setConfigurationFilters(configurationFilters)
            .setUncompressedExtensions(uncompressedExtensions)
            .setJavaPackage(resourceContainer.getJavaPackage())
            .setDebug(ruleContext.getConfiguration().getCompilationMode() != CompilationMode.OPT)
            .withPrimary(resourceContainer)
            .withDependencies(resourceContainers)
            .setDensities(densities)
            .setProguardOut(proguardCfg)
            .setApplicationId(applicationId)
            .setVersionCode(versionCode)
            .setVersionName(versionName);

    if (!incremental) {
      builder
          .setRTxtOut(resourceContainer.getRTxt())
          .setSymbolsTxt(resourceContainer.getSymbolsTxt())
          .setSourceJarOut(resourceContainer.getJavaSourceJar());
    }

    ResourceContainer processed = builder.build(ruleContext);
    NestedSet<ResourceContainer> transitiveResources =
        NestedSetBuilder.<ResourceContainer>naiveLinkOrder()
            // TODO(bazel-team): If this is replaced with .addTransitive(), a few tests fail.
            // Investigate.
            .addAll(resourceContainers)
            .add(processed)
            .build();

    return new ResourceApk(
        resourceApk, processed.getJavaSourceJar(), transitiveResources, processed, manifest,
        proguardCfg, false);
  }

  private static ResourceContainer checkForInlinedResources(ResourceContainer resourceContainer,
      Iterable<ResourceContainer> resourceContainers, RuleContext ruleContext) {
    // Dealing with Android library projects
    if (Iterables.size(resourceContainers) > 1) {
      if (resourceContainer.getConstantsInlined()
          && !resourceContainer.getArtifacts(ResourceType.RESOURCES).isEmpty()) {
        ruleContext.ruleError("This android binary depends on an android "
            + "library project, so the resources '"
            + AndroidCommon.getAndroidResources(ruleContext).getLabel()
            + "' should have the attribute inline_constants set to 0");
        throw new RuleConfigurationException();
      }
    }
    return resourceContainer;
  }

  /** Uses the resource apk from the resources attribute, as opposed to recompiling. */
  public ResourceApk useCurrentResources(RuleContext ruleContext, Artifact proguardCfg) {
    ResourceContainer resourceContainer = Iterables.getOnlyElement(
        AndroidCommon.getAndroidResources(ruleContext).getTransitiveAndroidResources());
    NestedSet<ResourceContainer> resourceContainers =
        NestedSetBuilder.emptySet(Order.NAIVE_LINK_ORDER);

    NestedSet<ResourceContainer> transitiveResources =
        NestedSetBuilder.<ResourceContainer>naiveLinkOrder()
            .addAll(resourceContainers)
            .add(resourceContainer)
            .build();

    new AndroidAaptActionHelper(
        ruleContext,
        resourceContainer.getManifest(),
        Lists.newArrayList(resourceContainer)).createGenerateProguardAction(proguardCfg);

    return new ResourceApk(
        resourceContainer.getApk(),
        null /* javaSrcJar */,
        transitiveResources,
        resourceContainer,
        manifest,
        proguardCfg,
        false);
  }

  /**
   * Packages up the manifest with resources, and generates the R.java.
   * @throws InterruptedException 
   *
   * @deprecated in favor of {@link ApplicationManifest#packWithDataAndResources}.
   */
  @Deprecated
  public ResourceApk packWithResources(
      Artifact resourceApk,
      RuleContext ruleContext,
      NestedSet<ResourceContainer> resourceContainers,
      boolean createSource,
      Artifact proguardCfg) throws InterruptedException {

    TransitiveInfoCollection resourcesPrerequisite =
        ruleContext.getPrerequisite("resources", Mode.TARGET);
    ResourceContainer resourceContainer = Iterables.getOnlyElement(
        resourcesPrerequisite.getProvider(AndroidResourcesProvider.class)
            .getTransitiveAndroidResources());

    // Dealing with Android library projects
    if (Iterables.size(resourceContainers) > 1) {
      if (resourceContainer.getConstantsInlined()
          && !resourceContainer.getArtifacts(ResourceType.RESOURCES).isEmpty()) {
        ruleContext.ruleError("This android_binary depends on an android_library, so the"
            + " resources '" + AndroidCommon.getAndroidResources(ruleContext).getLabel()
            + "' should have the attribute inline_constants set to 0");
        throw new RuleConfigurationException();
      }
    }

    // This binary depends on a library project, so we need to regenerate the
    // resources. The resulting sources and apk will combine all the resources
    // contained in the transitive closure of the binary.
    AndroidAaptActionHelper aaptActionHelper = new AndroidAaptActionHelper(ruleContext,
        getManifest(), Lists.newArrayList(resourceContainers));

    List<String> resourceConfigurationFilters =
        ruleContext.getTokenizedStringListAttr("resource_configuration_filters");
    List<String> uncompressedExtensions =
        ruleContext.getTokenizedStringListAttr("nocompress_extensions");

    ImmutableList.Builder<String> additionalAaptOpts = ImmutableList.<String>builder();

    for (String extension : uncompressedExtensions) {
      additionalAaptOpts.add("-0").add(extension);
    }
    if (!resourceConfigurationFilters.isEmpty()) {
      additionalAaptOpts.add("-c").add(Joiner.on(",").join(resourceConfigurationFilters));
    }

    Artifact javaSourcesJar = null;

    if (createSource) {
      javaSourcesJar =
        ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_JAVA_SOURCE_JAR);
      aaptActionHelper.createGenerateResourceSymbolsAction(
          javaSourcesJar, null, resourceContainer.getJavaPackage(), true);
    }

    List<String> densities = ruleContext.getTokenizedStringListAttr("densities");
    aaptActionHelper.createGenerateApkAction(resourceApk,
        resourceContainer.getRenameManifestPackage(), additionalAaptOpts.build(), densities);

    ResourceContainer updatedResources = new ResourceContainer(
        ruleContext.getLabel(),
        resourceContainer.getJavaPackage(),
        resourceContainer.getRenameManifestPackage(),
        resourceContainer.getConstantsInlined(),
        resourceApk,
        getManifest(),
        javaSourcesJar,
        resourceContainer.getArtifacts(ResourceType.ASSETS),
        resourceContainer.getArtifacts(ResourceType.RESOURCES),
        resourceContainer.getRoots(ResourceType.ASSETS),
        resourceContainer.getRoots(ResourceType.RESOURCES),
        resourceContainer.isManifestExported(),
        resourceContainer.getRTxt(), null);

    aaptActionHelper.createGenerateProguardAction(proguardCfg);

    return new ResourceApk(resourceApk, updatedResources.getJavaSourceJar(),
        resourceContainers, updatedResources, manifest, proguardCfg, true);
  }

  public Artifact getManifest() {
    return manifest;
  }
}