scanDirectoryEnhanced function

Future<Map<String, List<String>>> scanDirectoryEnhanced(
  1. String directoryPath, {
  2. List<String>? excludePatterns,
})

Enhanced scan directory with pattern-based string extraction.

Scans the specified directoryPath for Dart files and extracts translatable strings using REGEX patterns and context analysis.

Parameters:

  • directoryPath - The root directory to scan for Dart files
  • excludePatterns - Optional list of glob patterns to exclude files/directories

Returns a Map where keys are file paths and values are lists of extracted strings.

Example:

final results = await scanDirectoryEnhanced(
  '/path/to/flutter/project',
  excludePatterns: ['test/**', 'build/**']
);

Implementation

Future<Map<String, List<String>>> scanDirectoryEnhanced(String directoryPath,
    {List<String>? excludePatterns}) async {
  print('🚀 Starting directory scan...');

  // Initialize string extractor
  await StringExtractorFactory.initializeML();
  print(
      '🎯 String extractor Status: ${StringExtractorFactory.isMLInitialized ? 'Ready' : 'Failed to initialize'}');

  final directory = Directory(path.normalize(directoryPath));

  if (!directory.existsSync()) {
    throw FileSystemException('Directory not found', directoryPath);
  }

  // Load exclude patterns from preferences if not provided
  if (excludePatterns == null) {
    try {
      final prefs = PreferencesManager.loadPreferences();
      if (prefs.containsKey('excludePatterns')) {
        final patterns = prefs['excludePatterns'];
        if (patterns is List) {
          excludePatterns = patterns.cast<String>();
        }
      }
    } catch (e) {
      print('\u001b[33mWarning: Could not load exclude patterns: $e\u001b[0m');
    }
  }

  try {
    final scanner = FileScanner(directory.path);
    final dartFiles = scanner.scan();
    final result = <String, List<String>>{};

    print('📁 Found ${dartFiles.length} Dart files.');
    print('🔍 Scanning with pattern-based extraction...');

    final stopwatch = Stopwatch()..start();
    int processed = 0;
    int totalStringsFound = 0;

    // Process files in batches for better performance
    final batchSize = 10;
    for (int i = 0; i < dartFiles.length; i += batchSize) {
      final batch = dartFiles.skip(i).take(batchSize).toList();

      // Process batch with string extraction
      final batchResults = await _extractFromFilesWithCache(
          batch, directory.path,
          maxParallelOperations: batchSize);

      result.addAll(batchResults);

      // Update progress
      processed += batch.length;
      final batchStrings = batchResults.values
          .fold<int>(0, (sum, strings) => sum + strings.length);
      totalStringsFound += batchStrings;

      if (processed % 20 == 0 || processed == dartFiles.length) {
        print(
            '📊 Processed $processed of ${dartFiles.length} files... ($totalStringsFound strings found)');
      }
    }

    stopwatch.stop();

    print('✅ Scan complete!');
    print('⏱️  Time taken: ${stopwatch.elapsedMilliseconds}ms');
    print(
        '📈 Performance: ${(dartFiles.length / (stopwatch.elapsedMilliseconds / 1000)).toStringAsFixed(2)} files/sec');
    print('🎯 Total strings found: $totalStringsFound');

    return result;
  } catch (e) {
    throw FileSystemException(
        'Error scanning directory: ${e.toString()}', directoryPath);
  } finally {
    // Don't dispose here as it might be used again
  }
}