test_compiler.dart 7.83 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
// @dart = 2.8

7 8 9 10 11 12 13 14 15
import 'dart:async';

import 'package:meta/meta.dart';

import '../artifacts.dart';
import '../base/file_system.dart';
import '../build_info.dart';
import '../bundle.dart';
import '../compile.dart';
16
import '../flutter_plugins.dart';
17
import '../globals_null_migrated.dart' as globals;
18 19 20
import '../project.dart';

/// A request to the [TestCompiler] for recompilation.
21 22
class CompilationRequest {
  CompilationRequest(this.mainUri, this.result);
23 24

  Uri mainUri;
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
  Completer<String> result;
}

/// A frontend_server wrapper for the flutter test runner.
///
/// This class is a wrapper around compiler that allows multiple isolates to
/// enqueue compilation requests, but ensures only one compilation at a time.
class TestCompiler {
  /// Creates a new [TestCompiler] which acts as a frontend_server proxy.
  ///
  /// [trackWidgetCreation] configures whether the kernel transform is applied
  /// to the output. This also changes the output file to include a '.track`
  /// extension.
  ///
  /// [flutterProject] is the project for which we are running tests.
40 41 42
  ///
  /// If [precompiledDillPath] is passed, it will be used to initialize the
  /// compiler.
43
  TestCompiler(
44
    this.buildInfo,
45
    this.flutterProject,
46 47
    { String precompiledDillPath }
  ) : testFilePath = precompiledDillPath ?? globals.fs.path.join(
48 49 50 51 52 53 54
        flutterProject.directory.path,
        getBuildDirectory(),
        'test_cache',
        getDefaultCachedKernelPath(
          trackWidgetCreation: buildInfo.trackWidgetCreation,
          dartDefines: buildInfo.dartDefines,
          extraFrontEndOptions: buildInfo.extraFrontEndOptions,
55 56
        )),
       shouldCopyDillFile = precompiledDillPath == null {
57 58 59
    // Compiler maintains and updates single incremental dill file.
    // Incremental compilation requests done for each test copy that file away
    // for independent execution.
60
    final Directory outputDillDirectory = globals.fs.systemTempDirectory.createTempSync('flutter_test_compiler.');
61
    outputDill = outputDillDirectory.childFile('output.dill');
62 63
    globals.printTrace('Compiler will use the following file as its incremental dill file: ${outputDill.path}');
    globals.printTrace('Listening to compiler controller...');
64
    compilerController.stream.listen(_onCompilationRequest, onDone: () {
65
      globals.printTrace('Deleting ${outputDillDirectory.path}...');
66 67 68 69
      outputDillDirectory.deleteSync(recursive: true);
    });
  }

70 71
  final StreamController<CompilationRequest> compilerController = StreamController<CompilationRequest>();
  final List<CompilationRequest> compilationQueue = <CompilationRequest>[];
72
  final FlutterProject flutterProject;
73
  final BuildInfo buildInfo;
74
  final String testFilePath;
75
  final bool shouldCopyDillFile;
76 77 78 79 80


  ResidentCompiler compiler;
  File outputDill;

81
  Future<String> compile(Uri mainDart) {
82
    final Completer<String> completer = Completer<String>();
83
    if (compilerController.isClosed) {
84
      return Future<String>.value();
85
    }
86
    compilerController.add(CompilationRequest(mainDart, completer));
87 88 89 90 91 92 93 94 95 96 97 98 99 100
    return completer.future;
  }

  Future<void> _shutdown() async {
    // Check for null in case this instance is shut down before the
    // lazily-created compiler has been created.
    if (compiler != null) {
      await compiler.shutdown();
      compiler = null;
    }
  }

  Future<void> dispose() async {
    await compilerController.close();
101
    await _shutdown();
102 103 104 105 106
  }

  /// Create the resident compiler used to compile the test.
  @visibleForTesting
  Future<ResidentCompiler> createCompiler() async {
107
    final ResidentCompiler residentCompiler = ResidentCompiler(
108
      globals.artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath),
109 110 111
      artifacts: globals.artifacts,
      logger: globals.logger,
      processManager: globals.processManager,
112 113
      buildMode: buildInfo.mode,
      trackWidgetCreation: buildInfo.trackWidgetCreation,
114 115
      initializeFromDill: testFilePath,
      unsafePackageSerialization: false,
116
      dartDefines: buildInfo.dartDefines,
117
      packagesPath: buildInfo.packagesPath,
118
      extraFrontEndOptions: buildInfo.extraFrontEndOptions,
119
      platform: globals.platform,
120
      testCompilation: true,
121
      fileSystem: globals.fs,
122 123
      fileSystemRoots: buildInfo.fileSystemRoots,
      fileSystemScheme: buildInfo.fileSystemScheme,
124
    );
125
    return residentCompiler;
126 127 128
  }

  // Handle a compilation request.
129
  Future<void> _onCompilationRequest(CompilationRequest request) async {
130 131 132 133 134 135 136 137 138
    final bool isEmpty = compilationQueue.isEmpty;
    compilationQueue.add(request);
    // Only trigger processing if queue was empty - i.e. no other requests
    // are currently being processed. This effectively enforces "one
    // compilation request at a time".
    if (!isEmpty) {
      return;
    }
    while (compilationQueue.isNotEmpty) {
139
      final CompilationRequest request = compilationQueue.first;
140
      globals.printTrace('Compiling ${request.mainUri}');
141 142 143 144 145 146
      final Stopwatch compilerTime = Stopwatch()..start();
      bool firstCompile = false;
      if (compiler == null) {
        compiler = await createCompiler();
        firstCompile = true;
      }
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162

      final List<Uri> invalidatedRegistrantFiles = <Uri>[];
      if (flutterProject != null) {
        // Update the generated registrant to use the test target's main.
        final String mainUriString = buildInfo.packageConfig.toPackageUri(request.mainUri)?.toString()
          ?? request.mainUri.toString();
        await generateMainDartWithPluginRegistrant(
          flutterProject,
          buildInfo.packageConfig,
          mainUriString,
          globals.fs.file(request.mainUri),
          throwOnPluginPubspecError: false,
        );
        invalidatedRegistrantFiles.add(flutterProject.dartPluginRegistrant.absolute.uri);
      }

163
      final CompilerOutput compilerOutput = await compiler.recompile(
164
        request.mainUri,
165
        <Uri>[request.mainUri, ...invalidatedRegistrantFiles],
166
        outputPath: outputDill.path,
167
        packageConfig: buildInfo.packageConfig,
168
        projectRootPath: flutterProject?.directory?.absolute?.path,
169
        checkDartPluginRegistry: true,
170
        fs: globals.fs,
171 172 173 174 175 176 177 178 179 180 181
      );
      final String outputPath = compilerOutput?.outputFilename;

      // In case compiler didn't produce output or reported compilation
      // errors, pass [null] upwards to the consumer and shutdown the
      // compiler to avoid reusing compiler that might have gotten into
      // a weird state.
      if (outputPath == null || compilerOutput.errorCount > 0) {
        request.result.complete(null);
        await _shutdown();
      } else {
182 183 184 185 186 187 188 189 190 191 192 193 194
        if (shouldCopyDillFile) {
          final String path = request.mainUri.toFilePath(windows: globals.platform.isWindows);
          final File outputFile = globals.fs.file(outputPath);
          final File kernelReadyToRun = await outputFile.copy('$path.dill');
          final File testCache = globals.fs.file(testFilePath);
          if (firstCompile || !testCache.existsSync() || (testCache.lengthSync() < outputFile.lengthSync())) {
            // The idea is to keep the cache file up-to-date and include as
            // much as possible in an effort to re-use as many packages as
            // possible.
            if (!testCache.parent.existsSync()) {
              testCache.parent.createSync(recursive: true);
            }
            await outputFile.copy(testFilePath);
195
          }
196 197 198
          request.result.complete(kernelReadyToRun.path);
        } else {
          request.result.complete(outputPath);
199 200 201 202
        }
        compiler.accept();
        compiler.reset();
      }
203
      globals.printTrace('Compiling ${request.mainUri} took ${compilerTime.elapsedMilliseconds}ms');
204 205 206 207 208
      // Only remove now when we finished processing the element
      compilationQueue.removeAt(0);
    }
  }
}