runCliAnalysis method

Future<Iterable<UnusedCodeFileReport>> runCliAnalysis(
  1. Iterable<String> folders,
  2. String rootFolder,
  3. UnusedCodeConfig config, {
  4. String? sdkPath,
})

Returns a list of unused code reports for analyzing all files in the given folders. The analysis is configured with the config.

Implementation

Future<Iterable<UnusedCodeFileReport>> runCliAnalysis(
  Iterable<String> folders,
  String rootFolder,
  UnusedCodeConfig config, {
  String? sdkPath,
}) async {
  final collection =
      createAnalysisContextCollection(folders, rootFolder, sdkPath);

  final codeUsages = FileElementsUsage();
  final publicCode = <String, Set<Element>>{};

  for (final context in collection.contexts) {
    final unusedCodeAnalysisConfig =
        _getAnalysisConfig(context, rootFolder, config);

    if (config.shouldPrintConfig) {
      _logger?.printConfig(unusedCodeAnalysisConfig.toJson());
    }

    final filePaths = getFilePaths(
      folders,
      context,
      rootFolder,
      unusedCodeAnalysisConfig.globalExcludes,
    );

    final analyzedFiles =
        filePaths.intersection(context.contextRoot.analyzedFiles().toSet());

    final contextsLength = collection.contexts.length;
    final filesLength = analyzedFiles.length;
    final updateMessage = contextsLength == 1
        ? 'Checking unused code for $filesLength file(s)'
        : 'Checking unused code for ${collection.contexts.indexOf(context) + 1}/$contextsLength contexts with $filesLength file(s)';
    _logger?.progress.update(updateMessage);

    for (final filePath in analyzedFiles) {
      _logger?.infoVerbose('Analyzing $filePath');

      final unit = await context.currentSession.getResolvedUnit(filePath);

      final codeUsage = _analyzeFileCodeUsages(unit);
      if (codeUsage != null) {
        codeUsages.merge(codeUsage);
      }

      if (!unusedCodeAnalysisConfig.analyzerExcludedPatterns
          .any((pattern) => pattern.matches(filePath))) {
        publicCode[filePath] = _analyzeFilePublicCode(unit);
      }
    }
  }

  if (!config.isMonorepo) {
    _logger?.infoVerbose(
      'Removing globally exported files with code usages from the analysis: ${codeUsages.exports.length}',
    );
    codeUsages.exports.forEach(publicCode.remove);
  }

  return _getReports(codeUsages, publicCode, rootFolder);
}