aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/rules/android/AndroidAaptActionHelper.java
blob: 2bcec39c9f3c65f7f5b3ed6227950e8384ab7261 (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
// Copyright 2015 Google Inc. 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.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ParameterFile.ParameterFileType;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.RunfilesSupport;
import com.google.devtools.build.lib.analysis.actions.CommandLine;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.actions.SpawnAction.Builder;
import com.google.devtools.build.lib.analysis.config.CompilationMode;
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.vfs.PathFragment;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * Helper class to generate Android aapt actions.
 */
public final class AndroidAaptActionHelper {
  private final RuleContext ruleContext;
  private final Artifact manifest;
  private final Collection<Artifact> inputs = new LinkedHashSet<>();
  private final List<ResourceContainer> resourceContainers;

  /**
   * Constructs an instance of AndroidAaptActionHelper.
   *
   * @param ruleContext RuleContext for which the aapt actions
   *        will be generated.
   * @param manifest Artifact representing the AndroidManifest.xml that will be
   *        used to package resources.
   * @param resourceContainers The transitive closure of the ResourceContainers.
   */
  public AndroidAaptActionHelper(RuleContext ruleContext, Artifact manifest,
      List<ResourceContainer> resourceContainers) {
    this.ruleContext = ruleContext;
    this.manifest = manifest;
    this.resourceContainers = resourceContainers;
  }

  /**
   * Returns the artifacts needed as inputs to process the resources/assets.
   */
  private Iterable<Artifact> getInputs() {
    if (inputs.isEmpty()) {
      FilesToRunProvider toolRunner =
          ruleContext.getExecutablePrerequisite("$android_tool_runner", Mode.HOST);
      // TODO(bazel-team): When using getFilesToRun(), the middleman is
      // not expanded. Fix by providing code to expand and use getFilesToRun here.
      RunfilesSupport aaptRunnerRunfiles = toolRunner.getRunfilesSupport();
      Preconditions.checkState(aaptRunnerRunfiles != null, toolRunner.getLabel());
      // Note the below may be an overapproximation of the actual runfiles, due to "conditional
      // artifacts" (see Runfiles.PruningManifest).
      Iterables.addAll(inputs, aaptRunnerRunfiles.getRunfilesArtifactsWithoutMiddlemen());
      inputs.add(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar());
      inputs.add(manifest);
      Iterables.addAll(inputs, Iterables.concat(Iterables.transform(resourceContainers,
          new Function<AndroidResourcesProvider.ResourceContainer, Iterable<Artifact>>() {
        @Override
        public Iterable<Artifact> apply(ResourceContainer container) {
          return container.getArtifacts();
        }
      })));
    }
    return inputs;
  }

  /**
   * Creates an Action that will invoke aapt to generate symbols java sources from the
   * resources and pack them into a srcjar.
   * @param javaSourcesJar Artifact to be generated by executing the action
   *        created by this method.
   * @param rTxt R.txt artifact to be generated by the aapt invocation.
   * @param javaPackage The package for which resources will be generated
   * @param inlineConstants whether or not constants in Java generated sources
   *        should be inlined by the compiler.
   */
  public void createGenerateResourceSymbolsAction(Artifact javaSourcesJar,
      Artifact rTxt, String javaPackage, boolean inlineConstants) {
    // java path from the provided package for the resources
    PathFragment javaPath = new PathFragment(javaPackage.replace('.', '/'));

    PathFragment javaResourcesRoot = javaSourcesJar.getRoot().getExecPath().getRelative(
        ruleContext.getUniqueDirectory("_java_resources"));

    String javaResources = javaResourcesRoot.getRelative(javaPath).getPathString();

    List<String> args = new ArrayList<>();
    args.add(javaSourcesJar.getExecPathString());
    args.add(javaResourcesRoot.getPathString());
    args.add(javaResources);

    args.addAll(createAaptCommand("javasrcs", javaSourcesJar, rTxt, inlineConstants,
        "-J", javaResources, "--custom-package", javaPackage, "--rename-manifest-package",
        javaPackage));
    final Builder builder = new SpawnAction.Builder()
        .addInputs(getInputs())
        .addTool(AndroidSdkProvider.fromRuleContext(ruleContext).getAapt())
        .setExecutable(
            ruleContext.getExecutablePrerequisite("$android_aapt_java_generator", Mode.HOST))
        .addOutput(javaSourcesJar)
        .setCommandLine(CommandLine.of(args, false))
        .useParameterFile(ParameterFileType.UNQUOTED)
        .setProgressMessage("Generating Java resources")
        .setMnemonic("AndroidAapt");
    if (rTxt != null) {
      builder.addOutput(rTxt);
    }
    ruleContext.registerAction(builder.build(ruleContext));
  }

  /**
   * Creates an Action that will invoke aapt to package the android resources
   * into an apk file.
   * @param apk Packed resources artifact to be generated by the aapt invocation.
   */
  public void createGenerateApkAction(Artifact apk, String renameManifestPackage,
      List<String> aaptOpts, List<String> densities) {
    List<String> args;

    if (renameManifestPackage == null) {
      args = createAaptCommand("apk", apk, null, true, "-F", apk.getExecPathString());
    } else {
      args = createAaptCommand("apk", apk, null, true, "-F",
          apk.getExecPathString(), "--rename-manifest-package", renameManifestPackage);
    }

    if (!densities.isEmpty()) {
      args.add(0, "start_densities");
      args.add(1, "end_densities");
      args.addAll(1, densities);
    }

    args.addAll(aaptOpts);

    ruleContext.registerAction(new SpawnAction.Builder()
        .addInputs(getInputs())
        .addTool(AndroidSdkProvider.fromRuleContext(ruleContext).getAapt())
        .addOutput(apk)
        .setExecutable(
            ruleContext.getExecutablePrerequisite("$android_aapt_apk_generator", Mode.HOST))
        .setCommandLine(CommandLine.of(args, false))
        .useParameterFile(ParameterFileType.UNQUOTED)
        .setProgressMessage("Generating apk resources")
        .setMnemonic("AndroidAapt")
        .build(ruleContext));
  }

  private List<String> createAaptCommand(String actionKind, Artifact output,
      Artifact rTxtOutput, boolean inlineConstants, String... outputArgs) {
    List<String> args = new ArrayList<>();
    args.addAll(getArgs(output, actionKind, ResourceType.RESOURCES));
    args.addAll(getArgs(output, actionKind, ResourceType.ASSETS));
    args.add(ruleContext.getExecutablePrerequisite("$android_tool_runner", Mode.HOST)
        .getExecutable().getExecPathString());
    args.add(
        AndroidSdkProvider.fromRuleContext(ruleContext).getAapt().getExecutable().getExecPathString());
    args.add("package");
    Collections.addAll(args, outputArgs);
    // Allow overlay in case the same resource appears in more than one target,
    // giving precedence to the order in which they are found. This is needed
    // in order to support android library projects.
    args.add("--auto-add-overlay");
    if (rTxtOutput != null) {
      args.add("--output-text-symbols");
      args.add(rTxtOutput.getExecPath().getParentDirectory().getPathString());
    }
    if (!inlineConstants) {
      args.add("--non-constant-id");
    }
    if (ruleContext.getConfiguration().getCompilationMode() != CompilationMode.OPT) {
      args.add("--debug-mode");
    }
    args.add("-I");
    args.add(AndroidSdkProvider.fromRuleContext(ruleContext).getAndroidJar().getExecPathString());
    args.add("-M");
    args.add(manifest.getExecPathString());
    args.addAll(getResourcesDirArg(output, actionKind, "-S", ResourceType.RESOURCES));
    args.addAll(getResourcesDirArg(output, actionKind, "-A", ResourceType.ASSETS));
    return args;
  }

  @VisibleForTesting
  public List<String> getArgs(Artifact output, String actionKind, ResourceType resourceType) {
    PathFragment outputPath = outputPath(output, actionKind, resourceType);
    List<String> args = new ArrayList<>();
    args.add("start_" + resourceType.getAttribute());
    args.add(outputPath.getPathString());
    // First make sure path elements are unique
    Collection<String> paths = new LinkedHashSet<>();
    for (AndroidResourcesProvider.ResourceContainer container : resourceContainers) {
      for (Artifact artifact : container.getArtifacts(resourceType)) {
        paths.add(artifact.getExecPathString());
      }
    }
    // Than populate the command line
    for (String path : paths) {
      args.add(path);
      args.add(path);
    }
    args.add("end_" + resourceType.getAttribute());

    // if there is at least one artifact
    if (args.size() > 3) {
      return ImmutableList.copyOf(args);
    } else {
      return ImmutableList.<String>of();
    }
  }

  /**
   * Returns optional part of the <code>aapt</code> command line:
   * optionName output_path.
   */
  @VisibleForTesting
  public List<String> getResourcesDirArg(Artifact output, String actionKind, String resourceArg,
      ResourceType resourceType) {
    PathFragment outputPath = outputPath(output, actionKind, resourceType);
    List<String> dirArgs = new ArrayList<>();
    Collection<String> paths = new LinkedHashSet<>();
    // First make sure roots are unique
    for (AndroidResourcesProvider.ResourceContainer container : resourceContainers) {
      for (PathFragment root : container.getRoots(resourceType)) {
        paths.add(outputPath.getRelative(root).getPathString());
      }
    }
    // Than populate the command line
    for (String path : paths) {
      dirArgs.add(resourceArg);
      dirArgs.add(path);
    }

    return ImmutableList.copyOf(dirArgs);
  }

  /**
   * Returns a resourceType specific unique output location for the given action kind.
   */
  private PathFragment outputPath(Artifact output, String actionKind, ResourceType resourceType) {
    return output.getRoot().getExecPath().getRelative(ruleContext.getUniqueDirectory(
        "_" + resourceType.getAttribute() + "_" + actionKind));
  }

  public void createGenerateProguardAction(Artifact outputSpec) {
    List<String> aaptCommand = createAaptCommand("proguard", outputSpec, null, true,
        "-G", outputSpec.getExecPathString());
    ruleContext.registerAction(new SpawnAction.Builder()
        .addInputs(getInputs())
        .addTool(AndroidSdkProvider.fromRuleContext(ruleContext).getAapt())
        .addOutput(outputSpec)
        .setExecutable(
            ruleContext.getExecutablePrerequisite("$android_aapt_apk_generator", Mode.HOST))
        .setCommandLine(CommandLine.of(aaptCommand, false))
        .useParameterFile(ParameterFileType.UNQUOTED)
        .setProgressMessage("Generating Proguard Configuration")
        .setMnemonic("AndroidAapt")
        .build(ruleContext));
  }
}