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

import 'package:async/async.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:meta/meta.dart';
import 'package:pool/pool.dart';
10
import 'package:process/process.dart';
11

12
import '../artifacts.dart';
13
import '../base/error_handling_io.dart';
14
import '../base/file_system.dart';
15
import '../base/logger.dart';
16
import '../base/platform.dart';
17
import '../base/utils.dart';
18 19
import '../cache.dart';
import '../convert.dart';
20
import '../reporting/reporting.dart';
21
import 'depfile.dart';
22
import 'exceptions.dart';
23
import 'file_store.dart';
24 25 26 27
import 'source.dart';

export 'source.dart';

28 29 30
/// A reasonable amount of files to open at the same time.
///
/// This number is somewhat arbitrary - it is difficult to detect whether
31
/// or not we'll run out of file descriptors when using async dart:io
32 33 34
/// APIs.
const int kMaxOpenFiles = 64;

35 36 37 38 39 40 41 42
/// Configuration for the build system itself.
class BuildSystemConfig {
  /// Create a new [BuildSystemConfig].
  const BuildSystemConfig({this.resourcePoolSize});

  /// The maximum number of concurrent tasks the build system will run.
  ///
  /// If not provided, defaults to [platform.numberOfProcessors].
43
  final int? resourcePoolSize;
44 45 46 47 48 49 50 51
}

/// A Target describes a single step during a flutter build.
///
/// The target inputs are required to be files discoverable via a combination
/// of at least one of the environment values and zero or more local values.
///
/// To determine if the action for a target needs to be executed, the
52 53 54
/// [BuildSystem] computes a key of the file contents for both inputs and
/// outputs. This is tracked separately in the [FileStore]. The key may
/// be either an md5 hash of the file contents or a timestamp.
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
///
/// A Target has both implicit and explicit inputs and outputs. Only the
/// later are safe to evaluate before invoking the [buildAction]. For example,
/// a wildcard output pattern requires the outputs to exist before it can
/// glob files correctly.
///
/// - All listed inputs are considered explicit inputs.
/// - Outputs which are provided as [Source.pattern].
///   without wildcards are considered explicit.
/// - The remaining outputs are considered implicit.
///
/// For each target, executing its action creates a corresponding stamp file
/// which records both the input and output files. This file is read by
/// subsequent builds to determine which file hashes need to be checked. If the
/// stamp file is missing, the target's action is always rerun.
///
///  file: `example_target.stamp`
///
/// {
///   "inputs": [
///      "absolute/path/foo",
///      "absolute/path/bar",
///      ...
///    ],
///    "outputs": [
///      "absolute/path/fizz"
///    ]
/// }
///
/// ## Code review
///
86
/// ### Targets should only depend on files that are provided as inputs
87 88 89 90 91 92 93 94 95
///
/// Example: gen_snapshot must be provided as an input to the aot_elf
/// build steps, even though it isn't a source file. This ensures that changes
/// to the gen_snapshot binary (during a local engine build) correctly
/// trigger a corresponding build update.
///
/// Example: aot_elf has a dependency on the dill and packages file
/// produced by the kernel_snapshot step.
///
96
/// ### Targets should declare all outputs produced
97 98 99 100 101 102 103 104 105 106 107 108 109
///
/// If a target produces an output it should be listed, even if it is not
/// intended to be consumed by another target.
///
/// ## Unit testing
///
/// Most targets will invoke an external binary which makes unit testing
/// trickier. It is recommend that for unit testing that a Fake is used and
/// provided via the dependency injection system. a [Testbed] may be used to
/// set up the environment before the test is run. Unit tests should fully
/// exercise the rule, ensuring that the existing input and output verification
/// logic can run, as well as verifying it correctly handles provided defines
/// and meets any additional contracts present in the target.
110 111
abstract class Target {
  const Target();
112 113 114 115
  /// The user-readable name of the target.
  ///
  /// This information is surfaced in the assemble commands and used as an
  /// argument to build a particular target.
116
  String get name;
117

118 119 120 121 122 123 124 125
  /// A name that measurements can be categorized under for this [Target].
  ///
  /// Unlike [name], this is not expected to be unique, so multiple targets
  /// that are conceptually the same can share an analytics name.
  ///
  /// If not provided, defaults to [name]
  String get analyticsName => name;

126
  /// The dependencies of this target.
127
  List<Target> get dependencies;
128 129

  /// The input [Source]s which are diffed to determine if a target should run.
130
  List<Source> get inputs;
131 132

  /// The output [Source]s which we attempt to verify are correctly produced.
133
  List<Source> get outputs;
134

135 136 137
  /// A list of zero or more depfiles, located directly under {BUILD_DIR}.
  List<String> get depfiles => const <String>[];

138 139 140 141 142 143
  /// Whether this target can be executed with the given [environment].
  ///
  /// Returning `true` will cause [build] to be skipped. This is equivalent
  /// to a build that produces no outputs.
  bool canSkip(Environment environment) => false;

144
  /// The action which performs this build step.
145
  Future<void> build(Environment environment);
146

147 148
  /// Create a [Node] with resolved inputs and outputs.
  Node _toNode(Environment environment) {
149 150
    final ResolvedFiles inputsFiles = resolveInputs(environment);
    final ResolvedFiles outputFiles = resolveOutputs(environment);
151 152
    return Node(
      this,
153 154
      inputsFiles.sources,
      outputFiles.sources,
155
      <Node>[
156
        for (final Target target in dependencies) target._toNode(environment),
157
      ],
158
      environment,
159
      inputsFiles.containsNewDepfile,
160
    );
161 162
  }

163
  /// Invoke to remove the stamp file if the [buildAction] threw an exception.
164 165
  void clearStamp(Environment environment) {
    final File stamp = _findStampFile(environment);
166
    ErrorHandlingFileSystem.deleteIfExists(stamp);
167 168 169 170 171 172 173 174 175
  }

  void _writeStamp(
    List<File> inputs,
    List<File> outputs,
    Environment environment,
  ) {
    final File stamp = _findStampFile(environment);
    final List<String> inputPaths = <String>[];
176
    for (final File input in inputs) {
177
      inputPaths.add(input.path);
178 179
    }
    final List<String> outputPaths = <String>[];
180
    for (final File output in outputs) {
181
      outputPaths.add(output.path);
182 183 184 185 186 187 188 189 190 191 192 193 194
    }
    final Map<String, Object> result = <String, Object>{
      'inputs': inputPaths,
      'outputs': outputPaths,
    };
    if (!stamp.existsSync()) {
      stamp.createSync();
    }
    stamp.writeAsStringSync(json.encode(result));
  }

  /// Resolve the set of input patterns and functions into a concrete list of
  /// files.
195
  ResolvedFiles resolveInputs(Environment environment) {
196
    return _resolveConfiguration(inputs, depfiles, environment);
197 198 199 200 201 202
  }

  /// Find the current set of declared outputs, including wildcard directories.
  ///
  /// The [implicit] flag controls whether it is safe to evaluate [Source]s
  /// which uses functions, behaviors, or patterns.
203
  ResolvedFiles resolveOutputs(Environment environment) {
204
    return _resolveConfiguration(outputs, depfiles, environment, inputs: false);
205 206 207
  }

  /// Performs a fold across this target and its dependencies.
208
  T fold<T>(T initialValue, T Function(T previousValue, Target target) combine) {
209 210 211 212 213 214 215 216 217 218 219 220 221
    final T dependencyResult = dependencies.fold(
        initialValue, (T prev, Target t) => t.fold(prev, combine));
    return combine(dependencyResult, this);
  }

  /// Convert the target to a JSON structure appropriate for consumption by
  /// external systems.
  ///
  /// This requires constants from the [Environment] to resolve the paths of
  /// inputs and the output stamp.
  Map<String, Object> toJson(Environment environment) {
    return <String, Object>{
      'name': name,
222
      'dependencies': <String>[
223
        for (final Target target in dependencies) target.name,
224 225
      ],
      'inputs': <String>[
226
        for (final File file in resolveInputs(environment).sources) file.path,
227 228
      ],
      'outputs': <String>[
229
        for (final File file in resolveOutputs(environment).sources) file.path,
230
      ],
231 232 233 234 235 236 237 238 239 240
      'stamp': _findStampFile(environment).absolute.path,
    };
  }

  /// Locate the stamp file for a particular target name and environment.
  File _findStampFile(Environment environment) {
    final String fileName = '$name.stamp';
    return environment.buildDir.childFile(fileName);
  }

241 242 243 244 245
  static ResolvedFiles _resolveConfiguration(
    List<Source> config,
    List<String> depfiles,
    Environment environment, {
    bool inputs = true,
246
  }) {
247
    final SourceVisitor collector = SourceVisitor(environment, inputs);
248
    for (final Source source in config) {
249 250
      source.accept(collector);
    }
251
    depfiles.forEach(collector.visitDepfile);
252
    return collector;
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
/// Target that contains multiple other targets.
///
/// This target does not do anything in its own [build]
/// and acts as a wrapper around multiple other targets.
class CompositeTarget extends Target {
  CompositeTarget(this.dependencies);

  @override
  final List<Target> dependencies;

  @override
  String get name => '_composite';

  @override
  Future<void> build(Environment environment) async { }

  @override
  List<Source> get inputs => <Source>[];

  @override
  List<Source> get outputs => <Source>[];
}

279 280 281 282 283 284 285 286 287
/// The [Environment] defines several constants for use during the build.
///
/// The environment contains configuration and file paths that are safe to
/// depend on and reference during the build.
///
/// Example (Good):
///
/// Use the environment to determine where to write an output file.
///
288
/// ```dart
289 290 291
///    environment.buildDir.childFile('output')
///      ..createSync()
///      ..writeAsStringSync('output data');
292
/// ```
293 294 295 296 297 298
///
/// Example (Bad):
///
/// Use a hard-coded path or directory relative to the current working
/// directory to write an output file.
///
299
/// ```dart
300
///   globals.fs.file('build/linux/out')
301 302
///     ..createSync()
///     ..writeAsStringSync('output data');
303
/// ```
304 305 306
///
/// Example (Good):
///
307
/// Using the build mode to produce different output. The action
308 309 310
/// is still responsible for outputting a different file, as defined by the
/// corresponding output [Source].
///
311
/// ```dart
312 313 314 315 316 317 318 319 320 321
///    final BuildMode buildMode = getBuildModeFromDefines(environment.defines);
///    if (buildMode == BuildMode.debug) {
///      environment.buildDir.childFile('debug.output')
///        ..createSync()
///        ..writeAsStringSync('debug');
///    } else {
///      environment.buildDir.childFile('non_debug.output')
///        ..createSync()
///        ..writeAsStringSync('non_debug');
///    }
322
/// ```
323 324
class Environment {
  /// Create a new [Environment] object.
325 326
  ///
  /// [engineVersion] should be set to null for local engine builds.
327
  factory Environment({
328 329 330 331 332 333 334 335 336
    required Directory projectDir,
    required Directory outputDir,
    required Directory cacheDir,
    required Directory flutterRootDir,
    required FileSystem fileSystem,
    required Logger logger,
    required Artifacts artifacts,
    required ProcessManager processManager,
    required Platform platform,
337
    required Usage usage,
338 339 340
    String? engineVersion,
    required bool generateDartPluginRegistry,
    Directory? buildDir,
341
    Map<String, String> defines = const <String, String>{},
342
    Map<String, String> inputs = const <String, String>{},
343 344 345 346 347 348 349
  }) {
    // Compute a unique hash of this build's particular environment.
    // Sort the keys by key so that the result is stable. We always
    // include the engine and dart versions.
    String buildPrefix;
    final List<String> keys = defines.keys.toList()..sort();
    final StringBuffer buffer = StringBuffer();
350 351 352 353
    // The engine revision is `null` for local or custom engines.
    if (engineVersion != null) {
      buffer.write(engineVersion);
    }
354
    for (final String key in keys) {
355 356 357
      buffer.write(key);
      buffer.write(defines[key]);
    }
358
    buffer.write(outputDir.path);
359 360 361 362 363 364 365
    final String output = buffer.toString();
    final Digest digest = md5.convert(utf8.encode(output));
    buildPrefix = hex.encode(digest.bytes);

    final Directory rootBuildDir = buildDir ?? projectDir.childDirectory('build');
    final Directory buildDirectory = rootBuildDir.childDirectory(buildPrefix);
    return Environment._(
366
      outputDir: outputDir,
367 368 369
      projectDir: projectDir,
      buildDir: buildDirectory,
      rootBuildDir: rootBuildDir,
370 371 372
      cacheDir: cacheDir,
      defines: defines,
      flutterRootDir: flutterRootDir,
373 374 375 376
      fileSystem: fileSystem,
      logger: logger,
      artifacts: artifacts,
      processManager: processManager,
377
      platform: platform,
378
      usage: usage,
379
      engineVersion: engineVersion,
380
      inputs: inputs,
381
      generateDartPluginRegistry: generateDartPluginRegistry,
382 383 384 385 386 387
    );
  }

  /// Create a new [Environment] object for unit testing.
  ///
  /// Any directories not provided will fallback to a [testDirectory]
388
  @visibleForTesting
389
  factory Environment.test(Directory testDirectory, {
390 391 392 393 394
    Directory? projectDir,
    Directory? outputDir,
    Directory? cacheDir,
    Directory? flutterRootDir,
    Directory? buildDir,
395
    Map<String, String> defines = const <String, String>{},
396
    Map<String, String> inputs = const <String, String>{},
397 398
    String? engineVersion,
    Platform? platform,
399
    Usage? usage,
400
    bool generateDartPluginRegistry = false,
401 402 403 404
    required FileSystem fileSystem,
    required Logger logger,
    required Artifacts artifacts,
    required ProcessManager processManager,
405 406 407 408 409 410 411
  }) {
    return Environment(
      projectDir: projectDir ?? testDirectory,
      outputDir: outputDir ?? testDirectory,
      cacheDir: cacheDir ?? testDirectory,
      flutterRootDir: flutterRootDir ?? testDirectory,
      buildDir: buildDir,
412
      defines: defines,
413
      inputs: inputs,
414 415 416 417
      fileSystem: fileSystem,
      logger: logger,
      artifacts: artifacts,
      processManager: processManager,
418
      platform: platform ?? FakePlatform(),
419
      usage: usage ?? TestUsage(),
420
      engineVersion: engineVersion,
421
      generateDartPluginRegistry: generateDartPluginRegistry,
422 423 424 425
    );
  }

  Environment._({
426 427 428 429 430 431 432 433 434 435 436 437
    required this.outputDir,
    required this.projectDir,
    required this.buildDir,
    required this.rootBuildDir,
    required this.cacheDir,
    required this.defines,
    required this.flutterRootDir,
    required this.processManager,
    required this.platform,
    required this.logger,
    required this.fileSystem,
    required this.artifacts,
438
    required this.usage,
439 440 441
    this.engineVersion,
    required this.inputs,
    required this.generateDartPluginRegistry,
442 443 444 445 446 447 448 449 450 451 452 453 454 455
  });

  /// The [Source] value which is substituted with the path to [projectDir].
  static const String kProjectDirectory = '{PROJECT_DIR}';

  /// The [Source] value which is substituted with the path to [buildDir].
  static const String kBuildDirectory = '{BUILD_DIR}';

  /// The [Source] value which is substituted with the path to [cacheDir].
  static const String kCacheDirectory = '{CACHE_DIR}';

  /// The [Source] value which is substituted with a path to the flutter root.
  static const String kFlutterRootDirectory = '{FLUTTER_ROOT}';

456 457 458
  /// The [Source] value which is substituted with a path to [outputDir].
  static const String kOutputDirectory = '{OUTPUT_DIR}';

459 460 461 462 463 464 465 466
  /// The `PROJECT_DIR` environment variable.
  ///
  /// This should be root of the flutter project where a pubspec and dart files
  /// can be located.
  final Directory projectDir;

  /// The `BUILD_DIR` environment variable.
  ///
467 468 469 470 471
  /// The root of the output directory where build step intermediates and
  /// outputs are written. Current usages of assemble configure ths to be
  /// a unique directory under `.dart_tool/flutter_build`, though it can
  /// be placed anywhere. The uniqueness is only enforced by callers, and
  /// is currently done by hashing the build configuration.
472 473 474 475 476 477 478 479
  final Directory buildDir;

  /// The `CACHE_DIR` environment variable.
  ///
  /// Defaults to `{FLUTTER_ROOT}/bin/cache`. The root of the artifact cache for
  /// the flutter tool.
  final Directory cacheDir;

480 481
  /// The `FLUTTER_ROOT` environment variable.
  ///
482
  /// Defaults to the value of [Cache.flutterRoot].
483 484
  final Directory flutterRootDir;

485 486 487 488 489
  /// The `OUTPUT_DIR` environment variable.
  ///
  /// Must be provided to configure the output location for the final artifacts.
  final Directory outputDir;

490 491 492 493 494 495
  /// Additional configuration passed to the build targets.
  ///
  /// Setting values here forces a unique build directory to be chosen
  /// which prevents the config from leaking into different builds.
  final Map<String, String> defines;

496 497 498 499 500 501 502 503 504 505
  /// Additional input files passed to the build targets.
  ///
  /// Unlike [defines], values set here do not force a new build configuration.
  /// This is useful for passing file inputs that may have changing paths
  /// without running builds from scratch.
  ///
  /// It is the responsibility of the [Target] to declare that an input was
  /// used in an output depfile.
  final Map<String, String> inputs;

506 507
  /// The root build directory shared by all builds.
  final Directory rootBuildDir;
508 509 510

  final ProcessManager processManager;

511 512
  final Platform platform;

513 514 515 516 517
  final Logger logger;

  final Artifacts artifacts;

  final FileSystem fileSystem;
518

519 520
  final Usage usage;

521
  /// The version of the current engine, or `null` if built with a local engine.
522
  final String? engineVersion;
523 524 525 526 527

  /// Whether to generate the Dart plugin registry.
  /// When [true], the main entrypoint is wrapped and the wrapper becomes
  /// the new entrypoint.
  final bool generateDartPluginRegistry;
528 529 530 531 532

  late final DepfileService depFileService = DepfileService(
    logger: logger,
    fileSystem: fileSystem,
  );
533 534 535 536
}

/// The result information from the build system.
class BuildResult {
537
  BuildResult({
538
    required this.success,
539 540 541 542 543
    this.exceptions = const <String, ExceptionMeasurement>{},
    this.performance = const <String, PerformanceMeasurement>{},
    this.inputFiles = const <File>[],
    this.outputFiles = const <File>[],
  });
544 545 546 547

  final bool success;
  final Map<String, ExceptionMeasurement> exceptions;
  final Map<String, PerformanceMeasurement> performance;
548 549
  final List<File> inputFiles;
  final List<File> outputFiles;
550 551 552 553 554

  bool get hasException => exceptions.isNotEmpty;
}

/// The build system is responsible for invoking and ordering [Target]s.
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
abstract class BuildSystem {
  /// Const constructor to allow subclasses to be const.
  const BuildSystem();

  /// Build [target] and all of its dependencies.
  Future<BuildResult> build(
    Target target,
    Environment environment, {
    BuildSystemConfig buildSystemConfig = const BuildSystemConfig(),
  });

  /// Perform an incremental build of [target] and all of its dependencies.
  ///
  /// If [previousBuild] is not provided, a new incremental build is
  /// initialized.
  Future<BuildResult> buildIncremental(
    Target target,
    Environment environment,
573
    BuildResult? previousBuild,
574 575 576 577 578
  );
}

class FlutterBuildSystem extends BuildSystem {
  const FlutterBuildSystem({
579 580 581
    required FileSystem fileSystem,
    required Platform platform,
    required Logger logger,
582 583 584 585 586 587 588
  }) : _fileSystem = fileSystem,
       _platform = platform,
       _logger = logger;

  final FileSystem _fileSystem;
  final Platform _platform;
  final Logger _logger;
589

590
  @override
591
  Future<BuildResult> build(
592
    Target target,
593 594 595
    Environment environment, {
    BuildSystemConfig buildSystemConfig = const BuildSystemConfig(),
  }) async {
596
    environment.buildDir.createSync(recursive: true);
597
    environment.outputDir.createSync(recursive: true);
598

599 600 601 602
    // Load file store from previous builds.
    final File cacheFile = environment.buildDir.childFile(FileStore.kFileCache);
    final FileStore fileCache = FileStore(
      cacheFile: cacheFile,
603
      logger: _logger,
604
    )..initialize();
605 606 607 608

    // Perform sanity checks on build.
    checkCycles(target);

609
    final Node node = target._toNode(environment);
610 611 612 613 614 615 616 617
    final _BuildInstance buildInstance = _BuildInstance(
      environment: environment,
      fileCache: fileCache,
      buildSystemConfig: buildSystemConfig,
      logger: _logger,
      fileSystem: _fileSystem,
      platform: _platform,
    );
618 619
    bool passed = true;
    try {
620
      passed = await buildInstance.invokeTarget(node);
621 622 623 624
    } finally {
      // Always persist the file cache to disk.
      fileCache.persist();
    }
625
    // This is a bit of a hack, due to various parts of
626
    // the flutter tool writing these files unconditionally. Since Xcode uses
627
    // timestamps to track files, this leads to unnecessary rebuilds if they
628 629
    // are included. Once all the places that write these files have been
    // tracked down and moved into assemble, these checks should be removable.
630 631
    // We also remove files under .dart_tool, since these are intermediaries
    // and don't need to be tracked by external systems.
632 633
    {
      buildInstance.inputFiles.removeWhere((String path, File file) {
634 635 636
        return path.contains('.flutter-plugins') ||
                       path.contains('xcconfig') ||
                     path.contains('.dart_tool');
637 638
      });
      buildInstance.outputFiles.removeWhere((String path, File file) {
639 640 641
        return path.contains('.flutter-plugins') ||
                       path.contains('xcconfig') ||
                     path.contains('.dart_tool');
642 643
      });
    }
644 645 646 647 648 649
    trackSharedBuildDirectory(
      environment, _fileSystem, buildInstance.outputFiles,
    );
    environment.buildDir.childFile('outputs.json')
      .writeAsStringSync(json.encode(buildInstance.outputFiles.keys.toList()));

650
    return BuildResult(
651 652 653 654 655 656 657
      success: passed,
      exceptions: buildInstance.exceptionMeasurements,
      performance: buildInstance.stepTimings,
      inputFiles: buildInstance.inputFiles.values.toList()
          ..sort((File a, File b) => a.path.compareTo(b.path)),
      outputFiles: buildInstance.outputFiles.values.toList()
          ..sort((File a, File b) => a.path.compareTo(b.path)),
658 659
    );
  }
660

661 662
  static final Expando<FileStore> _incrementalFileStore = Expando<FileStore>();

663
  @override
664 665 666
  Future<BuildResult> buildIncremental(
    Target target,
    Environment environment,
667
    BuildResult? previousBuild,
668 669 670 671
  ) async {
    environment.buildDir.createSync(recursive: true);
    environment.outputDir.createSync(recursive: true);

672
    FileStore? fileCache;
673 674 675 676 677 678 679 680 681 682 683 684 685
    if (previousBuild == null || _incrementalFileStore[previousBuild] == null) {
      final File cacheFile = environment.buildDir.childFile(FileStore.kFileCache);
      fileCache = FileStore(
        cacheFile: cacheFile,
        logger: _logger,
        strategy: FileStoreStrategy.timestamp,
      )..initialize();
    } else {
      fileCache = _incrementalFileStore[previousBuild];
    }
    final Node node = target._toNode(environment);
    final _BuildInstance buildInstance = _BuildInstance(
      environment: environment,
686
      fileCache: fileCache!,
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
      buildSystemConfig: const BuildSystemConfig(),
      logger: _logger,
      fileSystem: _fileSystem,
      platform: _platform,
    );
    bool passed = true;
    try {
      passed = await buildInstance.invokeTarget(node);
    } finally {
      fileCache.persistIncremental();
    }
    final BuildResult result = BuildResult(
      success: passed,
      exceptions: buildInstance.exceptionMeasurements,
      performance: buildInstance.stepTimings,
    );
    _incrementalFileStore[result] = fileCache;
    return result;
  }

707 708 709 710 711 712 713 714 715 716 717 718
  /// Write the identifier of the last build into the output directory and
  /// remove the previous build's output.
  ///
  /// The build identifier is the basename of the build directory where
  /// outputs and intermediaries are written, under `.dart_tool/flutter_build`.
  /// This is computed from a hash of the build's configuration.
  ///
  /// This identifier is used to perform a targeted cleanup of the last output
  /// files, if these were not already covered by the built-in cleanup. This
  /// cleanup is only necessary when multiple different build configurations
  /// output to the same directory.
  @visibleForTesting
719
  void trackSharedBuildDirectory(
720 721 722 723 724 725 726
    Environment environment,
    FileSystem fileSystem,
    Map<String, File> currentOutputs,
  ) {
    final String currentBuildId = fileSystem.path.basename(environment.buildDir.path);
    final File lastBuildIdFile = environment.outputDir.childFile('.last_build_id');
    if (!lastBuildIdFile.existsSync()) {
727
      lastBuildIdFile.parent.createSync(recursive: true);
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
      lastBuildIdFile.writeAsStringSync(currentBuildId);
      // No config file, either output was cleaned or this is the first build.
      return;
    }
    final String lastBuildId = lastBuildIdFile.readAsStringSync().trim();
    if (lastBuildId == currentBuildId) {
      // The last build was the same configuration as the current build
      return;
    }
    // Update the output dir with the latest config.
    lastBuildIdFile
      ..createSync()
      ..writeAsStringSync(currentBuildId);
    final File outputsFile = environment.buildDir
      .parent
      .childDirectory(lastBuildId)
      .childFile('outputs.json');

    if (!outputsFile.existsSync()) {
      // There is no output list. This could happen if the user manually
      // edited .last_config or deleted .dart_tool.
      return;
    }
751
    final List<String> lastOutputs = (json.decode(outputsFile.readAsStringSync()) as List<Object?>)
752 753 754 755
      .cast<String>();
    for (final String lastOutput in lastOutputs) {
      if (!currentOutputs.containsKey(lastOutput)) {
        final File lastOutputFile = fileSystem.file(lastOutput);
756
        ErrorHandlingFileSystem.deleteIfExists(lastOutputFile);
757 758 759
      }
    }
  }
760 761 762 763
}

/// An active instance of a build.
class _BuildInstance {
764
  _BuildInstance({
765 766 767 768 769 770
    required this.environment,
    required this.fileCache,
    required this.buildSystemConfig,
    required this.logger,
    required this.fileSystem,
    Platform? platform,
771 772 773 774 775
  })
    : resourcePool = Pool(buildSystemConfig.resourcePoolSize ?? platform?.numberOfProcessors ?? 1);

  final Logger logger;
  final FileSystem fileSystem;
776 777
  final BuildSystemConfig buildSystemConfig;
  final Pool resourcePool;
778
  final Map<String, AsyncMemoizer<bool>> pending = <String, AsyncMemoizer<bool>>{};
779
  final Environment environment;
780
  final FileStore fileCache;
781 782
  final Map<String, File> inputFiles = <String, File>{};
  final Map<String, File> outputFiles = <String, File>{};
783 784 785 786 787 788 789

  // Timings collected during target invocation.
  final Map<String, PerformanceMeasurement> stepTimings = <String, PerformanceMeasurement>{};

  // Exceptions caught during the build process.
  final Map<String, ExceptionMeasurement> exceptionMeasurements = <String, ExceptionMeasurement>{};

790 791
  Future<bool> invokeTarget(Node node) async {
    final List<bool> results = await Future.wait(node.dependencies.map(invokeTarget));
792 793 794
    if (results.any((bool result) => !result)) {
      return false;
    }
795 796
    final AsyncMemoizer<bool> memoizer = pending[node.target.name] ??= AsyncMemoizer<bool>();
    return memoizer.runOnce(() => _invokeInternal(node));
797 798
  }

799
  Future<bool> _invokeInternal(Node node) async {
800 801
    final PoolResource resource = await resourcePool.request();
    final Stopwatch stopwatch = Stopwatch()..start();
802
    bool succeeded = true;
803
    bool skipped = false;
804 805 806 807 808 809 810 811 812 813 814 815

    // The build system produces a list of aggregate input and output
    // files for the overall build. This list is provided to a hosting build
    // system, such as Xcode, to configure logic for when to skip the
    // rule/phase which contains the flutter build.
    //
    // When looking at the inputs and outputs for the individual rules, we need
    // to be careful to remove inputs that were actually output from previous
    // build steps. This indicates that the file is an intermediary. If
    // these files are included as both inputs and outputs then it isn't
    // possible to construct a DAG describing the build.
    void updateGraph() {
816
      for (final File output in node.outputs) {
817 818
        outputFiles[output.path] = output;
      }
819
      for (final File input in node.inputs) {
820
        final String resolvedPath = input.absolute.path;
821 822 823 824 825
        if (outputFiles.containsKey(resolvedPath)) {
          continue;
        }
        inputFiles[resolvedPath] = input;
      }
826 827 828 829 830 831
    }

    try {
      // If we're missing a depfile, wait until after evaluating the target to
      // compute changes.
      final bool canSkip = !node.missingDepfile &&
832
        node.computeChanges(environment, fileCache, fileSystem, logger);
833

834
      if (canSkip) {
835
        skipped = true;
836
        logger.printTrace('Skipping target: ${node.target.name}');
837
        updateGraph();
838
        return succeeded;
839
      }
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
      // Clear old inputs. These will be replaced with new inputs/outputs
      // after the target is run. In the case of a runtime skip, each list
      // must be empty to ensure the previous outputs are purged.
      node.inputs.clear();
      node.outputs.clear();

      // Check if we can skip via runtime dependencies.
      final bool runtimeSkip = node.target.canSkip(environment);
      if (runtimeSkip) {
        logger.printTrace('Skipping target: ${node.target.name}');
        skipped = true;
      } else {
        logger.printTrace('${node.target.name}: Starting due to ${node.invalidatedReasons}');
        await node.target.build(environment);
        logger.printTrace('${node.target.name}: Complete');
        node.inputs.addAll(node.target.resolveInputs(environment).sources);
        node.outputs.addAll(node.target.resolveOutputs(environment).sources);
      }

      // If we were missing the depfile, resolve input files after executing the
860 861
      // target so that all file hashes are up to date on the next run.
      if (node.missingDepfile) {
862
        fileCache.diffFileList(node.inputs);
863 864
      }

865
      // Always update hashes for output files.
866
      fileCache.diffFileList(node.outputs);
867 868 869 870 871
      node.target._writeStamp(node.inputs, node.outputs, environment);
      updateGraph();

      // Delete outputs from previous stages that are no longer a part of the
      // build.
872
      for (final String previousOutput in node.previousOutputs) {
873 874
        if (outputFiles.containsKey(previousOutput)) {
          continue;
875
        }
876
        final File previousFile = fileSystem.file(previousOutput);
877
        ErrorHandlingFileSystem.deleteIfExists(previousFile);
878
      }
879
    } on Exception catch (exception, stackTrace) {
880
      node.target.clearStamp(environment);
881
      succeeded = false;
882
      skipped = false;
883
      exceptionMeasurements[node.target.name] = ExceptionMeasurement(
884
          node.target.name, exception, stackTrace, fatal: true);
885 886 887
    } finally {
      resource.release();
      stopwatch.stop();
888
      stepTimings[node.target.name] = PerformanceMeasurement(
889 890 891
        target: node.target.name,
        elapsedMilliseconds: stopwatch.elapsedMilliseconds,
        skipped: skipped,
892
        succeeded: succeeded,
893
        analyticsName: node.target.analyticsName,
894
      );
895
    }
896
    return succeeded;
897 898 899 900 901
  }
}

/// Helper class to collect exceptions.
class ExceptionMeasurement {
902
  ExceptionMeasurement(this.target, this.exception, this.stackTrace, {this.fatal = false});
903 904

  final String target;
905
  final Object? exception;
906
  final StackTrace stackTrace;
907

908 909 910
  /// Whether this exception was a fatal build system error.
  final bool fatal;

911 912
  @override
  String toString() => 'target: $target\nexception:$exception\n$stackTrace';
913 914 915 916
}

/// Helper class to collect measurement data.
class PerformanceMeasurement {
917
  PerformanceMeasurement({
918 919 920 921 922
    required this.target,
    required this.elapsedMilliseconds,
    required this.skipped,
    required this.succeeded,
    required this.analyticsName,
923 924
  });

925 926
  final int elapsedMilliseconds;
  final String target;
927
  final bool skipped;
928
  final bool succeeded;
929
  final String analyticsName;
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
}

/// Check if there are any dependency cycles in the target.
///
/// Throws a [CycleException] if one is encountered.
void checkCycles(Target initial) {
  void checkInternal(Target target, Set<Target> visited, Set<Target> stack) {
    if (stack.contains(target)) {
      throw CycleException(stack..add(target));
    }
    if (visited.contains(target)) {
      return;
    }
    visited.add(target);
    stack.add(target);
945
    for (final Target dependency in target.dependencies) {
946 947 948 949 950 951 952 953 954 955 956 957
      checkInternal(dependency, visited, stack);
    }
    stack.remove(target);
  }
  checkInternal(initial, <Target>{}, <Target>{});
}

/// Verifies that all files exist and are in a subdirectory of [Environment.buildDir].
void verifyOutputDirectories(List<File> outputs, Environment environment, Target target) {
  final String buildDirectory = environment.buildDir.resolveSymbolicLinksSync();
  final String projectDirectory = environment.projectDir.resolveSymbolicLinksSync();
  final List<File> missingOutputs = <File>[];
958
  for (final File sourceFile in outputs) {
959 960 961 962
    if (!sourceFile.existsSync()) {
      missingOutputs.add(sourceFile);
      continue;
    }
963
    final String path = sourceFile.path;
964 965 966 967 968 969 970 971
    if (!path.startsWith(buildDirectory) && !path.startsWith(projectDirectory)) {
      throw MisplacedOutputException(path, target.name);
    }
  }
  if (missingOutputs.isNotEmpty) {
    throw MissingOutputException(missingOutputs, target.name);
  }
}
972 973 974

/// A node in the build graph.
class Node {
975 976 977 978 979 980 981 982
  Node(
    this.target,
    this.inputs,
    this.outputs,
    this.dependencies,
    Environment environment,
    this.missingDepfile,
  ) {
983 984 985 986 987 988 989 990 991 992 993
    final File stamp = target._findStampFile(environment);

    // If the stamp file doesn't exist, we haven't run this step before and
    // all inputs were added.
    if (!stamp.existsSync()) {
      // No stamp file, not safe to skip.
      _dirty = true;
      return;
    }
    final String content = stamp.readAsStringSync();
    // Something went wrong writing the stamp file.
994
    if (content.isEmpty) {
995 996 997 998 999
      stamp.deleteSync();
      // Malformed stamp file, not safe to skip.
      _dirty = true;
      return;
    }
1000
    Map<String, Object?>? values;
1001
    try {
1002
      values = castStringKeyedMap(json.decode(content));
1003 1004 1005 1006 1007
    } on FormatException {
      // The json is malformed in some way.
      _dirty = true;
      return;
    }
1008 1009 1010 1011 1012
    final Object? inputs = values?['inputs'];
    final Object? outputs = values?['outputs'];
    if (inputs is List<Object?> && outputs is List<Object?>) {
      inputs.cast<String?>().whereType<String>().forEach(previousInputs.add);
      outputs.cast<String?>().whereType<String>().forEach(previousOutputs.add);
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    } else {
      // The json is malformed in some way.
      _dirty = true;
    }
  }

  /// The resolved input files.
  ///
  /// These files may not yet exist if they are produced by previous steps.
  final List<File> inputs;

  /// The resolved output files.
  ///
  /// These files may not yet exist if the target hasn't run yet.
  final List<File> outputs;

1029 1030 1031 1032 1033 1034
  /// Whether this node is missing a depfile.
  ///
  /// This requires an additional pass of source resolution after the target
  /// has been executed.
  final bool missingDepfile;

1035 1036 1037 1038 1039 1040 1041 1042 1043
  /// The target definition which contains the build action to invoke.
  final Target target;

  /// All of the nodes that this one depends on.
  final List<Node> dependencies;

  /// Output file paths from the previous invocation of this build node.
  final Set<String> previousOutputs = <String>{};

1044
  /// Input file paths from the previous invocation of this build node.
1045 1046
  final Set<String> previousInputs = <String>{};

1047 1048 1049
  /// One or more reasons why a task was invalidated.
  ///
  /// May be empty if the task was skipped.
1050
  final Map<InvalidatedReasonKind, InvalidatedReason> invalidatedReasons = <InvalidatedReasonKind, InvalidatedReason>{};
1051

1052 1053 1054 1055
  /// Whether this node needs an action performed.
  bool get dirty => _dirty;
  bool _dirty = false;

1056 1057 1058 1059
  InvalidatedReason _invalidate(InvalidatedReasonKind kind) {
    return invalidatedReasons[kind] ??= InvalidatedReason(kind);
  }

1060 1061 1062
  /// Collect hashes for all inputs to determine if any have changed.
  ///
  /// Returns whether this target can be skipped.
1063
  bool computeChanges(
1064
    Environment environment,
1065
    FileStore fileStore,
1066 1067
    FileSystem fileSystem,
    Logger logger,
1068
  ) {
1069
    final Set<String> currentOutputPaths = <String>{
1070
      for (final File file in outputs) file.path,
1071
    };
1072 1073 1074
    // For each input, first determine if we've already computed the key
    // for it. Then collect it to be sent off for diffing as a group.
    final List<File> sourcesToDiff = <File>[];
1075
    final List<File> missingInputs = <File>[];
1076
    for (final File file in inputs) {
1077 1078 1079 1080 1081 1082
      if (!file.existsSync()) {
        missingInputs.add(file);
        continue;
      }

      final String absolutePath = file.path;
1083
      final String? previousAssetKey = fileStore.previousAssetKeys[absolutePath];
1084
      if (fileStore.currentAssetKeys.containsKey(absolutePath)) {
1085
        final String? currentHash = fileStore.currentAssetKeys[absolutePath];
1086
        if (currentHash != previousAssetKey) {
1087 1088
          final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.inputChanged);
          reason.data.add(absolutePath);
1089 1090 1091
          _dirty = true;
        }
      } else {
1092
        sourcesToDiff.add(file);
1093 1094 1095
      }
    }

1096
    // For each output, first determine if we've already computed the key
1097
    // for it. Then collect it to be sent off for hashing as a group.
1098
    for (final String previousOutput in previousOutputs) {
1099 1100 1101
      // output paths changed.
      if (!currentOutputPaths.contains(previousOutput)) {
        _dirty = true;
1102 1103
        final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.outputSetChanged);
        reason.data.add(previousOutput);
1104
        // if this isn't a current output file there is no reason to compute the key.
1105 1106
        continue;
      }
1107
      final File file = fileSystem.file(previousOutput);
1108
      if (!file.existsSync()) {
1109 1110
        final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.outputMissing);
        reason.data.add(file.path);
1111 1112 1113 1114
        _dirty = true;
        continue;
      }
      final String absolutePath = file.path;
1115
      final String? previousHash = fileStore.previousAssetKeys[absolutePath];
1116
      if (fileStore.currentAssetKeys.containsKey(absolutePath)) {
1117
        final String? currentHash = fileStore.currentAssetKeys[absolutePath];
1118
        if (currentHash != previousHash) {
1119 1120
          final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.outputChanged);
          reason.data.add(absolutePath);
1121 1122 1123
          _dirty = true;
        }
      } else {
1124
        sourcesToDiff.add(file);
1125 1126 1127
      }
    }

1128
    // If we depend on a file that doesn't exist on disk, mark the build as
1129 1130
    // dirty. if the rule is not correctly specified, this will result in it
    // always being rerun.
1131
    if (missingInputs.isNotEmpty) {
1132 1133
      _dirty = true;
      final String missingMessage = missingInputs.map((File file) => file.path).join(', ');
1134
      logger.printTrace('invalidated build due to missing files: $missingMessage');
1135 1136
      final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.inputMissing);
      reason.data.addAll(missingInputs.map((File file) => file.path));
1137 1138
    }

1139
    // If we have files to diff, compute them asynchronously and then
1140
    // update the result.
1141
    if (sourcesToDiff.isNotEmpty) {
1142
      final List<File> dirty = fileStore.diffFileList(sourcesToDiff);
1143
      if (dirty.isNotEmpty) {
1144 1145
        final InvalidatedReason reason = _invalidate(InvalidatedReasonKind.inputChanged);
        reason.data.addAll(dirty.map((File file) => file.path));
1146 1147 1148 1149 1150 1151
        _dirty = true;
      }
    }
    return !_dirty;
  }
}
1152

1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
/// Data about why a target was re-run.
class InvalidatedReason {
  InvalidatedReason(this.kind);

  final InvalidatedReasonKind kind;
  /// Absolute file paths of inputs or outputs, depending on [kind].
  final List<String> data = <String>[];

  @override
  String toString() {
1163 1164 1165 1166 1167 1168 1169
    return switch (kind) {
      InvalidatedReasonKind.inputMissing => 'The following inputs were missing: ${data.join(',')}',
      InvalidatedReasonKind.inputChanged => 'The following inputs have updated contents: ${data.join(',')}',
      InvalidatedReasonKind.outputChanged => 'The following outputs have updated contents: ${data.join(',')}',
      InvalidatedReasonKind.outputMissing => 'The following outputs were missing: ${data.join(',')}',
      InvalidatedReasonKind.outputSetChanged => 'The following outputs were removed from the output set: ${data.join(',')}'
    };
1170 1171 1172
  }
}

1173
/// A description of why a target was rerun.
1174
enum InvalidatedReasonKind {
1175 1176 1177 1178
  /// An input file that was expected is missing. This can occur when using
  /// depfile dependencies, or if a target is incorrectly specified.
  inputMissing,

1179
  /// An input file has an updated key.
1180 1181
  inputChanged,

1182
  /// An output file has an updated key.
1183 1184 1185 1186 1187 1188 1189 1190
  outputChanged,

  /// An output file that is expected is missing.
  outputMissing,

  /// The set of expected output files changed.
  outputSetChanged,
}