checkAndAddDeps method

Future<void> checkAndAddDeps({
  1. required Config config,
  2. required String workingDirectory,
})

Checks the target project for required dependencies and installs any missing ones.

Dependencies are added via dart pub add to keep the project in a valid state (it updates pubspec.yaml and runs pub get). This includes packages needed for either bloc or riverpod generation.

Implementation

Future<void> checkAndAddDeps({required Config config, required String workingDirectory}) async {
  final requiredDependencies = [
    'get_it',
    'injectable',
    if (config.bloc == true) ...['flutter_bloc', 'bloc'],
    'equatable',
    'freezed_annotation',
    'json_annotation',
    if (config.riverpod == true) 'flutter_riverpod',
  ];
  const requiredDevDependencies = [
    'build_runner',
    'injectable_generator',
    'freezed',
    'json_serializable',
  ];

  try {
    final (dependencies, devDependencies) = await YamlHelper().getDependencies(
      workingDirectory: workingDirectory,
    );

    final installableDeps = <String>[];
    final installableDevDeps = <String>[];

    for (var dep in requiredDependencies) {
      if (dependencies == null || !dependencies.containsKey(dep)) {
        stdout.writeln('Adding $dep to dependencies');
        installableDeps.add(dep);
      }
    }

    for (var dep in requiredDevDependencies) {
      if (devDependencies == null || !devDependencies.containsKey(dep)) {
        stdout.writeln('Adding $dep to dev_dependencies');
        installableDevDeps.add('dev:$dep');
      }
    }

    if (installableDeps.isNotEmpty || installableDevDeps.isNotEmpty) {
      final exitCode = await _runCommand('dart', [
        'pub',
        'add',
        ...installableDeps,
        ...installableDevDeps,
      ], workingDirectory: workingDirectory);

      if (exitCode != 0) {
        CommandHelper().warning('Failed to add dependencies');
      } else {
        CommandHelper().success('Dependencies added successfully', shouldExit: false);
      }
    }
  } catch (e) {
    CommandHelper().warning('Could not check dependencies: $e');
  }
}