detectPackageName function

String detectPackageName(
  1. String directoryPath
)

Implementation

String detectPackageName(String directoryPath) {
  try {
    // Normalize path to make sure it doesn't end with a slash
    final normalizedPath = directoryPath.endsWith('/')
        ? directoryPath.substring(0, directoryPath.length - 1)
        : directoryPath;

    // Handle relative paths using path package for better cross-platform support
    final rootPath = normalizedPath.startsWith('lib${path.separator}')
        ? normalizedPath.replaceFirst('lib${path.separator}', '')
        : normalizedPath;

    // Try different possible locations for pubspec.yaml
    final List<String> possiblePaths = [
      path.join(rootPath, 'pubspec.yaml'),
      'pubspec.yaml',
      path.join('..', 'pubspec.yaml'),
    ];

    File? pubspecFile;
    for (final path in possiblePaths) {
      final file = File(path);
      if (file.existsSync()) {
        pubspecFile = file;
        break;
      }
    }

    if (pubspecFile == null) {
      // If we still haven't found it, try searching up the directory tree
      var currentDir = Directory(rootPath);
      while (currentDir.path != '/' && currentDir.path.isNotEmpty) {
        final pubspec = File('${currentDir.path}/pubspec.yaml');
        if (pubspec.existsSync()) {
          pubspecFile = pubspec;
          break;
        }
        currentDir = currentDir.parent;
      }
    }

    if (pubspecFile != null) {
      final content = pubspecFile.readAsStringSync();

      // Try to find the package name with a more robust regex
      final nameMatch = RegExp(r'name:\s*([a-zA-Z0-9_-]+)').firstMatch(content);
      if (nameMatch != null && nameMatch.groupCount >= 1) {
        final pkgName = nameMatch.group(1)!;
        print('\u001b[36mℹ️  Detected package name: $pkgName\u001b[0m');
        return pkgName;
      }

      print(
          '\u001b[33mWarning: Could not detect package name from pubspec.yaml\u001b[0m');
    }

    // Use directory name as fallback
    final dirName =
        path.basename(path.dirname(pubspecFile?.path ?? directoryPath));
    final sanitizedDirName = dirName.replaceAll(RegExp(r'[^a-zA-Z0-9_]'), '_');
    print(
        '\u001b[33mℹ️  Using directory name as package name: $sanitizedDirName\u001b[0m');
    return sanitizedDirName;
  } catch (e) {
    print('Error detecting package name: $e');
    return 'app';
  }
}