Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions packages/leancode_lint/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,39 @@ class MyClassCubit extends Cubit<int> {}

None.

### `bloc_related_class_naming`
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

update with main. it's in <details> now


**DO** follow the naming convention for Bloc/Cubit related classes.

For `ExampleBloc`:
- Event class: `ExampleEvent`
- State class: `ExampleState`
- Presentation Event class: `ExamplePresentationEvent`

For `ExampleCubit`:
- State class: `ExampleState`
- Presentation Event class: `ExampleEvent`

> [!NOTE]
> This lint only checks classes defined in the same library (including parts) as the Bloc/Cubit.
> Presentation events are only checked if the `bloc_presentation` package is used.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Presentation events are only checked if the bloc_presentation package is used.

What does "used" mean here? If it's imported?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the "presentation" is implemented with the bloc_presentation package (there might be different offerings; we don't check those)


**BAD:**

```dart
class MyBloc extends Bloc<WrongEvent, WrongState> {}
```

**GOOD:**

```dart
class MyBloc extends Bloc<MyEvent, MyState> {}
```

#### Configuration

None.

### `avoid_conditional_hooks`

**AVOID** using hooks conditionally
Expand Down
2 changes: 2 additions & 0 deletions packages/leancode_lint/lib/plugin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'package:leancode_lint/src/assists/convert_record_into_nominal_type.dart'
import 'package:leancode_lint/src/lints/add_cubit_suffix_for_cubits.dart';
import 'package:leancode_lint/src/lints/avoid_conditional_hooks.dart';
import 'package:leancode_lint/src/lints/avoid_single_child_in_multi_child_widget.dart';
import 'package:leancode_lint/src/lints/bloc_related_class_naming.dart';
import 'package:leancode_lint/src/lints/catch_parameter_names.dart';
import 'package:leancode_lint/src/lints/constructor_parameters_and_fields_should_have_the_same_order.dart';
import 'package:leancode_lint/src/lints/hook_widget_does_not_use_hooks.dart';
Expand Down Expand Up @@ -45,6 +46,7 @@ final class LeanCodeLintPlugin extends Plugin {
AddStartingSpaceToComment.new,
)
..registerWarningRule(AddCubitSuffixForYourCubits())
..registerWarningRule(BlocRelatedClassNaming())
..registerWarningRule(CatchParameterNames(config: config))
..registerWarningRule(AvoidConditionalHooks())
..registerWarningRule(HookWidgetDoesNotUseHooks())
Expand Down
93 changes: 93 additions & 0 deletions packages/leancode_lint/lib/src/bloc_utils.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:leancode_lint/src/type_checker.dart';

const blocChecker = TypeChecker.fromName('Bloc', packageName: 'bloc');

const cubitChecker = TypeChecker.fromName('Cubit', packageName: 'bloc');

const blocPresentationMixinChecker = TypeChecker.fromName(
'BlocPresentationMixin',
packageName: 'bloc_presentation',
);

String? getBlocSubject(String className, {required BlocType blocType}) =>
switch (blocType) {
.bloc when className.endsWith('Bloc') => className.substring(
0,
className.length - 4,
),
.cubit when className.endsWith('Cubit') => className.substring(
0,
className.length - 5,
),
_ => null,
};

enum BlocType { bloc, cubit }

BlocType? determineBlocType(Element? element) {
if (element == null) {
return null;
}

if (blocChecker.isAssignableFrom(element)) {
return .bloc;
} else if (cubitChecker.isAssignableFrom(element)) {
return .cubit;
}

return null;
}

class BlocInfo {
const BlocInfo({
required this.type,
this.stateType,
this.eventType,
this.presentationEventType,
});

final BlocType type;
final TypeAnnotation? stateType;
final TypeAnnotation? eventType;
final TypeAnnotation? presentationEventType;
}

BlocInfo? getBlocInfo(ClassDeclaration node) {
final extendsClause = node.extendsClause;
final superclass = extendsClause?.superclass;
final superclassElement = superclass?.element;

final type = determineBlocType(superclassElement);
if (type == null) {
return null;
}

final typeArguments = superclass?.typeArguments?.arguments;

final (eventType, stateType) = switch (typeArguments) {
[final state] when type == .cubit => (null, state),
[final event, final state] when type == .bloc => (event, state),
_ => (null, null),
};

TypeAnnotation? presentationEventType;
if (node.withClause case final withClause?) {
for (final mixin in withClause.mixinTypes) {
if (mixin.element case final mixinElement?
when blocPresentationMixinChecker.isExactly(mixinElement)) {
if (mixin.typeArguments?.arguments case [_, final presentationEvent]) {
presentationEventType = presentationEvent;
}
}
}
}

return .new(
type: type,
stateType: stateType,
eventType: eventType,
presentationEventType: presentationEventType,
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import 'package:analyzer/analysis_rule/analysis_rule.dart';
import 'package:analyzer/analysis_rule/rule_context.dart';
import 'package:analyzer/analysis_rule/rule_visitor_registry.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/error/error.dart';
import 'package:leancode_lint/src/bloc_utils.dart';
import 'package:leancode_lint/src/utils.dart';

class BlocRelatedClassNaming extends AnalysisRule {
Comment thread
Albert221 marked this conversation as resolved.
BlocRelatedClassNaming()
: super(name: code.lowerCaseName, description: code.problemMessage);

static const code = LintCode(
'bloc_related_class_naming',
"The name of {0}'s {1} should be {2}.",
severity: .WARNING,
);

@override
LintCode get diagnosticCode => code;

@override
void registerNodeProcessors(
RuleVisitorRegistry registry,
RuleContext context,
) {
registry.addClassDeclaration(this, _Visitor(this, context));
}
}

class _Visitor extends SimpleAstVisitor<void> {
_Visitor(this.rule, this.context);

final AnalysisRule rule;
final RuleContext context;

@override
void visitClassDeclaration(ClassDeclaration node) {
final blocInfo = getBlocInfo(node);
if (blocInfo == null) {
return;
}

final classElement = node.declaredFragment?.element;
final className = node.namePart.typeName.lexeme;
final subject = getBlocSubject(className, blocType: blocInfo.type);

if (subject == null) {
return;
}

void checkName(TypeAnnotation type, String classType, String expectedName) {
if (type case NamedType(
:final name,
:final element?,
:final CompilationUnit root,
) when name.lexeme != expectedName) {
if (element.library != classElement?.library) {
return;
}

final declaration = root.declarations
.whereType<ClassDeclaration>()
.firstWhereOrNull((d) => d.declaredFragment?.element == element);

rule.reportAtToken(
Comment thread
PiotrRogulski marked this conversation as resolved.
declaration?.namePart.typeName ?? name,
arguments: [className, classType, expectedName],
);
}
}

if (blocInfo.stateType case final stateType?) {
checkName(stateType, 'state', '${subject}State');
}

if (blocInfo.eventType case final eventType?) {
checkName(eventType, 'event', '${subject}Event');
}

if (blocInfo.presentationEventType case final presentationEventType?) {
final expectedPresentationEventName = blocInfo.type == .cubit
? '${subject}Event'
: '${subject}PresentationEvent';
checkName(
presentationEventType,
'presentation event',
expectedPresentationEventName,
);
}
}
}
1 change: 1 addition & 0 deletions packages/leancode_lint/test/mock_libraries.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:analyzer_testing/analysis_rule/analysis_rule.dart';

part 'mock_libraries/bloc.dart';
part 'mock_libraries/bloc_presentation.dart';
part 'mock_libraries/flutter.dart';
part 'mock_libraries/flutter_bloc.dart';
part 'mock_libraries/flutter_hooks.dart';
Expand Down
9 changes: 9 additions & 0 deletions packages/leancode_lint/test/mock_libraries/bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,18 @@ mixin MockBloc on AnalysisRuleTest {
@override
void setUp() {
newPackage('bloc').addFile('lib/bloc.dart', '''
class BlocBase<State> {
BlocBase(this.state);
State state;
}

abstract class Cubit<State> extends BlocBase<State> {
Cubit(State initialState) : super(initialState);
}

abstract class Bloc<Event, State> extends BlocBase<State> {
Bloc(State initialState) : super(initialState);
}
''');
super.setUp();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
part of '../mock_libraries.dart';

mixin MockBlocPresentation on AnalysisRuleTest {
@override
void setUp() {
newPackage('bloc_presentation').addFile('lib/bloc_presentation.dart', '''
mixin BlocPresentationMixin<State, PresentationEvent> {}
''');
super.setUp();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import 'package:analyzer_testing/analysis_rule/analysis_rule.dart';
import 'package:leancode_lint/src/lints/bloc_related_class_naming.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';

import '../assert_ranges.dart';
import '../mock_libraries.dart';

void main() {
defineReflectiveSuite(() {
defineReflectiveTests(BlocRelatedClassNamingTest);
});
}

@reflectiveTest
class BlocRelatedClassNamingTest extends AnalysisRuleTest
with MockBloc, MockBlocPresentation, MockFlutterBloc {
@override
void setUp() {
rule = BlocRelatedClassNaming();

newPackage('external_lib').addFile('lib/external_lib.dart', '''
class ExternalWrongEvent {}
class ExternalWrongState {}
''');

super.setUp();
}

Future<void> test_bloc() async {
await assertDiagnosticsInRanges('''
import 'package:bloc/bloc.dart';
import 'package:bloc_presentation/bloc_presentation.dart';

class GoodEvent {}
class GoodState {}
class GoodPresentationEvent {}

class GoodBloc extends Bloc<GoodEvent, GoodState>
with BlocPresentationMixin<GoodState, GoodPresentationEvent> {
GoodBloc() : super(GoodState());
}

class /*[0*/WrongEvent/*0]*/ {}
class /*[1*/WrongState/*1]*/ {}
class /*[2*/WrongPresentationEvent/*2]*/ {}

class MyBloc extends Bloc<WrongEvent, WrongState>
with BlocPresentationMixin<WrongState, WrongPresentationEvent> {
MyBloc() : super(WrongState());
}
''');
}

Future<void> test_cubit() async {
await assertDiagnosticsInRanges('''
import 'package:bloc/bloc.dart';
import 'package:bloc_presentation/bloc_presentation.dart';

class GoodState {}
class GoodEvent {}

class GoodCubit extends Cubit<GoodState>
with BlocPresentationMixin<GoodState, GoodEvent> {
GoodCubit() : super(GoodState());
}

class /*[0*/WrongState/*0]*/ {}
class /*[1*/WrongPresentationEvent/*1]*/ {}

class MyCubit extends Cubit<WrongState>
with BlocPresentationMixin<WrongState, WrongPresentationEvent> {
MyCubit() : super(WrongState());
}
''');
}

Future<void> test_external_classes_ignored() async {
await assertNoDiagnostics('''
import 'package:bloc/bloc.dart';
import 'package:external_lib/external_lib.dart';

class MyBloc extends Bloc<ExternalWrongEvent, ExternalWrongState> {
MyBloc() : super(ExternalWrongState());
}
''');
}

Future<void> test_part_file_definition() async {
newFile('$testPackageLibPath/part.dart', '''
part of 'test.dart';

class WrongState {}

class GoodState {}
''');

await assertDiagnosticsInRanges('''
import 'package:bloc/bloc.dart';

part 'part.dart';

class MyCubit extends Cubit</*[0*/WrongState/*0]*/> {
MyCubit() : super(WrongState());
}

class GoodCubit extends Cubit<GoodState> {
GoodCubit() : super(GoodState());
}
''');
}
}