runWithReporter method

  1. @override
void runWithReporter(
  1. SaropaDiagnosticReporter reporter,
  2. SaropaContext context
)
override

Override this method to implement your lint rule.

Use context to register callbacks for AST node types:

context.addMethodInvocation((node) {
  if (condition) {
    reporter.atNode(node);
  }
});

Implementation

@override
void runWithReporter(
  SaropaDiagnosticReporter reporter,
  SaropaContext context,
) {
  // Track occurrences and report when threshold is reached.
  // Note: Map state is per-file since runWithReporter is called per-file.
  final Map<String, List<AstNode>> stringOccurrences =
      <String, List<AstNode>>{};

  context.addSimpleStringLiteral((SimpleStringLiteral node) {
    final String value = node.value;

    // Skip short strings
    if (value.length < _minLength) return;

    // Skip directive URIs (import/export/part): Dart requires these to be
    // string literals, so there is no legal way to extract them to a
    // constant. See isInImportOrExport doc for details.
    if (isInImportOrExport(node)) return;

    // Skip excluded patterns
    if (_shouldSkipString(value)) return;

    final List<AstNode> occurrences = stringOccurrences.putIfAbsent(
      value,
      () => <AstNode>[],
    );
    occurrences.add(node);

    // Report when we hit the threshold (report the current node)
    // and when we exceed it (each subsequent occurrence)
    if (occurrences.length >= _minOccurrences) {
      reporter.atNode(node);
    }
  });
}