aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/rules/android/AndroidResourceValidatorActionBuilder.java
blob: ac051ea20cc97a7492bc0663c6ef42dbb1a324b2 (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
// Copyright 2016 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.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ParameterFile.ParameterFileType;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.actions.ActionConstructionContext;
import com.google.devtools.build.lib.analysis.actions.CustomCommandLine;
import com.google.devtools.build.lib.analysis.actions.CustomCommandLine.VectorArg;
import com.google.devtools.build.lib.analysis.actions.ParamFileInfo;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import java.util.ArrayList;
import java.util.List;

/**
 * Builder for creating $android_resource_validator action. This action validates merged resources
 * of an android_library via aapt, and writes out an R.txt file (mostly to serve as a dependency for
 * the android_binary -- otherwise the merger step could have generated the R.txt).
 *
 * <p>This is split from merging, so that it can happen off of the compilation critical path.
 */
public class AndroidResourceValidatorActionBuilder {

  private final RuleContext ruleContext;
  private final AndroidSdkProvider sdk;

  // Inputs
  private ResourceContainer primary;
  private Artifact mergedResources;

  // Outputs
  private Artifact rTxtOut;
  private Artifact sourceJarOut;

  // Flags
  private String customJavaPackage;
  private boolean debug;
  private Artifact staticLibraryOut;
  private ResourceDependencies resourceDeps;
  private Artifact aapt2SourceJarOut;
  private Artifact aapt2RTxtOut;
  private Artifact compiledSymbols;
  private Artifact apkOut;

  /** @param ruleContext The RuleContext that was used to create the SpawnAction.Builder. */
  public AndroidResourceValidatorActionBuilder(RuleContext ruleContext) {
    this.ruleContext = ruleContext;
    this.sdk = AndroidSdkProvider.fromRuleContext(ruleContext);
  }

  public AndroidResourceValidatorActionBuilder setStaticLibraryOut(Artifact staticLibraryOut) {
    this.staticLibraryOut = staticLibraryOut;
    return this;
  }

  /** The primary resource container. We mostly propagate its values, but update the R.txt. */
  public AndroidResourceValidatorActionBuilder withPrimary(ResourceContainer primary) {
    this.primary = primary;
    return this;
  }

  public AndroidResourceValidatorActionBuilder setMergedResources(Artifact mergedResources) {
    this.mergedResources = mergedResources;
    return this;
  }

  public AndroidResourceValidatorActionBuilder setJavaPackage(String customJavaPackage) {
    this.customJavaPackage = customJavaPackage;
    return this;
  }

  public AndroidResourceValidatorActionBuilder setDebug(boolean debug) {
    this.debug = debug;
    return this;
  }

  public AndroidResourceValidatorActionBuilder setRTxtOut(Artifact rTxtOut) {
    this.rTxtOut = rTxtOut;
    return this;
  }

  public AndroidResourceValidatorActionBuilder setSourceJarOut(Artifact sourceJarOut) {
    this.sourceJarOut = sourceJarOut;
    return this;
  }

  /** Used to add the static library from the dependencies. */
  public AndroidResourceValidatorActionBuilder withDependencies(ResourceDependencies resourceDeps) {
    this.resourceDeps = resourceDeps;
    return this;
  }

  public AndroidResourceValidatorActionBuilder setAapt2RTxtOut(Artifact aapt2RTxtOut) {
    this.aapt2RTxtOut = aapt2RTxtOut;
    return this;
  }

  public AndroidResourceValidatorActionBuilder setAapt2SourceJarOut(Artifact aapt2SourceJarOut) {
    this.aapt2SourceJarOut = aapt2SourceJarOut;
    return this;
  }

  public ResourceContainer build(ActionConstructionContext context) {
    ResourceContainer container = primary;
    if (rTxtOut != null) {
      container = createValidateAction(container, context);
    }
    if (compiledSymbols != null) {
      container = createLinkStaticLibraryAction(container, context);
    }
    return container;
  }

  public AndroidResourceValidatorActionBuilder setCompiledSymbols(Artifact compiledSymbols) {
    this.compiledSymbols = compiledSymbols;
    return this;
  }

  public AndroidResourceValidatorActionBuilder setApkOut(Artifact apkOut) {
    this.apkOut = apkOut;
    return this;
  }

  /**
   * This creates a static library using aapt2. It also generates a source jar and R.txt from aapt.
   *
   * <p>This allows the link action to replace the validate action for builds that use aapt2, as
   * opposed to executing both actions.
   */
  private ResourceContainer createLinkStaticLibraryAction(
      ResourceContainer validated, ActionConstructionContext context) {
    Preconditions.checkNotNull(staticLibraryOut);
    Preconditions.checkNotNull(aapt2SourceJarOut);
    Preconditions.checkNotNull(aapt2RTxtOut);
    Preconditions.checkNotNull(resourceDeps);

    CustomCommandLine.Builder builder = new CustomCommandLine.Builder();
    ImmutableList.Builder<Artifact> inputs = ImmutableList.builder();
    ImmutableList.Builder<Artifact> outs = ImmutableList.builder();

    // Set the busybox tool.
    builder.add("--tool").add("LINK_STATIC_LIBRARY").add("--");

    builder.addExecPath("--aapt2", sdk.getAapt2().getExecutable());

    FluentIterable<Artifact> libraries =
        FluentIterable.from(resourceDeps.getResources()).transform(
            ResourceContainer::getStaticLibrary).append(sdk.getAndroidJar());

    builder
        .add("--libraries")
        .addExecPaths(
            VectorArg.join(context.getConfiguration().getHostPathSeparator())
                .each(libraries.toList()));
    inputs.addAll(libraries);

    builder.addExecPath("--compiled", compiledSymbols);
    inputs.add(compiledSymbols);

    builder.addExecPath("--manifest", primary.getManifest());
    inputs.add(validated.getManifest());

    if (!Strings.isNullOrEmpty(customJavaPackage)) {
      // Sets an alternative java package for the generated R.java
      // this allows android rules to generate resources outside of the java{,tests} tree.
      builder.add("--packageForR", customJavaPackage);
    }

    builder.addExecPath("--sourceJarOut", aapt2SourceJarOut);
    outs.add(aapt2SourceJarOut);

    builder.addExecPath("--rTxtOut", aapt2RTxtOut);
    outs.add(aapt2RTxtOut);

    builder.addExecPath("--staticLibraryOut", staticLibraryOut);
    outs.add(staticLibraryOut);

    ruleContext.registerAction(
        new SpawnAction.Builder()
            .useDefaultShellEnvironment()
            .addTool(sdk.getAapt2())
            .addInputs(inputs.build())
            .addOutputs(outs.build())
            .addCommandLine(
                builder.build(), ParamFileInfo.builder(ParameterFileType.UNQUOTED).build())
            .setExecutable(
                ruleContext.getExecutablePrerequisite("$android_resources_busybox", Mode.HOST))
            .setProgressMessage(
                "Linking static android resource library for %s", ruleContext.getLabel())
            .setMnemonic("AndroidResourceLink")
            .build(context));

    return validated
        .toBuilder()
        .setAapt2JavaSourceJar(aapt2SourceJarOut)
        .setAapt2RTxt(aapt2RTxtOut)
        .setStaticLibrary(staticLibraryOut)
        .build();
  }

  private ResourceContainer createValidateAction(
      ResourceContainer primary, ActionConstructionContext context) {
    CustomCommandLine.Builder builder = new CustomCommandLine.Builder();

    // Set the busybox tool.
    builder.add("--tool").add("VALIDATE").add("--");

    if (!Strings.isNullOrEmpty(sdk.getBuildToolsVersion())) {
      builder.add("--buildToolsVersion", sdk.getBuildToolsVersion());
    }

    builder.addExecPath("--aapt", sdk.getAapt().getExecutable());

    ImmutableList.Builder<Artifact> inputs = ImmutableList.builder();

    builder.addExecPath("--annotationJar", sdk.getAnnotationsJar());
    inputs.add(sdk.getAnnotationsJar());

    builder.addExecPath("--androidJar", sdk.getAndroidJar());
    inputs.add(sdk.getAndroidJar());

    Preconditions.checkNotNull(mergedResources);
    builder.addExecPath("--mergedResources", mergedResources);
    inputs.add(mergedResources);

    builder.addExecPath("--manifest", primary.getManifest());
    inputs.add(primary.getManifest());

    if (debug) {
      builder.add("--debug");
    }

    if (!Strings.isNullOrEmpty(customJavaPackage)) {
      // Sets an alternative java package for the generated R.java
      // this allows android rules to generate resources outside of the java{,tests} tree.
      builder.add("--packageForR", customJavaPackage);
    }
    List<Artifact> outs = new ArrayList<>();
    Preconditions.checkNotNull(rTxtOut);
    builder.addExecPath("--rOutput", rTxtOut);
    outs.add(rTxtOut);

    Preconditions.checkNotNull(sourceJarOut);
    builder.addExecPath("--srcJarOutput", sourceJarOut);
    outs.add(sourceJarOut);

    if (apkOut != null) {
      builder.addExecPath("--packagePath", apkOut);
      outs.add(apkOut);
    }

    SpawnAction.Builder spawnActionBuilder = new SpawnAction.Builder();
    // Create the spawn action.
    ruleContext.registerAction(
        spawnActionBuilder
            .useDefaultShellEnvironment()
            .addTool(sdk.getAapt())
            .addInputs(inputs.build())
            .addOutputs(ImmutableList.copyOf(outs))
            .addCommandLine(
                builder.build(), ParamFileInfo.builder(ParameterFileType.UNQUOTED).build())
            .setExecutable(
                ruleContext.getExecutablePrerequisite("$android_resources_busybox", Mode.HOST))
            .setProgressMessage("Validating Android resources for %s", ruleContext.getLabel())
            .setMnemonic("AndroidResourceValidator")
            .build(context));

    // Return the full set of validated transitive dependencies.
    return primary.toBuilder()
        .setJavaSourceJar(sourceJarOut)
        .setRTxt(rTxtOut)
        .build();
  }
}