Add --lint-all=<regex> as an option for clang_tidy, refactor lint targets (flutter/engine#46522)

I plan to use this to get reasonable re-lint times locally when
iterating on enabling lints, and finishing
https://github.com/flutter/flutter/issues/134969.

For example:

```shell
$ prebuilts/macos-arm64/dart-sdk/bin/dart tools/clang_tidy/bin/main.dart --lint-regex=".*\/fml\/.*"
┌──────────────────────────┐
│ Engine Clang Tidy Linter │
└──────────────────────────┘
The following errors have been reported by the Engine Clang Tidy Linter.  For
more information on addressing these issues please see:
https://github.com/flutter/flutter/wiki/Engine-Clang-Tidy-Linter

🔶 linting flutter/fml/command_line.cc
🔶 linting flutter/fml/command_line.cc
🔶 linting flutter/fml/ascii_trie.cc
🔶 linting flutter/fml/base32.cc
🔶 linting flutter/fml/concurrent_message_loop.cc
🔶 linting flutter/fml/cpu_affinity.cc
🔶 linting flutter/fml/delayed_task.cc
🔶 linting flutter/fml/endianness.cc
🔶 linting flutter/fml/file.cc
🔶 linting flutter/fml/hex_codec.cc
🔶 linting flutter/fml/icu_util.cc
🔶 linting flutter/fml/log_settings.cc
🔶 linting flutter/fml/log_settings_state.cc
🔶 linting flutter/fml/logging.cc
🔶 linting flutter/fml/mapping.cc
🔶 linting flutter/fml/memory/task_runner_checker.cc
🔶 linting flutter/fml/memory/thread_checker.cc
🔶 linting flutter/fml/memory/weak_ptr_internal.cc
🔶 linting flutter/fml/message_loop.cc
🔶 linting flutter/fml/message_loop_impl.cc
🔶 linting flutter/fml/message_loop_task_queues.cc
🔶 linting flutter/fml/paths.cc
🔶 linting flutter/fml/raster_thread_merger.cc
🔶 linting flutter/fml/shared_thread_merger.cc
🔶 linting flutter/fml/synchronization/count_down_latch.cc
🔶 linting flutter/fml/synchronization/semaphore.cc
🔶 linting flutter/fml/synchronization/sync_switch.cc
🔶 linting flutter/fml/synchronization/waitable_event.cc
🔶 linting flutter/fml/task_runner.cc
🔶 linting flutter/fml/task_source.cc
🔶 linting flutter/fml/thread.cc
🔶 linting flutter/fml/thread_local.cc
🔶 linting flutter/fml/time/time_point.cc
🔶 linting flutter/fml/trace_event.cc
🔶 linting flutter/fml/unique_fd.cc
🔶 linting flutter/fml/backtrace_stub.cc
🔶 linting flutter/fml/platform/darwin/concurrent_message_loop_factory.mm
🔶 linting flutter/fml/platform/posix/shared_mutex_posix.cc
🔶 linting flutter/fml/platform/darwin/cf_utils.cc
🔶 linting flutter/fml/platform/darwin/message_loop_darwin.mm
🔶 linting flutter/fml/platform/darwin/paths_darwin.mm
🔶 linting flutter/fml/platform/darwin/platform_version.mm
🔶 linting flutter/fml/platform/darwin/scoped_block.mm
🔶 linting flutter/fml/platform/darwin/scoped_nsautorelease_pool.cc
🔶 linting flutter/fml/platform/darwin/scoped_nsobject.mm
🔶 linting flutter/fml/platform/darwin/string_range_sanitization.mm
🔶 linting flutter/fml/platform/posix/command_line_posix.cc
🔶 linting flutter/fml/platform/posix/file_posix.cc
🔶 linting flutter/fml/platform/posix/mapping_posix.cc
🔶 linting flutter/fml/platform/posix/native_library_posix.cc
🔶 linting flutter/fml/platform/posix/paths_posix.cc
🔶 linting flutter/fml/platform/posix/posix_wrappers_posix.cc
🔶 linting flutter/fml/ascii_trie.cc
🔶 linting flutter/fml/base32.cc
🔶 linting flutter/fml/concurrent_message_loop.cc
🔶 linting flutter/fml/cpu_affinity.cc
🔶 linting flutter/fml/delayed_task.cc
🔶 linting flutter/fml/endianness.cc
🔶 linting flutter/fml/file.cc
🔶 linting flutter/fml/hex_codec.cc
🔶 linting flutter/fml/icu_util.cc
🔶 linting flutter/fml/log_settings.cc
🔶 linting flutter/fml/log_settings_state.cc
🔶 linting flutter/fml/logging.cc
🔶 linting flutter/fml/mapping.cc
🔶 linting flutter/fml/memory/task_runner_checker.cc
🔶 linting flutter/fml/memory/thread_checker.cc
🔶 linting flutter/fml/memory/weak_ptr_internal.cc
🔶 linting flutter/fml/message_loop.cc
🔶 linting flutter/fml/message_loop_impl.cc
🔶 linting flutter/fml/message_loop_task_queues.cc
🔶 linting flutter/fml/paths.cc
🔶 linting flutter/fml/raster_thread_merger.cc
🔶 linting flutter/fml/shared_thread_merger.cc
🔶 linting flutter/fml/synchronization/count_down_latch.cc
🔶 linting flutter/fml/synchronization/semaphore.cc
🔶 linting flutter/fml/synchronization/sync_switch.cc
🔶 linting flutter/fml/synchronization/waitable_event.cc
🔶 linting flutter/fml/task_runner.cc
🔶 linting flutter/fml/task_source.cc
🔶 linting flutter/fml/thread.cc
🔶 linting flutter/fml/thread_local.cc
🔶 linting flutter/fml/time/time_point.cc
🔶 linting flutter/fml/trace_event.cc
🔶 linting flutter/fml/unique_fd.cc
🔶 linting flutter/fml/backtrace_stub.cc
🔶 linting flutter/fml/platform/darwin/concurrent_message_loop_factory.mm
🔶 linting flutter/fml/platform/posix/shared_mutex_posix.cc
🔶 linting flutter/fml/platform/darwin/cf_utils.cc
🔶 linting flutter/fml/platform/darwin/message_loop_darwin.mm
🔶 linting flutter/fml/platform/darwin/paths_darwin.mm
🔶 linting flutter/fml/platform/darwin/platform_version.mm
🔶 linting flutter/fml/platform/darwin/scoped_block.mm
🔶 linting flutter/fml/platform/darwin/scoped_nsautorelease_pool.cc
🔶 linting flutter/fml/platform/darwin/scoped_nsobject.mm
🔶 linting flutter/fml/platform/darwin/string_range_sanitization.mm
🔶 linting flutter/fml/platform/posix/command_line_posix.cc
🔶 linting flutter/fml/platform/posix/file_posix.cc
🔶 linting flutter/fml/platform/posix/mapping_posix.cc
🔶 linting flutter/fml/platform/posix/native_library_posix.cc
🔶 linting flutter/fml/platform/posix/paths_posix.cc
🔶 linting flutter/fml/platform/posix/posix_wrappers_posix.cc
🔶 linting flutter/fml/message_loop_task_queues_benchmark.cc
🔶 linting flutter/fml/ascii_trie_unittests.cc
🔶 linting flutter/fml/backtrace_unittests.cc
🔶 linting flutter/fml/base32_unittest.cc
🔶 linting flutter/fml/closure_unittests.cc
🔶 linting flutter/fml/command_line_unittest.cc
🔶 linting flutter/fml/container_unittests.cc
🔶 linting flutter/fml/cpu_affinity_unittests.cc
🔶 linting flutter/fml/endianness_unittests.cc
🔶 linting flutter/fml/file_unittest.cc
🔶 linting flutter/fml/hash_combine_unittests.cc
🔶 linting flutter/fml/hex_codec_unittest.cc
🔶 linting flutter/fml/logging_unittests.cc
🔶 linting flutter/fml/mapping_unittests.cc
🔶 linting flutter/fml/math_unittests.cc
🔶 linting flutter/fml/memory/ref_counted_unittest.cc
🔶 linting flutter/fml/memory/task_runner_checker_unittest.cc
🔶 linting flutter/fml/memory/weak_ptr_unittest.cc
🔶 linting flutter/fml/message_loop_impl_unittests.cc
🔶 linting flutter/fml/message_loop_task_queues_merge_unmerge_unittests.cc
🔶 linting flutter/fml/message_loop_task_queues_unittests.cc
🔶 linting flutter/fml/message_loop_unittests.cc
🔶 linting flutter/fml/paths_unittests.cc
🔶 linting flutter/fml/raster_thread_merger_unittests.cc
🔶 linting flutter/fml/string_conversion_unittests.cc
🔶 linting flutter/fml/synchronization/count_down_latch_unittests.cc
🔶 linting flutter/fml/synchronization/semaphore_unittest.cc
🔶 linting flutter/fml/synchronization/sync_switch_unittest.cc
🔶 linting flutter/fml/synchronization/waitable_event_unittest.cc
🔶 linting flutter/fml/task_source_unittests.cc
🔶 linting flutter/fml/thread_local_unittests.cc
🔶 linting flutter/fml/thread_unittests.cc
🔶 linting flutter/fml/time/chrono_timestamp_provider.cc
🔶 linting flutter/fml/time/time_delta_unittest.cc
🔶 linting flutter/fml/time/time_point_unittest.cc
🔶 linting flutter/fml/time/time_unittest.cc
🔶 linting flutter/fml/platform/darwin/cf_utils_unittests.mm
🔶 linting flutter/fml/platform/darwin/string_range_sanitization_unittests.mm
🔶 linting flutter/fml/string_conversion.cc
🔶 linting flutter/fml/string_conversion.cc
🔶 linting flutter/fml/dart/dart_converter.cc
[0:00] Jobs:   0% done,   1/143 completed,  7 in progress, 135 pending,   0 failed.  
```
This commit is contained in:
Matan Lurey
2023-10-18 11:06:04 -07:00
committed by GitHub
parent d4b98c93a5
commit c9c5c52428
5 changed files with 175 additions and 50 deletions

View File

@@ -88,7 +88,16 @@ Use `--lint-all` to lint all files in the repo:
dart ./tools/clang_tidy/bin/main.dart --lint-all
```
> **⚠️ WARNING**: This will take a long time to run.
Or, provide a regular expression to lint files that match:
```shell
dart ./tools/clang_tidy/bin/main.dart --lint-regex=".*test.*\.cc"
```
> **⚠️ WARNING**: This may take a long time to run if a pattern is not provided
> or if the pattern matches a large number of files, i.e. on the order of
> thousands of files could take 30 minutes or more to run and lock your
> machine.
[^1]: Modified files are determined by a `git diff` command compared to `HEAD`.
[^2]: Latest build is the last updated directory in `src/out/`.

View File

@@ -13,6 +13,7 @@ import 'package:process/process.dart';
import 'package:process_runner/process_runner.dart';
import 'src/command.dart';
import 'src/lint_target.dart';
import 'src/options.dart';
const String _linterOutputHeader = '''
@@ -48,14 +49,17 @@ class ClangTidy {
/// Builds an instance of [ClangTidy] using a repo's [buildCommandPath].
///
/// ## Required
///
/// - [buildCommandsPath] is the path to the build_commands.json file.
///
/// ## Optional
///
/// - [checksArg] are specific checks for clang-tidy to do.
///
/// If omitted, checks will be determined by the `.clang-tidy` file in the
/// repo.
/// - [lintAll] when true indicates that all files should be linted.
///
/// - [lintTarget] is what files to lint.
///
/// ## Optional (Test Overrides)
///
@@ -76,8 +80,7 @@ class ClangTidy {
ClangTidy({
required io.File buildCommandsPath,
String checksArg = '',
bool lintAll = false,
bool lintHead = false,
LintTarget lintTarget = const LintChanged(),
bool fix = false,
StringSink? outSink,
StringSink? errSink,
@@ -86,8 +89,7 @@ class ClangTidy {
options = Options(
buildCommandsPath: buildCommandsPath,
checksArg: checksArg,
lintAll: lintAll,
lintHead: lintHead,
lintTarget: lintTarget,
fix: fix,
errSink: errSink,
),
@@ -143,12 +145,23 @@ class ClangTidy {
_outSink.writeln('Checking for specific checks: ${options.checks}.');
}
final int changedFilesCount = filesOfInterest.length;
if (options.lintAll) {
_outSink.writeln('Checking all $changedFilesCount files the repo dir.');
} else {
_outSink.writeln(
'Dectected $changedFilesCount files that have changed',
);
switch (options.lintTarget) {
case LintAll():
_outSink.writeln('Checking all $changedFilesCount files in the repo.');
case LintChanged():
_outSink.writeln(
'Checking $changedFilesCount files that have changed since the '
'last commit.',
);
case LintHead():
_outSink.writeln(
'Checking $changedFilesCount files that have changed compared to '
'HEAD.',
);
case LintRegex(:final String regex):
_outSink.writeln(
'Checking $changedFilesCount files that match the regex "$regex".',
);
}
}
@@ -200,26 +213,39 @@ class ClangTidy {
return computeResult + runResult > 0 ? 1 : 0;
}
/// The files with local modifications or all the files if `lintAll` was
/// specified.
/// The files with local modifications or all/a subset of all files.
///
/// See [LintTarget] for more information.
@visibleForTesting
Future<List<io.File>> computeFilesOfInterest() async {
if (options.lintAll) {
return options.repoPath
.listSync(recursive: true)
.whereType<io.File>()
.toList();
switch (options.lintTarget) {
case LintAll():
return options.repoPath
.listSync(recursive: true)
.whereType<io.File>()
.toList();
case LintRegex(:final String regex):
final RegExp pattern = RegExp(regex);
return options.repoPath
.listSync(recursive: true)
.whereType<io.File>()
.where((io.File file) => pattern.hasMatch(file.path))
.toList();
case LintChanged():
final GitRepo repo = GitRepo.fromRoot(
options.repoPath,
processManager: _processManager,
verbose: options.verbose,
);
return repo.changedFiles;
case LintHead():
final GitRepo repo = GitRepo.fromRoot(
options.repoPath,
processManager: _processManager,
verbose: options.verbose,
);
return repo.changedFilesAtHead;
}
final GitRepo repo = GitRepo.fromRoot(
options.repoPath,
processManager: _processManager,
verbose: options.verbose,
);
if (options.lintHead) {
return repo.changedFilesAtHead;
}
return repo.changedFiles;
}
/// Returns f(n) = value(n * [shardCount] + [id]).

View File

@@ -0,0 +1,40 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Describes what should be linted by the Clang Tidy tool.
sealed class LintTarget {
/// Creates a new [LintTarget].
const LintTarget();
}
/// Lints all files in the project.
final class LintAll extends LintTarget {
/// Defines a lint target that lints all files in the project.
const LintAll();
}
/// Lint all files that have changed since the last commit.
///
/// This considers only the last commit, not all commits in the current branch.
final class LintChanged extends LintTarget {
/// Defines a lint target of files that have changed since the last commit.
const LintChanged();
}
/// Lint all files that have changed compared to HEAD.
///
/// This considers _all_ commits in the current branch, not just the last one.
final class LintHead extends LintTarget {
/// Defines a lint target of files that have changed compared to HEAD.
const LintHead();
}
/// Lint all files whose paths match the given regex.
final class LintRegex extends LintTarget {
/// Creates a new [LintRegex] with the given [regex].
const LintRegex(this.regex);
/// The regular expression to match against file paths.
final String regex;
}

View File

@@ -8,6 +8,8 @@ import 'package:args/args.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:path/path.dart' as path;
import 'lint_target.dart';
final Engine _engineRoot = Engine.findWithin(path.dirname(path.fromUri(io.Platform.script)));
/// Adds warnings as errors for only specific runs. This is helpful if migrating one platform at a time.
@@ -28,8 +30,7 @@ class Options {
this.help = false,
this.verbose = false,
this.checksArg = '',
this.lintAll = false,
this.lintHead = false,
this.lintTarget = const LintChanged(),
this.fix = false,
this.errorMessage,
this.warningsAsErrors,
@@ -69,14 +70,22 @@ class Options {
required List<io.File> shardCommandsPaths,
int? shardId,
}) {
final LintTarget lintTarget;
if (options.wasParsed('lint-all') || io.Platform.environment['FLUTTER_LINT_ALL'] != null) {
lintTarget = const LintAll();
} else if (options.wasParsed('lint-regex')) {
lintTarget = LintRegex(options['lint-regex'] as String? ?? '');
} else if (options.wasParsed('lint-head')) {
lintTarget = const LintHead();
} else {
lintTarget = const LintChanged();
}
return Options(
help: options['help'] as bool,
verbose: options['verbose'] as bool,
buildCommandsPath: buildCommandsPath,
checksArg: options.wasParsed('checks') ? options['checks'] as String : '',
lintAll: io.Platform.environment['FLUTTER_LINT_ALL'] != null ||
options['lint-all'] as bool,
lintHead: options['lint-head'] as bool,
lintTarget: lintTarget,
fix: options['fix'] as bool,
errSink: errSink,
warningsAsErrors: _platformSpecificWarningsAsErrors(options),
@@ -148,9 +157,16 @@ class Options {
help: 'Print help.',
negatable: false,
)
..addOption(
'lint-regex',
help: 'Lint all files, regardless of FLUTTER_NOLINT. Provide a regex '
'to filter files. For example, `--lint-regex=".*impeller.*"` will '
'lint all files within a path that contains "impeller".',
valueHelp: 'regex',
)
..addFlag(
'lint-all',
help: 'Lint all of the sources, regardless of FLUTTER_NOLINT.',
help: 'Lint all files, regardless of FLUTTER_NOLINT.',
)
..addFlag(
'lint-head',
@@ -245,11 +261,8 @@ class Options {
/// Check argument to be supplied to the clang-tidy subprocess.
final String? checks;
/// Whether all files should be linted.
final bool lintAll;
/// Whether to lint only files changed in the tip-of-tree commit.
final bool lintHead;
/// What files to lint.
final LintTarget lintTarget;
/// Whether checks should apply available fix-ups to the working copy.
final bool fix;
@@ -290,8 +303,8 @@ class Options {
return 'ERROR: --compile-commands option cannot be used with --src-dir.';
}
if (argResults.wasParsed('lint-all') && argResults.wasParsed('lint-head')) {
return 'ERROR: At most one of --lint-all and --lint-head can be passed.';
if (const <String>['lint-all', 'lint-head', 'lint-regex'].where(argResults.wasParsed).length > 1) {
return 'ERROR: At most one of --lint-all, --lint-head, --lint-regex can be passed.';
}
if (!buildCommandsPath.existsSync()) {

View File

@@ -6,6 +6,7 @@ import 'dart:io' as io show Directory, File, Platform, stderr;
import 'package:clang_tidy/clang_tidy.dart';
import 'package:clang_tidy/src/command.dart';
import 'package:clang_tidy/src/lint_target.dart';
import 'package:clang_tidy/src/options.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:litetest/litetest.dart';
@@ -43,8 +44,7 @@ final class Fixture {
final StringBuffer errBuffer = StringBuffer();
return Fixture._(ClangTidy(
buildCommandsPath: options.buildCommandsPath,
lintAll: options.lintAll,
lintHead: options.lintHead,
lintTarget: options.lintTarget,
fix: options.fix,
outSink: outBuffer,
errSink: errBuffer,
@@ -275,7 +275,24 @@ Future<int> main(List<String> args) async {
expect(result, equals(1));
expect(fixture.errBuffer.toString(), contains(
'ERROR: At most one of --lint-all and --lint-head can be passed.',
'ERROR: At most one of --lint-all, --lint-head, --lint-regex can be passed.',
));
});
test('Error when --lint-all and --lint-regex are used together', () async {
final Fixture fixture = Fixture.fromCommandLine(
<String>[
'--compile-commands',
'/unused',
'--lint-all',
'--lint-regex=".*"',
],
);
final int result = await fixture.tool.run();
expect(result, equals(1));
expect(fixture.errBuffer.toString(), contains(
'ERROR: At most one of --lint-all, --lint-head, --lint-regex can be passed.',
));
});
@@ -283,7 +300,7 @@ Future<int> main(List<String> args) async {
final Fixture fixture = Fixture.fromOptions(
Options(
buildCommandsPath: io.File(buildCommands),
lintAll: true,
lintTarget: const LintAll(),
),
);
final List<io.File> fileList = await fixture.tool.computeFilesOfInterest();
@@ -296,7 +313,7 @@ Future<int> main(List<String> args) async {
buildCommandsPath: io.File(buildCommands),
// Intentional:
// ignore: avoid_redundant_argument_values
lintAll: false,
lintTarget: const LintChanged(),
),
processManager: FakeProcessManager(
onStart: (List<String> command) {
@@ -312,11 +329,31 @@ Future<int> main(List<String> args) async {
expect(fileList.length, lessThan(300));
});
test('lintAll=pattern checks based on a RegEx', () async {
final Fixture fixture = Fixture.fromOptions(
Options(
buildCommandsPath: io.File(buildCommands),
lintTarget: const LintRegex(r'.*test.*\.cc$'),
),
processManager: FakeProcessManager(
onStart: (List<String> command) {
if (command.first == 'git') {
// This just allows git to not actually be called.
return FakeProcess();
}
return FakeProcessManager.unhandledStart(command);
},
),
);
final List<io.File> fileList = await fixture.tool.computeFilesOfInterest();
expect(fileList.length, lessThan(1000));
});
test('Sharding', () async {
final Fixture fixture = Fixture.fromOptions(
Options(
buildCommandsPath: io.File(buildCommands),
lintAll: true,
lintTarget: const LintAll(),
),
processManager: FakeProcessManager(
onStart: (List<String> command) {
@@ -392,7 +429,7 @@ Future<int> main(List<String> args) async {
final Fixture fixture = Fixture.fromOptions(
Options(
buildCommandsPath: io.File(buildCommands),
lintAll: true,
lintTarget: const LintAll(),
),
);
@@ -418,7 +455,7 @@ Future<int> main(List<String> args) async {
final Fixture fixture = Fixture.fromOptions(
Options(
buildCommandsPath: io.File(buildCommands),
lintAll: true,
lintTarget: const LintAll(),
),
);