extractModuleName static method

Future<String?> extractModuleName(
  1. String jarPath
)

Extracts the module name from a JAR file

Attempts to determine the module name by examining:

  • module-info.class
  • META-INF/MANIFEST.MF for Automatic-Module-Name or Microsoft-Module-Name
  • Bundle-SymbolicName
  • Falls back to extracting module information from the filename

jarPath - Path to the JAR file Returns the module name if found, null otherwise

Implementation

static Future<String?> extractModuleName(String jarPath) async {
  try {
    final tempDir = await Directory.systemTemp.createTemp('jar_module_');

    try {
      final moduleInfoPath = p.join(tempDir.path, 'module-info.class');

      final process = await Process.run('jar', [
        'xf',
        jarPath,
        'module-info.class',
      ], workingDirectory: tempDir.path);

      if (process.exitCode == 0 && await File(moduleInfoPath).exists()) {
        final jarName = p.basename(jarPath).toLowerCase();
        final nameParts = jarName.split('-');

        if (nameParts.isNotEmpty) {
          return nameParts[0];
        }
      }

      final manifestDir = p.join(tempDir.path, 'META-INF');
      final manifestPath = p.join(manifestDir, 'MANIFEST.MF');

      final manifestProcess = await Process.run('jar', [
        'xf',
        jarPath,
        'META-INF/MANIFEST.MF',
      ], workingDirectory: tempDir.path);

      if (manifestProcess.exitCode == 0 &&
          await File(manifestPath).exists()) {
        final manifestFile = File(manifestPath);
        final content = await manifestFile.readAsString();

        final moduleNameMatch = RegExp(
          r'(Automatic-Module-Name|Microsoft-Module-Name): ([^\r\n]+)',
        ).firstMatch(content);

        if (moduleNameMatch != null && moduleNameMatch.groupCount >= 2) {
          return moduleNameMatch.group(2)?.trim();
        }

        final bundleNameMatch = RegExp(
          r'Bundle-SymbolicName: ([^\r\n;]+)',
        ).firstMatch(content);

        if (bundleNameMatch != null && bundleNameMatch.groupCount >= 1) {
          return bundleNameMatch.group(1)?.trim();
        }
      }

      final jarFileName = p.basenameWithoutExtension(jarPath);
      final fileNameParts = jarFileName.split('-');

      if (fileNameParts.isNotEmpty) {
        String moduleName = fileNameParts[0];

        for (int i = 1; i < fileNameParts.length; i++) {
          final part = fileNameParts[i];
          if (RegExp(r'^\d').hasMatch(part)) {
            break;
          }
          moduleName += '-$part';
        }

        return moduleName;
      }
    } finally {
      await tempDir.delete(recursive: true);
    }
  } catch (e) {
    debugPrint('Error extracting module name: $e');
  }

  return null;
}