clean function

Future<void> clean(
  1. Directory dir,
  2. bool recursive, {
  3. required bool explicitRemoveCache,
  4. required bool explicitRemoveGenerated,
})

Implementation

Future<void> clean(
  Directory dir,
  bool recursive, {
  required bool explicitRemoveCache,
  required bool explicitRemoveGenerated,
}) async {
  var path = await dir.resolveSymbolicLinks();
  if (ignores.contains(p.split(path).last) || path.endsWith('.git')) {
    return;
  }

  late final File? pubspec;
  try {
    pubspec = await dir
        .list(recursive: false)
        .where((event) => event is File)
        .cast<File>()
        .singleWhere((element) => element.path.endsWith('pubspec.yaml'));
  } catch (e) {
    pubspec = null;
  }

  if (pubspec != null) {
    YamlMap parsed = loadYaml(await pubspec.readAsString());
    YamlMap? dependencies = parsed["dependencies"];

    if (dependencies != null && dependencies.containsKey('flutter')) {
      print('Cleaning `$path`');

      var result = await Process.run(
        'flutter',
        ['clean'],
        workingDirectory: path,
      );
      if (result.exitCode != 0) {
        throw result.stderr;
      }
      print(
          '\t${result.stdout.toString().trimRight().replaceAll('\n', '\n\t')}');
    } else {
      print('Cleaning `$path`');
      await _deleteDir(path, 'build');
      await _deleteDir(path, '.dart_tool');
    }
    if (explicitRemoveCache) {
      await _deleteDir(path, '.pub-cache');
      await _deleteFile(path, '.packages');
      await _deleteFile(path, 'pubspec.lock');
    }
    if (explicitRemoveGenerated) {
      await _deleteGenerated(dir);
    }

    // Keep looking recursively, as there could be nested packages
    // in a Dart/Flutter project
    if (recursive) {
      await _cleanRecursive(
        dir,
        isDartFlutterDir: true,
        explicitRemoveCache: explicitRemoveCache,
        explicitRemoveGenerated: explicitRemoveGenerated,
      );
    }
  } else {
    if (recursive) {
      print('No pubspec found, skipping `$path`');

      await _cleanRecursive(
        dir,
        isDartFlutterDir: false,
        explicitRemoveCache: explicitRemoveCache,
        explicitRemoveGenerated: explicitRemoveGenerated,
      );
    } else {
      print('No pubspec found, skipping `$path`');
    }
  }
}