|
| 1 | +import 'package:analyzer/dart/ast/ast.dart'; |
| 2 | +import 'package:analyzer/error/error.dart' hide LintCode; |
| 3 | +import 'package:analyzer/error/listener.dart'; |
| 4 | +import 'package:custom_lint_builder/custom_lint_builder.dart'; |
| 5 | + |
| 6 | +final managerTypeChecker = |
| 7 | + TypeChecker.fromName('BaseTableManager', packageName: 'drift'); |
| 8 | +final insertStatementChecker = |
| 9 | + TypeChecker.fromName('InsertStatement', packageName: 'drift'); |
| 10 | +final insertOrIgnoreChecker = |
| 11 | + TypeChecker.fromName('InsertMode', packageName: 'drift'); |
| 12 | + |
| 13 | +class NonNullInsertWithIgnore extends DartLintRule { |
| 14 | + NonNullInsertWithIgnore() : super(code: _code); |
| 15 | + |
| 16 | + static const _code = LintCode( |
| 17 | + name: 'non_null_insert_with_ignore', |
| 18 | + problemMessage: |
| 19 | + '`insertReturning` and `createReturning` will throw an exception if a row isn\'t actually inserted. Use `createReturningOrNull` or `insertReturningOrNull` if you want to ignore conflicts.', |
| 20 | + errorSeverity: ErrorSeverity.WARNING, |
| 21 | + ); |
| 22 | + |
| 23 | + @override |
| 24 | + void run(CustomLintResolver resolver, ErrorReporter reporter, |
| 25 | + CustomLintContext context) async { |
| 26 | + context.registry.addMethodInvocation( |
| 27 | + (node) { |
| 28 | + if (node.argumentList.arguments.isEmpty) return; |
| 29 | + switch (node.function) { |
| 30 | + case SimpleIdentifier func: |
| 31 | + if (func.name == "insertReturning" || |
| 32 | + func.name == "createReturning") { |
| 33 | + switch (func.parent) { |
| 34 | + case MethodInvocation func: |
| 35 | + final targetType = func.realTarget?.staticType; |
| 36 | + if (targetType != null) { |
| 37 | + if (managerTypeChecker.isSuperTypeOf(targetType) || |
| 38 | + insertStatementChecker.isExactlyType(targetType)) { |
| 39 | + final namedArgs = func.argumentList.arguments |
| 40 | + .whereType<NamedExpression>(); |
| 41 | + for (final arg in namedArgs) { |
| 42 | + if (arg.name.label.name == "mode") { |
| 43 | + switch (arg.expression) { |
| 44 | + case PrefixedIdentifier mode: |
| 45 | + if (mode.identifier.name == "insertOrIgnore") { |
| 46 | + print("Found insertOrIgnore"); |
| 47 | + reporter.atNode(node, _code); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + }, |
| 58 | + ); |
| 59 | + } |
| 60 | +} |
0 commit comments