aboutsummaryrefslogtreecommitdiff
path: root/java/com/google/turbine/options/TurbineOptionsParser.java
blob: 55697ca21d55cc4a9df2905283909b5a635edf2a (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
/*
 * Copyright 2016 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.turbine.options;

import static com.google.common.base.Preconditions.checkArgument;
import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import org.checkerframework.checker.nullness.qual.Nullable;

/** A command line options parser for {@link TurbineOptions}. */
public class TurbineOptionsParser {

  /**
   * Parses command line options into {@link TurbineOptions}, expanding any {@code @params} files.
   */
  public static TurbineOptions parse(Iterable<String> args) throws IOException {
    TurbineOptions.Builder builder = TurbineOptions.builder();
    parse(builder, args);
    return builder.build();
  }

  /**
   * Parses command line options into a {@link TurbineOptions.Builder}, expanding any
   * {@code @params} files.
   */
  public static void parse(TurbineOptions.Builder builder, Iterable<String> args)
      throws IOException {
    Deque<String> argumentDeque = new ArrayDeque<>();
    expandParamsFiles(argumentDeque, args);
    parse(builder, argumentDeque);
  }

  private static void parse(TurbineOptions.Builder builder, Deque<String> argumentDeque) {
    while (!argumentDeque.isEmpty()) {
      String next = argumentDeque.pollFirst();
      switch (next) {
        case "--output":
          builder.setOutput(readOne(argumentDeque));
          break;
        case "--source_jars":
          builder.setSourceJars(readList(argumentDeque));
          break;
        case "--temp_dir":
          // TODO(cushon): remove this when Bazel no longer passes the flag
          readOne(argumentDeque);
          break;
        case "--processors":
          builder.addProcessors(readList(argumentDeque));
          break;
        case "--processorpath":
          builder.addProcessorPathEntries(readList(argumentDeque));
          break;
        case "--classpath":
          builder.addClassPathEntries(readList(argumentDeque));
          break;
        case "--bootclasspath":
          builder.addBootClassPathEntries(readList(argumentDeque));
          break;
        case "--release":
          builder.setRelease(readOne(argumentDeque));
          break;
        case "--system":
          builder.setSystem(readOne(argumentDeque));
          break;
        case "--javacopts":
          {
            ImmutableList<String> javacopts = readJavacopts(argumentDeque);
            setReleaseFromJavacopts(builder, javacopts);
            builder.addAllJavacOpts(javacopts);
            break;
          }
        case "--sources":
          builder.addSources(readList(argumentDeque));
          break;
        case "--output_deps":
          builder.setOutputDeps(readOne(argumentDeque));
          break;
        case "--direct_dependencies":
          builder.addDirectJars(readList(argumentDeque));
          break;
        case "--deps_artifacts":
          builder.addAllDepsArtifacts(readList(argumentDeque));
          break;
        case "--target_label":
          builder.setTargetLabel(readOne(argumentDeque));
          break;
        case "--injecting_rule_kind":
          builder.setInjectingRuleKind(readOne(argumentDeque));
          break;
        case "--javac_fallback":
          builder.setJavacFallback(true);
          break;
        case "--nojavac_fallback":
          builder.setJavacFallback(false);
          break;
        case "--reduce_classpath":
          builder.setShouldReduceClassPath(true);
          break;
        case "--noreduce_classpath":
          builder.setShouldReduceClassPath(false);
          break;
        case "--help":
          builder.setHelp(true);
          break;
        default:
          throw new IllegalArgumentException("unknown option: " + next);
      }
    }
  }

  private static final Splitter ARG_SPLITTER =
      Splitter.on(CharMatcher.breakingWhitespace()).omitEmptyStrings().trimResults();

  /**
   * Pre-processes an argument list, expanding arguments of the form {@code @filename} by reading
   * the content of the file and appending whitespace-delimited options to {@code argumentDeque}.
   */
  private static void expandParamsFiles(Deque<String> argumentDeque, Iterable<String> args)
      throws IOException {
    for (String arg : args) {
      if (arg.isEmpty()) {
        continue;
      }
      if (arg.charAt(0) == '\'') {
        // perform best-effort unescaping as a concession to ninja, see:
        // https://android.googlesource.com/platform/external/ninja/+/6f903faaf5488dc052ffc4e3e0b12757b426e088/src/util.cc#274
        checkArgument(arg.charAt(arg.length() - 1) == '\'', arg);
        arg = arg.substring(1, arg.length() - 1);
        checkArgument(!arg.contains("'"), arg);
      }
      if (arg.startsWith("@@")) {
        argumentDeque.addLast(arg.substring(1));
      } else if (arg.startsWith("@")) {
        Path paramsPath = Paths.get(arg.substring(1));
        if (!Files.exists(paramsPath)) {
          throw new AssertionError("params file does not exist: " + paramsPath);
        }
        expandParamsFiles(
            argumentDeque, ARG_SPLITTER.split(new String(Files.readAllBytes(paramsPath), UTF_8)));
      } else {
        argumentDeque.addLast(arg);
      }
    }
  }

  /** Returns the value of an option, or {@code null}. */
  @Nullable
  private static String readOne(Deque<String> argumentDeque) {
    if (argumentDeque.isEmpty() || argumentDeque.peekFirst().startsWith("-")) {
      return null;
    }
    return argumentDeque.pollFirst();
  }

  /** Returns a list of option values. */
  private static ImmutableList<String> readList(Deque<String> argumentDeque) {
    ImmutableList.Builder<String> result = ImmutableList.builder();
    while (!argumentDeque.isEmpty() && !argumentDeque.peekFirst().startsWith("--")) {
      result.add(argumentDeque.pollFirst());
    }
    return result.build();
  }

  /**
   * Returns a list of javacopts. Reads options until a terminating {@code "--"} is reached, to
   * support parsing javacopts that start with {@code --} (e.g. --release).
   */
  private static ImmutableList<String> readJavacopts(Deque<String> argumentDeque) {
    ImmutableList.Builder<String> result = ImmutableList.builder();
    while (!argumentDeque.isEmpty()) {
      String arg = argumentDeque.pollFirst();
      if (arg.equals("--")) {
        return result.build();
      }
      result.add(arg);
    }
    throw new IllegalArgumentException("javacopts should be terminated by `--`");
  }

  /**
   * Parses the given javacopts for {@code --release}, and if found sets turbine's {@code --release}
   * flag.
   */
  private static void setReleaseFromJavacopts(
      TurbineOptions.Builder builder, ImmutableList<String> javacopts) {
    Iterator<String> it = javacopts.iterator();
    while (it.hasNext()) {
      if (it.next().equals("--release") && it.hasNext()) {
        builder.setRelease(it.next());
      }
    }
  }
}