run method

  1. @override
Future<int> run()
override

Runs this command.

The return value is wrapped in a Future if necessary and returned by CommandRunner.runCommand.

Implementation

@override
Future<int> run() async {
  if (!isProjectMode) {
    stderr.writeln('Project cache is not supported for global mode');
    return 1;
  }

  final options = ApplyOptions.fromArgResults(argResults!);
  final resolvedCacheDir = resolveCacheDir(
    options.globalPatchOptions.cacheDir,
  );
  final cacheDir = Directory(resolvedCacheDir);

  if (!cacheDir.existsSync()) {
    stderr.writeln(
      '$resolvedCacheDir does not exist. Did you run `$kExecutableName pub get`?',
    );
    return 1;
  }

  if (!(await gitExists())) {
    stderr.writeln('Git is not installed');
    return 1;
  }

  final patchDir = Directory(
    resolveProjectPath(options.globalPatchOptions.patchDir),
  );
  if (!patchDir.existsSync()) {
    stderr.writeln(
      'Patch directory does not exist. Did you run `$kExecutableName patch generate`?',
    );
    return 1;
  }

  final hostedPatchesDir = Directory(join(patchDir.path, 'hosted'));
  final gitPatchesDir = Directory(join(patchDir.path, 'git'));

  final hostedPatches = hostedPatchesDir.existsSync()
      ? hostedPatchesDir.listSync().whereType<File>()
      : <File>[];
  final gitPatches = gitPatchesDir.existsSync()
      ? gitPatchesDir.listSync().whereType<File>()
      : <File>[] as Iterable<File>;

  if (hostedPatches.isEmpty && gitPatches.isEmpty) {
    stderr.writeln('No patches to apply');
    return 0;
  }

  final resetCacheExitCode = await _resetGitWorktree(
    workingDirectory: resolvedCacheDir,
    label: basename(resolvedCacheDir),
    force: options.force,
  );
  if (resetCacheExitCode != 0) {
    return resetCacheExitCode;
  }

  for (final patch in hostedPatches) {
    final result = await Process.run('git', [
      'apply',
      patch.path,
    ], workingDirectory: resolvedCacheDir);

    if (result.exitCode != 0) {
      stderr.writeln(
        'Failed to apply patch ${patch.path}:\n${result.stderr}',
      );
      return 1;
    }
  }

  for (final patch in gitPatches) {
    final workingDir = join(
      resolvedCacheDir,
      'git',
      basenameWithoutExtension(patch.path),
    );

    final resetExitCode = await _resetGitWorktree(
      workingDirectory: workingDir,
      label: basenameWithoutExtension(patch.path),
      force: options.force,
    );
    if (resetExitCode != 0) {
      return resetExitCode;
    }

    final result = await Process.run('git', [
      'apply',
      patch.path,
    ], workingDirectory: workingDir);

    if (result.exitCode != 0) {
      stderr.writeln(
        'Failed to apply patch ${patch.path}:\n${result.stderr}',
      );
      return 1;
    }
  }

  return 0;
}