Skip to content

Commit

Permalink
Fix avoid_global_state_rule (#87)
Browse files Browse the repository at this point in the history
Co-authored-by: Yurii Prykhodko <[email protected]>
  • Loading branch information
1 parent b6adfd5 commit cf530f2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
25 changes: 19 additions & 6 deletions lib/lints/avoid_global_state/avoid_global_state_rule.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/error/listener.dart';
import 'package:custom_lint_builder/custom_lint_builder.dart';
import 'package:solid_lints/models/rule_config.dart';
Expand Down Expand Up @@ -30,12 +31,24 @@ class AvoidGlobalStateRule extends SolidLintRule {
ErrorReporter reporter,
CustomLintContext context,
) {
context.registry.addVariableDeclaration((node) {
final isPrivate = node.declaredElement?.isPrivate ?? false;

if (!isPrivate && !node.isFinal && !node.isConst) {
reporter.reportErrorForNode(code, node);
}
context.registry.addTopLevelVariableDeclaration(
(node) => node.variables.variables
.where((variable) => variable.isPublicMutable)
.forEach((node) => reporter.reportErrorForNode(code, node)),
);
context.registry.addFieldDeclaration((node) {
if (!node.isStatic) return;
node.fields.variables
.where((variable) => variable.isPublicMutable)
.forEach((node) => reporter.reportErrorForNode(code, node));
});
}
}

extension on VariableDeclaration {
bool get isMutable => !isFinal && !isConst;

bool get isPrivate => declaredElement?.isPrivate ?? false;

bool get isPublicMutable => isMutable && !isPrivate;
}
20 changes: 19 additions & 1 deletion lint_test/avoid_global_state_test.dart
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
// ignore_for_file: type_annotate_public_apis, prefer_match_file_name
// ignore_for_file: type_annotate_public_apis, prefer_match_file_name, unused_local_variable

/// Check global mutable variable fail
/// `avoid_global_state`
// expect_lint: avoid_global_state
var globalMutable = 0;

final globalFinal = 1;

const globalConst = 1;

class Test {
static final int globalFinal = 1;

// expect_lint: avoid_global_state
static int globalMutable = 0;

final int memberFinal = 1;

int memberMutable = 0;

void m() {
int localMutable = 0;

final localFinal = 1;

const localConst = 2;
}
}

0 comments on commit cf530f2

Please sign in to comment.