Why does the implementation_imports linting rule only work in lib directory?

107 views Asked by At

I'm pretty new to dart and as far as I understand you should never import from the lib/src directory of other packages, as it is (by convention) implementation code of the respective package. This should be checked by the implementation_imports linting rule.

So I added the rule to my analysis_options.yaml file:

linter:
  rules:
    - implementation_imports

and this works fine for files in the lib/ directory, I can see the message in the VS code Problems section as well as when running dart analyze. However it seems as though files in other top level directories such as bin/ and test/ are ignored.

I tried searching for this issue but haven't found anything useful or related. Is this by design? Is there something wrong with my configuration/version? Because I don't understand why this rule shouldn't apply to directories other than lib?

Dart SDK version: 3.2.6

dev_dependencies:
  lints: ^3.0.0

Edit:

reported as a bug on github

1

There are 1 answers

5
Dhafin Rayhan On

In the source code of this linter rule, it has these lines:

@override
void visitImportDirective(ImportDirective node) {
  var importUri = node.element?.importedLibrary?.source.uri;
  var sourceUri = node.element?.source.uri;

  // Test for 'package:*/src/'.
  if (!isImplementation(importUri)) {
    return;
  }

  // If the source URI is not a `package` URI bail out.
  if (!isPackage(sourceUri)) {
    return;
  }

  if (!samePackage(importUri, sourceUri)) {
    rule.reportLint(node.uri);
  }
}

Notice how it's checking if the sourceUri is a package, and "bail out" when it's not. This is the implementation of isPackage function:

bool isPackage(Uri? uri) => uri?.scheme == 'package';

When the source file is not in the /lib directory, it won't have the package scheme in its URI (package: is only for the /lib directory, see this and this). It makes this visitImportDirective function returns in that check and won't have that reportLint method called.