Skip to content

Commit f67f6a7

Browse files
[camera_android_camerax][tool] Migrate complexity checks to package:cognitive_complexity (flutter#12356)
When we initially added cyclomatic complexity [we wanted cognitive complexity](flutter/packages#11999). Now there is a mit licensed version that meets our dependency constraints maintained by a flutter contributor so let's migrate to that. - @reidbaker --- Agent authored pr description Migrates codebase complexity enforcement for `camera_android_camerax` from `dart_code_linter` (cyclomatic complexity) to `package:cognitive_complexity` (cognitive complexity), matching the migration in flutter/agent-plugins#211 and replacing flutter/packages#11999. ## Summary - Replaced `dart_code_linter` with `cognitive_complexity` under `pinned` allowed dependencies in `.repo_tool_config.yaml`. - Updated `AnalyzeCommand` in `script/tool/lib/src/analyze_command.dart` to execute `cognitive_complexity` with configured fail thresholds from `analysis_options.yaml` while filtering out generated Dart files (`.g.dart`, `.mocks.dart`, `.gen.dart`). - Replaced `dart_code_linter` with `cognitive_complexity: 0.2.1` in `packages/camera/camera_android_camerax/pubspec.yaml` and configured `fail-threshold: 15` in `analysis_options.yaml`. - Updated repository tooling unit tests in `script/tool/test/analyze_command_test.dart` to test `cognitive_complexity` and verify generated file exclusion. ## Pre-Review Checklist
1 parent 142990b commit f67f6a7

5 files changed

Lines changed: 129 additions & 62 deletions

File tree

‎.repo_tool_config.yaml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ allowed_dependencies:
2020
# A pin can be either an exact version, or a range with an explicit, inclusive
2121
# max version, which must a version that already exists, not a future version.
2222
pinned:
23-
# Cyclomatic complexity linter for camera_android_camerax
24-
- dart_code_linter
23+
# Cognitive complexity linter for camera_android_camerax
24+
- cognitive_complexity
2525

2626
# Test-only dependency, so does not impact package clients, and
2727
# has limited impact so could be easily removed if there are

‎packages/camera/camera_android_camerax/analysis_options.yaml‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ analyzer:
1010
- macos/**
1111
- linux/**
1212

13-
dart_code_linter:
14-
metrics:
15-
cyclomatic-complexity: 15
13+
cognitive_complexity:
14+
fail-threshold: 15
1615

‎packages/camera/camera_android_camerax/pubspec.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ dependencies:
2727

2828
dev_dependencies:
2929
build_runner: ^2.2.0
30-
dart_code_linter: 4.1.5
30+
cognitive_complexity: 0.2.1
3131
dart_skills_lint:
3232
git:
3333
url: https://github.com/flutter/skills.git

‎script/tool/lib/src/analyze_command.dart‎

Lines changed: 47 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ class AnalyzeCommand extends PackageLoopingCommand {
321321
];
322322

323323
final customCheckRunners = <_CustomLinter>[
324-
_CustomLinter(dependencyName: 'dart_code_linter', run: _runDartCodeLinterForPackage),
324+
_CustomLinter(dependencyName: 'cognitive_complexity', run: _runCognitiveComplexityForPackage),
325325
];
326326

327327
// Skip custom linters during downgrade as metrics are redundant and vulnerable to dependency issues.
@@ -338,7 +338,7 @@ class AnalyzeCommand extends PackageLoopingCommand {
338338
return errors.isEmpty ? PackageResult.success() : PackageResult.fail(errors);
339339
}
340340

341-
/// Retrieves the configured cyclomatic complexity threshold from the local
341+
/// Retrieves the configured cognitive complexity threshold from the local
342342
/// `analysis_options.yaml` if it exists and is configured.
343343
int? _getLinterThreshold(RepositoryPackage package) {
344344
final File optionsFile = package.directory.childFile('analysis_options.yaml');
@@ -348,14 +348,11 @@ class AnalyzeCommand extends PackageLoopingCommand {
348348
try {
349349
final Object? yaml = loadYaml(optionsFile.readAsStringSync());
350350
if (yaml is YamlMap) {
351-
final Object? linter = yaml['dart_code_linter'];
351+
final Object? linter = yaml['cognitive_complexity'];
352352
if (linter is YamlMap) {
353-
final Object? metrics = linter['metrics'];
354-
if (metrics is YamlMap) {
355-
final Object? complexity = metrics['cyclomatic-complexity'];
356-
if (complexity is int) {
357-
return complexity;
358-
}
353+
final Object? threshold = linter['fail-threshold'];
354+
if (threshold is int) {
355+
return threshold;
359356
}
360357
}
361358
}
@@ -365,23 +362,53 @@ class AnalyzeCommand extends PackageLoopingCommand {
365362
return null;
366363
}
367364

368-
/// Runs the `dart_code_linter` metrics analyzer on the package.
365+
bool _isGeneratedDartFile(String filePath) {
366+
return filePath.endsWith('.g.dart') ||
367+
filePath.endsWith('.mocks.dart') ||
368+
filePath.endsWith('.gen.dart');
369+
}
370+
371+
/// Runs the `cognitive_complexity` metrics analyzer on the package.
369372
///
370-
/// Assumes `dart_code_linter` is present in `dev_dependencies`.
371-
Future<List<String>> _runDartCodeLinterForPackage(RepositoryPackage package) async {
373+
/// Assumes `cognitive_complexity` is present in `dev_dependencies`.
374+
Future<List<String>> _runCognitiveComplexityForPackage(RepositoryPackage package) async {
372375
if (!package.libDirectory.existsSync()) {
373376
return <String>[];
374377
}
375-
print('Running dart_code_linter:metrics analysis...');
376-
final int linterExitCode = await processRunner.runAndStream(_dartBinaryPath, <String>[
378+
final filesToAnalyze = <String>[];
379+
for (final FileSystemEntity entity in package.libDirectory.listSync(recursive: true)) {
380+
if (entity is File && entity.path.endsWith('.dart') && !_isGeneratedDartFile(entity.path)) {
381+
final String relativePath = path.relative(entity.path, from: package.directory.path);
382+
filesToAnalyze.add(relativePath.replaceAll(r'\', '/'));
383+
}
384+
}
385+
if (filesToAnalyze.isEmpty) {
386+
return <String>[];
387+
}
388+
filesToAnalyze.sort();
389+
390+
print('Running cognitive_complexity analysis...');
391+
final int? threshold = _getLinterThreshold(package);
392+
final args = <String>[
377393
'run',
378-
'dart_code_linter:metrics',
379-
'analyze',
380-
'lib',
381-
'--set-exit-on-violation-level=warning',
382-
], workingDir: package.directory);
394+
'cognitive_complexity',
395+
if (threshold != null) ...<String>[
396+
// --fail-threshold only controls the exit code, while --threshold
397+
// controls which functions are printed in the output table (default 0).
398+
// Pass both so that only failing functions are printed in CI logs.
399+
'--threshold',
400+
threshold.toString(),
401+
'--fail-threshold',
402+
threshold.toString(),
403+
],
404+
...filesToAnalyze,
405+
];
406+
final int linterExitCode = await processRunner.runAndStream(
407+
_dartBinaryPath,
408+
args,
409+
workingDir: package.directory,
410+
);
383411
if (linterExitCode != 0) {
384-
final int? threshold = _getLinterThreshold(package);
385412
final thresholdMessage = threshold != null ? ' (configured threshold: $threshold)' : '';
386413
return <String>[
387414
'Metrics violations found$thresholdMessage. See the package\'s local "analysis_options.yaml" for configured thresholds.',

‎script/tool/test/analyze_command_test.dart‎

Lines changed: 77 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -407,19 +407,20 @@ void main() {
407407
});
408408
});
409409

410-
group('dart_code_linter', () {
411-
test('runs dart_code_linter if present in dev_dependencies', () async {
410+
group('cognitive_complexity', () {
411+
test('runs cognitive_complexity if present in dev_dependencies', () async {
412412
final RepositoryPackage package = createFakePackage(
413413
'a_package',
414414
packagesDir,
415415
isFlutter: true,
416416
);
417417
_writeFakePubspecWithLinter(package, inDevDependencies: true);
418+
package.libDirectory.childFile('lib.dart').createSync();
418419

419420
_mockCallsForFlutterAnalyze(
420421
processRunner,
421422
extraDartCalls: [
422-
FakeProcessInfo(MockProcess(), <String>['run', 'dart_code_linter:metrics']),
423+
FakeProcessInfo(MockProcess(), <String>['run', 'cognitive_complexity']),
423424
],
424425
);
425426

@@ -432,23 +433,22 @@ void main() {
432433
ProcessCall('dart', const <String>['analyze', '--fatal-infos'], package.path),
433434
ProcessCall('dart', const <String>[
434435
'run',
435-
'dart_code_linter:metrics',
436-
'analyze',
437-
'lib',
438-
'--set-exit-on-violation-level=warning',
436+
'cognitive_complexity',
437+
'lib/lib.dart',
439438
], package.path),
440439
]),
441440
);
442-
expect(output, contains('Running dart_code_linter:metrics analysis...'));
441+
expect(output, contains('Running cognitive_complexity analysis...'));
443442
});
444443

445-
test('does not run dart_code_linter when --downgrade is specified', () async {
444+
test('does not run cognitive_complexity when --downgrade is specified', () async {
446445
final RepositoryPackage package = createFakePackage(
447446
'a_package',
448447
packagesDir,
449448
isFlutter: true,
450449
);
451450
_writeFakePubspecWithLinter(package, inDevDependencies: true);
451+
package.libDirectory.childFile('lib.dart').createSync();
452452

453453
processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[
454454
FakeProcessInfo(MockProcess(), <String>['pub', 'downgrade']),
@@ -472,17 +472,17 @@ void main() {
472472
]),
473473
);
474474
final String combinedOutput = output.join('\n').toLowerCase();
475-
expect(combinedOutput, isNot(contains('dart_code_linter')));
476-
expect(combinedOutput, isNot(contains('metrics')));
475+
expect(combinedOutput, isNot(contains('cognitive_complexity')));
477476
});
478477

479-
test('does not run dart_code_linter if present in dependencies', () async {
478+
test('does not run cognitive_complexity if present in dependencies', () async {
480479
final RepositoryPackage package = createFakePackage(
481480
'a_package',
482481
packagesDir,
483482
isFlutter: true,
484483
);
485484
_writeFakePubspecWithLinter(package, inDependencies: true);
485+
package.libDirectory.childFile('lib.dart').createSync();
486486

487487
_mockCallsForFlutterAnalyze(processRunner);
488488

@@ -496,16 +496,16 @@ void main() {
496496
]),
497497
);
498498
final String combinedOutput = output.join('\n').toLowerCase();
499-
expect(combinedOutput, isNot(contains('dart_code_linter')));
500-
expect(combinedOutput, isNot(contains('metrics')));
499+
expect(combinedOutput, isNot(contains('cognitive_complexity')));
501500
});
502501

503-
test('does not run dart_code_linter if not present', () async {
502+
test('does not run cognitive_complexity if not present', () async {
504503
final RepositoryPackage package = createFakePackage(
505504
'a_package',
506505
packagesDir,
507506
isFlutter: true,
508507
);
508+
package.libDirectory.childFile('lib.dart').createSync();
509509

510510
_mockCallsForFlutterAnalyze(processRunner);
511511

@@ -519,18 +519,18 @@ void main() {
519519
]),
520520
);
521521
final String combinedOutput = output.join('\n').toLowerCase();
522-
expect(combinedOutput, isNot(contains('dart_code_linter')));
523-
expect(combinedOutput, isNot(contains('metrics')));
522+
expect(combinedOutput, isNot(contains('cognitive_complexity')));
524523
});
525524

526-
test('runs dart_code_linter using dart for pure Dart packages', () async {
525+
test('runs cognitive_complexity using dart for pure Dart packages', () async {
527526
final RepositoryPackage package = createFakePackage('a_package', packagesDir);
528527
_writeFakePubspecWithLinter(package, inDevDependencies: true, includeFlutter: false);
528+
package.libDirectory.childFile('lib.dart').createSync();
529529

530530
processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[
531531
FakeProcessInfo(MockProcess(), <String>['pub', 'get']),
532532
FakeProcessInfo(MockProcess(), <String>['analyze']),
533-
FakeProcessInfo(MockProcess(), <String>['run', 'dart_code_linter:metrics']),
533+
FakeProcessInfo(MockProcess(), <String>['run', 'cognitive_complexity']),
534534
];
535535

536536
final List<String> output = await runCapturingPrint(runner, <String>['analyze']);
@@ -542,17 +542,15 @@ void main() {
542542
ProcessCall('dart', const <String>['analyze', '--fatal-infos'], package.path),
543543
ProcessCall('dart', const <String>[
544544
'run',
545-
'dart_code_linter:metrics',
546-
'analyze',
547-
'lib',
548-
'--set-exit-on-violation-level=warning',
545+
'cognitive_complexity',
546+
'lib/lib.dart',
549547
], package.path),
550548
]),
551549
);
552-
expect(output, contains('Running dart_code_linter:metrics analysis...'));
550+
expect(output, contains('Running cognitive_complexity analysis...'));
553551
});
554552

555-
test('skips dart_code_linter if lib/ does not exist', () async {
553+
test('skips cognitive_complexity if lib/ does not exist', () async {
556554
final RepositoryPackage package = createFakePackage(
557555
'a_package',
558556
packagesDir,
@@ -573,22 +571,48 @@ void main() {
573571
]),
574572
);
575573
final String combinedOutput = output.join('\n').toLowerCase();
576-
expect(combinedOutput, isNot(contains('dart_code_linter')));
577-
expect(combinedOutput, isNot(contains('metrics')));
574+
expect(combinedOutput, isNot(contains('cognitive_complexity')));
578575
});
579576

580-
test('fails if dart_code_linter analysis fails', () async {
577+
test('skips cognitive_complexity if lib/ only contains generated files', () async {
581578
final RepositoryPackage package = createFakePackage(
582579
'a_package',
583580
packagesDir,
584581
isFlutter: true,
585582
);
586583
_writeFakePubspecWithLinter(package, inDevDependencies: true);
584+
package.libDirectory.childFile('foo.g.dart').createSync();
585+
package.libDirectory.childFile('bar.mocks.dart').createSync();
586+
package.libDirectory.childFile('baz.gen.dart').createSync();
587+
588+
_mockCallsForFlutterAnalyze(processRunner);
589+
590+
final List<String> output = await runCapturingPrint(runner, <String>['analyze']);
591+
592+
expect(
593+
processRunner.recordedCalls,
594+
orderedEquals(<ProcessCall>[
595+
ProcessCall('flutter', const <String>['pub', 'get'], package.path),
596+
ProcessCall('dart', const <String>['analyze', '--fatal-infos'], package.path),
597+
]),
598+
);
599+
final String combinedOutput = output.join('\n').toLowerCase();
600+
expect(combinedOutput, isNot(contains('cognitive_complexity')));
601+
});
602+
603+
test('fails if cognitive_complexity analysis fails', () async {
604+
final RepositoryPackage package = createFakePackage(
605+
'a_package',
606+
packagesDir,
607+
isFlutter: true,
608+
);
609+
_writeFakePubspecWithLinter(package, inDevDependencies: true);
610+
package.libDirectory.childFile('lib.dart').createSync();
587611

588612
_mockCallsForFlutterAnalyze(
589613
processRunner,
590614
extraDartCalls: [
591-
FakeProcessInfo(MockProcess(exitCode: 1), <String>['run', 'dart_code_linter:metrics']),
615+
FakeProcessInfo(MockProcess(exitCode: 1), <String>['run', 'cognitive_complexity']),
592616
],
593617
);
594618

@@ -619,17 +643,17 @@ void main() {
619643
isFlutter: true,
620644
);
621645
_writeFakePubspecWithLinter(package, inDevDependencies: true);
646+
package.libDirectory.childFile('lib.dart').createSync();
622647
package.ciConfigFile.writeAsStringSync('allow_custom_analysis_options: true');
623648
package.directory.childFile('analysis_options.yaml').writeAsStringSync('''
624-
dart_code_linter:
625-
metrics:
626-
cyclomatic-complexity: 15
649+
cognitive_complexity:
650+
fail-threshold: 15
627651
''');
628652

629653
_mockCallsForFlutterAnalyze(
630654
processRunner,
631655
extraDartCalls: [
632-
FakeProcessInfo(MockProcess(exitCode: 1), <String>['run', 'dart_code_linter:metrics']),
656+
FakeProcessInfo(MockProcess(exitCode: 1), <String>['run', 'cognitive_complexity']),
633657
],
634658
);
635659

@@ -642,6 +666,22 @@ dart_code_linter:
642666
},
643667
);
644668

669+
expect(
670+
processRunner.recordedCalls,
671+
orderedEquals(<ProcessCall>[
672+
ProcessCall('flutter', const <String>['pub', 'get'], package.path),
673+
ProcessCall('dart', const <String>['analyze', '--fatal-infos'], package.path),
674+
ProcessCall('dart', const <String>[
675+
'run',
676+
'cognitive_complexity',
677+
'--threshold',
678+
'15',
679+
'--fail-threshold',
680+
'15',
681+
'lib/lib.dart',
682+
], package.path),
683+
]),
684+
);
645685
expect(commandError, isA<ToolExit>());
646686
expect(
647687
output,
@@ -773,6 +813,7 @@ dart_code_linter:
773813
isFlutter: true,
774814
);
775815
_writeFakePubspecWithLinter(package, inDevDependencies: true);
816+
package.libDirectory.childFile('lib.dart').createSync();
776817
package.ciConfigFile.writeAsStringSync('analyze_skills: true');
777818

778819
package.directory
@@ -789,7 +830,7 @@ dart_code_linter:
789830
FakeProcessInfo(MockProcess(exitCode: 1), <String>['analyze']), // skills package
790831
FakeProcessInfo(MockProcess(exitCode: 1), <String>[
791832
'run',
792-
'dart_code_linter:metrics',
833+
'cognitive_complexity',
793834
]), // custom linter
794835
];
795836

@@ -1914,8 +1955,8 @@ environment:
19141955
${includeFlutter ? 'flutter: ">=2.5.0"' : ''}
19151956
dependencies:
19161957
${includeFlutter ? 'flutter:\n sdk: flutter' : ''}
1917-
${inDependencies ? ' dart_code_linter: 4.1.5' : ''}
1918-
${inDevDependencies ? 'dev_dependencies:\n dart_code_linter: 4.1.5' : ''}
1958+
${inDependencies ? ' cognitive_complexity: 0.2.0' : ''}
1959+
${inDevDependencies ? 'dev_dependencies:\n cognitive_complexity: 0.2.0' : ''}
19191960
''');
19201961
}
19211962

0 commit comments

Comments
 (0)