aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/tools/android/java/com/google/devtools/build/android/SplitConfigurationFilter.java
blob: 4103b800a280cd64797ee444d5325f05d58b6107 (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
// 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.android;

import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A parsed set of configuration filters for a split flag or an output filename.
 *
 * <p>The natural ordering of this class sorts by number of configurations, then by highest required
 * API version, if any, then by other specifiers (case-insensitive), with ties broken by the
 * filename or split flag originally used to create the instance (case-sensitive).
 *
 * <p>This has the following useful property:<br>
 * Given two sets of {@link SplitConfigurationFilter}s, one from the input split flags, and one from
 * aapt's outputs... Each member of the output set can be matched to the greatest member of the
 * input set for which {@code input.matchesFilterFromFilename(output)} is true.
 */
final class SplitConfigurationFilter implements Comparable<SplitConfigurationFilter> {

  /**
   * Finds a mapping from filename suffixes to the split flags which could have spawned them.
   *
   * @param filenames The suffixes of the original apk filenames output by aapt, not including the
   *     underscore used to set it off from the base filename or the base filename itself.
   * @param splitFlags The split flags originally passed to aapt.
   * @return A map whose keys are the filenames from {@code filenames} and whose values are
   *     predictable filenames based on the split flags - that is, the commas present in the input
   *     have been replaced with underscores.
   * @throws UnrecognizedSplitException if any of the inputs are unused or could not be matched
   */
  static Map<String, String> mapFilenamesToSplitFlags(
      Iterable<String> filenames, Iterable<String> splitFlags) throws UnrecognizedSplitsException {
    TreeSet<SplitConfigurationFilter> filenameFilters = new TreeSet<>();
    for (String filename : filenames) {
      filenameFilters.add(SplitConfigurationFilter.fromFilenameSuffix(filename));
    }
    TreeSet<SplitConfigurationFilter> flagFilters = new TreeSet<>();
    for (String splitFlag : splitFlags) {
      flagFilters.add(SplitConfigurationFilter.fromSplitFlag(splitFlag));
    }
    ImmutableMap.Builder<String, String> result = ImmutableMap.builder();
    List<String> unidentifiedFilenames = new ArrayList<>();
    for (SplitConfigurationFilter filenameFilter : filenameFilters) {
      Optional<SplitConfigurationFilter> matched =
          Iterables.tryFind(flagFilters, new MatchesFilterFromFilename(filenameFilter));
      if (matched.isPresent()) {
        result.put(filenameFilter.filename, matched.get().filename);
        flagFilters.remove(matched.get());
      } else {
        unidentifiedFilenames.add(filenameFilter.filename);
      }
    }
    if (!(unidentifiedFilenames.isEmpty() && flagFilters.isEmpty())) {
      ImmutableList.Builder<String> unidentifiedFlags = ImmutableList.builder();
      for (SplitConfigurationFilter flagFilter : flagFilters) {
        unidentifiedFlags.add(flagFilter.filename);
      }
      throw new UnrecognizedSplitsException(
          unidentifiedFlags.build(), unidentifiedFilenames, result.build());
    }
    return result.build();
  }

  /**
   * Exception thrown when mapFilenamesToSplitFlags fails to find matches for all elements of both
   * input sets.
   */
  static final class UnrecognizedSplitsException extends Exception {
    private final ImmutableList<String> unidentifiedSplits;
    private final ImmutableList<String> unidentifiedFilenames;
    private final ImmutableMap<String, String> identifiedSplits;

    UnrecognizedSplitsException(
        Iterable<String> unidentifiedSplits,
        Iterable<String> unidentifiedFilenames,
        Map<String, String> identifiedSplits) {
      super(
          "Could not find matching filenames for these split flags:\n"
              + Joiner.on("\n").join(unidentifiedSplits)
              + "\nnor matching split flags for these filenames:\n"
              + Joiner.on(", ").join(unidentifiedFilenames)
              + "\nFound these (filename => split flag) matches though:\n"
              + Joiner.on("\n").withKeyValueSeparator(" => ").join(identifiedSplits));
      this.unidentifiedSplits = ImmutableList.copyOf(unidentifiedSplits);
      this.unidentifiedFilenames = ImmutableList.copyOf(unidentifiedFilenames);
      this.identifiedSplits = ImmutableMap.copyOf(identifiedSplits);
    }

    /** Returns the list of split flags which did not find a match. */
    ImmutableList<String> getUnidentifiedSplits() {
      return unidentifiedSplits;
    }

    /** Returns the list of filename suffixes which did not find a match. */
    ImmutableList<String> getUnidentifiedFilenames() {
      return unidentifiedFilenames;
    }

    /** Returns the mapping from filename suffix to split flag for splits that did match. */
    ImmutableMap<String, String> getIdentifiedSplits() {
      return identifiedSplits;
    }
  }

  /** Generates a SplitConfigurationFilter from a split flag. */
  static SplitConfigurationFilter fromSplitFlag(String flag) {
    return SplitConfigurationFilter.fromFilenameSuffix(flag.replace(',', '_'));
  }

  /** Generates a SplitConfigurationFilter from the suffix of a split generated by aapt. */
  static SplitConfigurationFilter fromFilenameSuffix(String suffix) {
    ImmutableSortedSet.Builder<ResourceConfiguration> configs = ImmutableSortedSet.reverseOrder();
    for (String configuration : Splitter.on('_').split(suffix)) {
      configs.add(ResourceConfiguration.fromString(configuration));
    }
    return new SplitConfigurationFilter(suffix, configs.build());
  }

  /**
   * The suffix to be appended to the output package for this split configuration.
   *
   * <p>When created with {@link fromFilenameSuffix}, this will be the original filename from aapt;
   * when created with {@link fromSplitFlag}, this will be the filename to rename to.
   */
  private final String filename;

  /**
   * A set of resource configurations which will be included in this split, sorted so that the
   * configs with the highest API versions come first.
   *
   * <p>It's okay for this to collapse duplicates, because aapt forbids duplicate resource
   * configurations across all splits in the same invocation anyway.
   */
  private final ImmutableSortedSet<ResourceConfiguration> configs;

  private SplitConfigurationFilter(
      String filename, ImmutableSortedSet<ResourceConfiguration> configs) {
    this.filename = filename;
    this.configs = configs;
  }

  /**
   * Checks if the {@code other} split configuration filter could have been produced as a filename
   * by aapt based on this configuration filter being passed as a split flag.
   *
   * <p>This means that there must be a one-to-one mapping from each configuration in this filter to
   * a configuration in the {@code other} filter such that the non-API-version specifiers of the two
   * configurations match and the API version specifier of the {@code other} filter's configuration
   * is greater than or equal to the API version specifier of this filter's configuration.
   *
   * <p>Order of whole configurations doesn't matter, as aapt will reorder the configurations
   * according to complicated internal logic (yes, logic even more complicated than this!).
   *
   * <p>Care is needed with API version specifiers because aapt may add or change minimum API
   * version specifiers to configurations according to whether they had specifiers which are only
   * supported in certain versions of Android. It will only ever increase the minimum version or
   * leave it the same.
   *
   * <p>The other (non-wildcard) specifiers should be case-insensitive identical, including order;
   * aapt will not allow parts of a single configuration to be parsed out of order.
   *
   * @see ResourceConfiguration#matchesConfigurationFromFilename(ResourceConfiguration)
   */
  boolean matchesFilterFromFilename(SplitConfigurationFilter filenameFilter) {
    if (filenameFilter.configs.size() != this.configs.size()) {
      return false;
    }

    List<ResourceConfiguration> unmatchedConfigs = new ArrayList<>(this.configs);
    for (ResourceConfiguration filenameConfig : filenameFilter.configs) {
      Optional<ResourceConfiguration> matched =
          Iterables.tryFind(
              unmatchedConfigs,
              new ResourceConfiguration.MatchesConfigurationFromFilename(filenameConfig));
      if (!matched.isPresent()) {
        return false;
      }
      unmatchedConfigs.remove(matched.get());
    }
    return true;
  }

  static final class MatchesFilterFromFilename implements Predicate<SplitConfigurationFilter> {
    private final SplitConfigurationFilter filenameFilter;

    MatchesFilterFromFilename(SplitConfigurationFilter filenameFilter) {
      this.filenameFilter = filenameFilter;
    }

    @Override
    public boolean apply(SplitConfigurationFilter flagFilter) {
      return flagFilter.matchesFilterFromFilename(filenameFilter);
    }
  }

  private static final Ordering<Iterable<ResourceConfiguration>> CONFIG_LEXICOGRAPHICAL =
      Ordering.natural().lexicographical();

  @Override
  public int compareTo(SplitConfigurationFilter other) {
    return ComparisonChain.start()
        .compare(this.configs.size(), other.configs.size())
        .compare(this.configs, other.configs, CONFIG_LEXICOGRAPHICAL)
        .compare(this.filename, other.filename)
        .result();
  }

  @Override
  public int hashCode() {
    return Objects.hash(configs, filename);
  }

  @Override
  public boolean equals(Object object) {
    if (object instanceof SplitConfigurationFilter) {
      SplitConfigurationFilter other = (SplitConfigurationFilter) object;
      // the configs are derived from the filename, so we can be assured they are equal if the
      // filenames are.
      return Objects.equals(this.filename, other.filename);
    }
    return false;
  }

  @Override
  public String toString() {
    return "SplitConfigurationFilter{" + filename + "}";
  }

  /**
   * An individual set of configuration specifiers, for the purposes of split name parsing.
   *
   * <p>The natural ordering of this class sorts by required API version, if any, then by other
   * specifiers.
   *
   * <p>This has the following useful property:<br>
   * Given two sets of {@link ResourceConfiguration}s, one from an input split flag, and one from
   * aapt's output... Each member of the output set can be matched to the greatest member of the
   * input set for which {@code input.matchesConfigurationFromFilename(output)} is true.
   */
  static final class ResourceConfiguration implements Comparable<ResourceConfiguration> {
    /**
     * Pattern to match wildcard parts ("any"), which can be safely ignored - aapt drops them.
     *
     * <p>Matches an 'any' part and the dash following it, or for an 'any' part which is the last
     * specifier, the dash preceding it. In the former case, it must be a full part - that is,
     * preceded by the beginning of the string or a dash, which will not be consumed.
     */
    private static final Pattern WILDCARD_SPECIFIER = Pattern.compile("(?<=^|-)any(?:-|$)|-any$");
    /**
     * Pattern to match the API version and capture the version number.
     *
     * <p>It must always be the last specifier in a config, although it may also be the first if
     * there are no other specifiers.
     */
    private static final Pattern API_VERSION = Pattern.compile("(?:-|^)v(\\d+)$");

    /** Parses a resource configuration into a form that can be compared to other configurations. */
    static ResourceConfiguration fromString(String text) {
      // Case is ignored for resource configurations (aapt lowercases internally),
      // and wildcards can be dropped.
      String cleanSpecifiers =
          WILDCARD_SPECIFIER.matcher(text.toLowerCase(Locale.ENGLISH)).replaceAll("");
      Matcher apiVersionMatcher = API_VERSION.matcher(cleanSpecifiers);
      if (apiVersionMatcher.find()) {
        return new ResourceConfiguration(
            cleanSpecifiers.substring(0, apiVersionMatcher.start()),
            Integer.parseInt(apiVersionMatcher.group(1)));
      } else {
        return new ResourceConfiguration(cleanSpecifiers, 0);
      }
    }

    /** The specifiers for this resource configuration, besides API version, in lowercase. */
    private final String specifiers;

    /** The API version, or 0 to indicate that no API version was present in the original config. */
    private final int apiVersion;

    private ResourceConfiguration(String specifiers, int apiVersion) {
      this.specifiers = specifiers;
      this.apiVersion = apiVersion;
    }

    /**
     * Checks that the {@code other} configuration could be a filename generated from this one.
     *
     * @see SplitConfigurationFilter#matchesFilterFromFilename(SplitConfigurationFilter)
     */
    boolean matchesConfigurationFromFilename(ResourceConfiguration other) {
      return Objects.equals(other.specifiers, this.specifiers)
          && other.apiVersion >= this.apiVersion;
    }

    static final class MatchesConfigurationFromFilename
        implements Predicate<ResourceConfiguration> {
      private final ResourceConfiguration filenameConfig;

      MatchesConfigurationFromFilename(ResourceConfiguration filenameConfig) {
        this.filenameConfig = filenameConfig;
      }

      @Override
      public boolean apply(ResourceConfiguration flagConfig) {
        return flagConfig.matchesConfigurationFromFilename(filenameConfig);
      }
    }

    @Override
    public int compareTo(ResourceConfiguration other) {
      return ComparisonChain.start()
          .compare(this.apiVersion, other.apiVersion)
          .compare(this.specifiers, other.specifiers)
          .result();
    }

    @Override
    public int hashCode() {
      return Objects.hash(specifiers, apiVersion);
    }

    @Override
    public boolean equals(Object object) {
      if (object instanceof ResourceConfiguration) {
        ResourceConfiguration other = (ResourceConfiguration) object;
        return Objects.equals(this.specifiers, other.specifiers)
            && this.apiVersion == other.apiVersion;
      }
      return false;
    }

    @Override
    public String toString() {
      return "ResourceConfiguration{" + specifiers + "-v" + Integer.toString(apiVersion) + "}";
    }
  }
}