shouldNotDependOn function

void shouldNotDependOn(
  1. LibrarySelector subject,
  2. LibrarySelector object,
  3. DependencyGraph graph, {
  4. LibrarySelector? except,
})

Asserts no library in subject directly imports any library in object.

Pass except to exclude a subset of subject from the check.

shouldNotDependOn(
  filesMatching('features/home/**'),
  filesMatching('features/discover/**'),
  graph,
);

// Allow one file to cross the boundary
shouldNotDependOn(
  filesMatching('shared/**'),
  filesMatching('features/**'),
  graph,
  except: filesMatching('shared/guards/**'),
);

Implementation

void shouldNotDependOn(
  LibrarySelector subject,
  LibrarySelector object,
  DependencyGraph graph, {
  LibrarySelector? except,
}) {
  final objectUris = object.resolve(graph);
  final exceptUris = except?.resolve(graph) ?? const <String>{};
  final violations = <Violation>[];

  for (final lib in subject.resolve(graph)) {
    if (exceptUris.contains(lib)) continue;
    for (final dep in Collector.dependenciesOf(graph, lib)) {
      if (objectUris.contains(dep)) {
        violations.add(
          Violation(
            rule: 'shouldNotDependOn',
            subject: lib,
            dependency: dep,
            message: 'must not import $dep',
          ),
        );
      }
    }
  }

  _assertNone(violations);
}