invertase / dart_custom_lint

💡 Easily write powerful Dart & Flutter lint rules for your projects or for users of your packages.
https://pub.dev/packages/custom_lint
Apache License 2.0
288 stars 65 forks source link

Dart Custom Lint support rules that read some value from other file ? #254

Closed azizarc88 closed 5 months ago

azizarc88 commented 5 months ago

Anw, just wondering, is it possible in custom_lint to create some rules that check the "value" are exist in the list in different file ?

file1.dart

class Test {
  Test(this.data) {
    register(object1);
    register(object2);
    register(object3);
  }

  List<dynamic> data = [];

  static void register(dynamic object) {
    data.add(object);
  }

  static dynamic get(dynamic object) {
     return data[object];
  }
}

file2.dart

class Main {
  Test.get(object4).call(); /// Lint error here, since object4 is not registered
  Test.get(object3).call(); /// No lint error
}
rrousselGit commented 5 months ago

That specific example is not easily feasible, because the AST of other files is not accessible naturally. You may need to adapt your API to be more accessible to linters. The API design matters a lot when writing lints.

rrousselGit commented 5 months ago

One proposal: Consider having a "key" constant for every registered object:

class Test {
  Test(this.data) {
    register(object1, "hello");
    register(object2, 42);
  }

  static final object1 = Key<String>();
  static final object2 = Key<int>();
  static final object3 = Key();
}

You could then implement a lint that warns if a static final name = Key() is declared but not registered inside the constructor.

In the above example, you'd have a warning because object3 is never registered.

Such an API wouldn't involve reading the AST of other files. And it can make reading/initializing objects type-safe.