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 {
  final args = argResults!;
  final rest = args.rest;
  if (rest.isEmpty) usageException('Usage: plexaverse add <component> [--example] [--overwrite]');

  final name = rest.first;
  final descriptor = ComponentRegistry.get(name);
  if (descriptor == null) {
    stderr.writeln('Component "$name" not found. Try "plexaverse list".');
    return 1;
  }

  final analyzer = ProjectAnalyzer(Directory.current);
  if (!analyzer.isFlutterProject) {
    usageException('Not a Flutter project (missing flutter dependency in pubspec.yaml).');
  }

  final configFile = File('plexaverse.json');
  if (!configFile.existsSync()) {
    usageException('Plexaverse not initialized. Run "plexaverse init" first.');
  }

  final config = jsonDecode(configFile.readAsStringSync()) as Map<String, dynamic>;
  final directories = config['directories'] as Map<String, dynamic>?;
  final componentsDir = directories?['components'] as String? ?? 'lib/widgets';

  // Write files
  for (final entry in descriptor.templates.entries) {
    // Replace default path with configured path
    // Assuming keys in registry are like 'lib/widgets/foo.dart'
    final relativePath = entry.key.replaceFirst('lib/widgets', componentsDir);
    final file = File(relativePath);

    // Ensure directory exists
    if (!file.parent.existsSync()) {
      file.parent.createSync(recursive: true);
    }

    FileSystem.writeFile(file, entry.value, overwrite: args['overwrite'] as bool);
    stdout.writeln('Wrote ${file.path}');
  }

  // Add dependencies
  for (final dep in descriptor.dependencies) {
    await PubspecEditor.addDependency(
      package: dep.name,
      version: dep.version,
      dev: dep.dev,
      useFlutter: true,
    );
    stdout.writeln('Ensured dependency ${dep.name}${dep.version != null ? " ${dep.version}" : ""}');
  }

  stdout.writeln('Component "$name" added.');
  return 0;
}