generateCode method

Future<int> generateCode()

Runs code generation for every package that has build_runner.

Returns the number of packages the generation was run for, 0 if there is nothing to generate.

Throws RunException if the generation has failed.

Implementation

Future<int> generateCode() async {
  final rootDirPath = p.current;
  printVerbose('Current directory: $rootDirPath');
  printVerbose('Search for pubspec with $_buildRunner dependency');

  final targets = await _findTargets();
  printVerbose('Found ${targets.length} target(s)');

  if (targets.isEmpty) return 0;

  try {
    for (final target in targets) {
      final relativePath = p.relative(target.pubspec.path, from: rootDirPath);
      printInfo('Generating code for $relativePath'
          '${target.useWorkspace ? ' (workspace)' : ''}');

      setCurrentDir(target.pubspec.parent.path);
      printVerbose('Current directory: ${Directory.current.path}');

      await flutter.runPubOrFail(
        'build_runner',
        [
          'build',
          '--delete-conflicting-outputs',
          if (target.useWorkspace) '--workspace',
        ],
        // Deps are already resolved while gating workspace generation,
        // so avoid a redundant pub get here.
        prependWithPubGet: !target.depsResolved,
        title: 'Running code generation',
      );

      printInfo('Generation for $relativePath - DONE');
    }
  } finally {
    // Generation is run in the directory of a target package,
    // so the caller gets the directory it started in back.
    setCurrentDir(rootDirPath);
  }

  return targets.length;
}