ensureUpToDate function

void ensureUpToDate(
  1. String path,
  2. String commandToRun, {
  3. Iterable<String?>? dependencies,
})

Ensures that path (usually a compilation artifact) has been modified more recently than all this package's source files.

By default, this checks files in the lib/ directory as well as pubspec.lock. Additional files or directories to check can be passed in dependencies.

If path doesn't exist or is out of date, throws a TestFailure encouraging the user to run commandToRun.

Implementation

void ensureUpToDate(String path, String commandToRun,
    {Iterable<String?>? dependencies}) {
  // Ensure path is relative so the error messages are more readable.
  path = p.relative(path);
  if (!File(path).existsSync()) {
    throw TestFailure("$path does not exist. Run $commandToRun.");
  }

  var entriesToCheck = [
    for (var dependency in [...?dependencies, "lib"])
      if (Directory(dependency!).existsSync())
        ...Directory(dependency).listSync(recursive: true)
      else if (File(dependency).existsSync())
        File(dependency),
    _hasPathDependency ? File("pubspec.yaml") : File("pubspec.lock")
  ];

  var lastModified = File(path).lastModifiedSync();
  for (var entry in entriesToCheck) {
    if (entry is File) {
      var entryLastModified = entry.lastModifiedSync();
      if (lastModified.isBefore(entryLastModified)) {
        throw TestFailure(
            "${entry.path} was modified after ${p.prettyUri(p.toUri(path))} "
            "was generated.\n"
            "Run $commandToRun.");
      }
    }
  }
}