aboutsummaryrefslogtreecommitdiff
path: root/java/dagger/hilt/android/testing/compile/HiltCompilerTests.java
blob: 89bf67882bd195820d38bad2e6edfd63df47c42b (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
/*
 * Copyright (C) 2020 The Dagger Authors.
 *
 * 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 dagger.hilt.android.testing.compile;

import static dagger.internal.codegen.extension.DaggerStreams.toImmutableList;
import static java.util.stream.Collectors.toMap;

import androidx.room.compiler.processing.XProcessingEnv;
import androidx.room.compiler.processing.util.CompilationResultSubject;
import androidx.room.compiler.processing.util.ProcessorTestExtKt;
import androidx.room.compiler.processing.util.Source;
import androidx.room.compiler.processing.util.compiler.TestCompilationArguments;
import androidx.room.compiler.processing.util.compiler.TestCompilationResult;
import androidx.room.compiler.processing.util.compiler.TestKotlinCompilerKt;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.ksp.processing.SymbolProcessorProvider;
import com.google.testing.compile.Compiler;
import dagger.hilt.android.processor.internal.androidentrypoint.AndroidEntryPointProcessor;
import dagger.hilt.android.processor.internal.androidentrypoint.KspAndroidEntryPointProcessor;
import dagger.hilt.android.processor.internal.customtestapplication.CustomTestApplicationProcessor;
import dagger.hilt.android.processor.internal.customtestapplication.KspCustomTestApplicationProcessor;
import dagger.hilt.processor.internal.BaseProcessingStep;
import dagger.hilt.processor.internal.HiltProcessingEnvConfigs;
import dagger.hilt.processor.internal.aggregateddeps.AggregatedDepsProcessor;
import dagger.hilt.processor.internal.aggregateddeps.KspAggregatedDepsProcessor;
import dagger.hilt.processor.internal.aliasof.AliasOfProcessor;
import dagger.hilt.processor.internal.aliasof.KspAliasOfProcessor;
import dagger.hilt.processor.internal.definecomponent.DefineComponentProcessor;
import dagger.hilt.processor.internal.definecomponent.KspDefineComponentProcessor;
import dagger.hilt.processor.internal.earlyentrypoint.EarlyEntryPointProcessor;
import dagger.hilt.processor.internal.earlyentrypoint.KspEarlyEntryPointProcessor;
import dagger.hilt.processor.internal.generatesrootinput.GeneratesRootInputProcessor;
import dagger.hilt.processor.internal.generatesrootinput.KspGeneratesRootInputProcessor;
import dagger.hilt.processor.internal.originatingelement.KspOriginatingElementProcessor;
import dagger.hilt.processor.internal.originatingelement.OriginatingElementProcessor;
import dagger.hilt.processor.internal.root.ComponentTreeDepsProcessor;
import dagger.hilt.processor.internal.root.KspComponentTreeDepsProcessor;
import dagger.hilt.processor.internal.root.KspRootProcessor;
import dagger.hilt.processor.internal.root.RootProcessor;
import dagger.hilt.processor.internal.uninstallmodules.KspUninstallModulesProcessor;
import dagger.hilt.processor.internal.uninstallmodules.UninstallModulesProcessor;
import dagger.internal.codegen.ComponentProcessor;
import dagger.internal.codegen.KspComponentProcessor;
import dagger.testing.compile.CompilerTests;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.annotation.processing.Processor;
import org.junit.rules.TemporaryFolder;

/** {@link Compiler} instances for testing Android Hilt. */
public final class HiltCompilerTests {
  /** Returns the {@link XProcessingEnv.Backend} for the given {@link CompilationResultSubject}. */
  public static XProcessingEnv.Backend backend(CompilationResultSubject subject) {
    return CompilerTests.backend(subject);
  }

  /** Returns a {@link Source.KotlinSource} with the given file name and content. */
  public static Source.KotlinSource kotlinSource(
      String fileName, ImmutableCollection<String> srcLines) {
    return CompilerTests.kotlinSource(fileName, srcLines);
  }

  /** Returns a {@link Source.KotlinSource} with the given file name and content. */
  public static Source.KotlinSource kotlinSource(String fileName, String... srcLines) {
    return CompilerTests.kotlinSource(fileName, srcLines);
  }

  /** Returns a {@link Source.JavaSource} with the given file name and content. */
  public static Source.JavaSource javaSource(
      String fileName, ImmutableCollection<String> srcLines) {
    return CompilerTests.javaSource(fileName, srcLines);
  }

  /** Returns a {@link Source.JavaSource} with the given file name and content. */
  public static Source.JavaSource javaSource(String fileName, String... srcLines) {
    return CompilerTests.javaSource(fileName, srcLines);
  }

  /** Returns a {@link Compiler} instance with the given sources. */
  public static HiltCompiler hiltCompiler(Source... sources) {
    return hiltCompiler(ImmutableList.copyOf(sources));
  }

  /** Returns a {@link Compiler} instance with the given sources. */
  public static HiltCompiler hiltCompiler(ImmutableCollection<Source> sources) {
    return HiltCompiler.builder().sources(sources).build();
  }

  public static Compiler compiler(Processor... extraProcessors) {
    return compiler(Arrays.asList(extraProcessors));
  }

  public static Compiler compiler(Collection<? extends Processor> extraProcessors) {
    Map<Class<?>, Processor> processors =
        defaultProcessors().stream()
            .collect(toMap((Processor e) -> e.getClass(), (Processor e) -> e));

    // Adds extra processors, and allows overriding any processors of the same class.
    extraProcessors.forEach(processor -> processors.put(processor.getClass(), processor));

    return CompilerTests.compiler().withProcessors(processors.values());
  }

  public static void compileWithKapt(
      List<Source> sources,
      TemporaryFolder tempFolder,
      Consumer<TestCompilationResult> onCompilationResult) {
    compileWithKapt(
        sources, ImmutableMap.of(), ImmutableList.of(), tempFolder, onCompilationResult);
  }

  public static void compileWithKapt(
      List<Source> sources,
      Map<String, String> processorOptions,
      TemporaryFolder tempFolder,
      Consumer<TestCompilationResult> onCompilationResult) {
    compileWithKapt(
        sources, processorOptions, ImmutableList.of(), tempFolder, onCompilationResult);
  }

  public static void compileWithKapt(
      List<Source> sources,
      List<Processor> additionalProcessors,
      TemporaryFolder tempFolder,
      Consumer<TestCompilationResult> onCompilationResult) {
    compileWithKapt(
        sources, ImmutableMap.of(), additionalProcessors, tempFolder, onCompilationResult);
  }

  public static void compileWithKapt(
      List<Source> sources,
      Map<String, String> processorOptions,
      List<Processor> additionalProcessors,
      TemporaryFolder tempFolder,
      Consumer<TestCompilationResult> onCompilationResult) {
    TestCompilationResult result =
        TestKotlinCompilerKt.compile(
            tempFolder.getRoot(),
            new TestCompilationArguments(
                sources,
                /* classpath= */ ImmutableList.of(CompilerTests.compilerDepsJar()),
                /* inheritClasspath= */ false,
                /* javacArguments= */ ImmutableList.of(),
                /* kotlincArguments= */ ImmutableList.of(),
                /* kaptProcessors= */ ImmutableList.<Processor>builder()
                    .addAll(defaultProcessors())
                    .addAll(additionalProcessors)
                    .build(),
                /* symbolProcessorProviders= */ ImmutableList.of(),
                /* processorOptions= */ processorOptions));
    onCompilationResult.accept(result);
  }

  static ImmutableList<Processor> defaultProcessors() {
    return ImmutableList.of(
        new AggregatedDepsProcessor(),
        new AliasOfProcessor(),
        new AndroidEntryPointProcessor(),
        new ComponentProcessor(),
        new ComponentTreeDepsProcessor(),
        new CustomTestApplicationProcessor(),
        new DefineComponentProcessor(),
        new EarlyEntryPointProcessor(),
        new GeneratesRootInputProcessor(),
        new OriginatingElementProcessor(),
        new RootProcessor(),
        new UninstallModulesProcessor());
  }

  private static ImmutableList<SymbolProcessorProvider> kspDefaultProcessors() {
    // TODO(bcorso): Add the rest of the KSP processors here.
    return ImmutableList.of(
        new KspAggregatedDepsProcessor.Provider(),
        new KspAliasOfProcessor.Provider(),
        new KspAndroidEntryPointProcessor.Provider(),
        new KspComponentProcessor.Provider(),
        new KspComponentTreeDepsProcessor.Provider(),
        new KspCustomTestApplicationProcessor.Provider(),
        new KspDefineComponentProcessor.Provider(),
        new KspEarlyEntryPointProcessor.Provider(),
        new KspGeneratesRootInputProcessor.Provider(),
        new KspOriginatingElementProcessor.Provider(),
        new KspRootProcessor.Provider(),
        new KspUninstallModulesProcessor.Provider());
  }

  /** Used to compile Hilt sources and inspect the compiled results. */
  @AutoValue
  public abstract static class HiltCompiler {
    static Builder builder() {
      return new AutoValue_HiltCompilerTests_HiltCompiler.Builder()
          // Set the builder defaults.
          .processorOptions(ImmutableMap.of())
          .additionalJavacProcessors(ImmutableList.of())
          .additionalKspProcessors(ImmutableList.of())
          .processingSteps(ImmutableList.of())
          .javacArguments(ImmutableList.of());
    }

    /** Returns the sources being compiled */
    abstract ImmutableCollection<Source> sources();

    /** Returns the annotation processors options. */
    abstract ImmutableMap<String, String> processorOptions();

    /** Returns the extra Javac processors. */
    abstract ImmutableCollection<Processor> additionalJavacProcessors();

    /** Returns the extra KSP processors. */
    abstract ImmutableCollection<SymbolProcessorProvider> additionalKspProcessors();

    /** Returns the command-line options */
    abstract ImmutableCollection<String> javacArguments();

    /** Returns a new {@link HiltCompiler} instance with the annotation processors options. */
    public HiltCompiler withProcessorOptions(ImmutableMap<String, String> processorOptions) {
      return toBuilder().processorOptions(processorOptions).build();
    }

    /** Returns the processing steps suppliers. */
    abstract ImmutableCollection<Function<XProcessingEnv, BaseProcessingStep>> processingSteps();

    public HiltCompiler withProcessingSteps(
        Function<XProcessingEnv, BaseProcessingStep>... mapping) {
      return toBuilder().processingSteps(ImmutableList.copyOf(mapping)).build();
    }

    /** Returns a new {@link HiltCompiler} instance with the additional Javac processors. */
    public HiltCompiler withAdditionalJavacProcessors(Processor... processors) {
      return toBuilder().additionalJavacProcessors(ImmutableList.copyOf(processors)).build();
    }

    /** Returns a new {@link HiltCompiler} instance with the additional KSP processors. */
    public HiltCompiler withAdditionalKspProcessors(SymbolProcessorProvider... processors) {
      return toBuilder().additionalKspProcessors(ImmutableList.copyOf(processors)).build();
    }

    /** Returns a new {@link HiltCompiler} instance with command-line options. */
    public HiltCompiler withJavacArguments(String... arguments) {
      return toBuilder().javacArguments(ImmutableList.copyOf(arguments)).build();
    }

    /** Returns a new {@link HiltCompiler} instance with command-line options. */
    public HiltCompiler withJavacArguments(ImmutableCollection<String> arguments) {
      return toBuilder().javacArguments(arguments).build();
    }

    /** Returns a builder with the current values of this {@link Compiler} as default. */
    abstract Builder toBuilder();

    public void compile(Consumer<CompilationResultSubject> onCompilationResult) {
      ProcessorTestExtKt.runProcessorTest(
          sources().asList(),
          /* classpath= */ ImmutableList.of(CompilerTests.compilerDepsJar()),
          /* options= */ processorOptions(),
          /* javacArguments= */ javacArguments().asList(),
          /* kotlincArguments= */ ImmutableList.of(
              "-P", "plugin:org.jetbrains.kotlin.kapt3:correctErrorTypes=true"),
          /* config= */ HiltProcessingEnvConfigs.CONFIGS,
          /* javacProcessors= */ ImmutableList.<Processor>builder()
              .addAll(mergeProcessors(defaultProcessors(), additionalJavacProcessors()))
              .addAll(
                  processingSteps().stream()
                      .map(HiltCompilerProcessors.JavacProcessor::new)
                      .collect(toImmutableList()))
              .build(),
          /* symbolProcessorProviders= */ ImmutableList.<SymbolProcessorProvider>builder()
              .addAll(mergeProcessors(kspDefaultProcessors(), additionalKspProcessors()))
              .addAll(
                  processingSteps().stream()
                      .map(HiltCompilerProcessors.KspProcessor.Provider::new)
                      .collect(toImmutableList()))
              .build(),
          result -> {
            onCompilationResult.accept(result);
            return null;
          });
    }

    private static <T> ImmutableList<T> mergeProcessors(
        Collection<T> defaultProcessors, Collection<T> extraProcessors) {
      Map<Class<?>, T> processors =
          defaultProcessors.stream().collect(toMap((T e) -> e.getClass(), (T e) -> e));
      // Adds extra processors, and allows overriding any processors of the same class.
      extraProcessors.forEach(processor -> processors.put(processor.getClass(), processor));
      return ImmutableList.copyOf(processors.values());
    }

    /** Used to build a {@link HiltCompiler}. */
    @AutoValue.Builder
    public abstract static class Builder {
      abstract Builder sources(ImmutableCollection<Source> sources);
      abstract Builder processorOptions(ImmutableMap<String, String> processorOptions);
      abstract Builder additionalJavacProcessors(ImmutableCollection<Processor> processors);
      abstract Builder additionalKspProcessors(
          ImmutableCollection<SymbolProcessorProvider> processors);
      abstract Builder javacArguments(ImmutableCollection<String> arguments);

      abstract Builder processingSteps(
          ImmutableCollection<Function<XProcessingEnv, BaseProcessingStep>> processingSteps);

      abstract HiltCompiler build();
    }
  }

  private HiltCompilerTests() {}
}