Make ci/lint.dart more idiomatic and move to tools/clang_tidy (flutter/engine#26722)
This commit is contained in:
@@ -132,6 +132,12 @@ analyze \
|
||||
--options "$FLUTTER_DIR/analysis_options.yaml" \
|
||||
"$FLUTTER_DIR/tools/githooks"
|
||||
|
||||
echo "Analyzing tools/clang_tidy"
|
||||
analyze \
|
||||
--packages="$FLUTTER_DIR/tools/clang_tidy/.dart_tool/package_config.json" \
|
||||
--options "$FLUTTER_DIR/analysis_options.yaml" \
|
||||
"$FLUTTER_DIR/tools/clang_tidy"
|
||||
|
||||
# Check that dart libraries conform.
|
||||
echo "Checking web_ui api conformance..."
|
||||
(cd "$FLUTTER_DIR/web_sdk"; "$PUB" get)
|
||||
|
||||
@@ -1,308 +0,0 @@
|
||||
// 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.
|
||||
|
||||
// Runs clang-tidy on files with changes.
|
||||
//
|
||||
// usage:
|
||||
// dart lint.dart <path to compile_commands.json> <path to git repository> [clang-tidy checks]
|
||||
//
|
||||
// User environment variable FLUTTER_LINT_ALL to run on all files.
|
||||
|
||||
import 'dart:async' show Completer;
|
||||
import 'dart:convert' show jsonDecode, utf8, LineSplitter;
|
||||
import 'dart:io' show File, exit, Directory, FileSystemEntity, Platform, stderr, exitCode;
|
||||
|
||||
import 'package:args/args.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:process_runner/process_runner.dart';
|
||||
|
||||
const String _linterOutputHeader = '''
|
||||
┌──────────────────────────┐
|
||||
│ 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
|
||||
''';
|
||||
|
||||
const String issueUrlPrefix = 'https://github.com/flutter/flutter/issues';
|
||||
|
||||
class Command {
|
||||
Directory directory = Directory('');
|
||||
String command = '';
|
||||
File file = File('');
|
||||
}
|
||||
|
||||
Command parseCommand(Map<String, dynamic> map) {
|
||||
final Directory dir = Directory(map['directory'] as String).absolute;
|
||||
return Command()
|
||||
..directory = dir
|
||||
..command = map['command'] as String
|
||||
..file = File(path.normalize(path.join(dir.path, map['file'] as String)));
|
||||
}
|
||||
|
||||
String calcTidyArgs(Command command) {
|
||||
String result = command.command;
|
||||
result = result.replaceAll(RegExp(r'\S*clang/bin/clang'), '');
|
||||
result = result.replaceAll(RegExp(r'-MF \S*'), '');
|
||||
return result;
|
||||
}
|
||||
|
||||
String calcTidyPath(Command command) {
|
||||
final RegExp regex = RegExp(r'\S*clang/bin/clang');
|
||||
return regex
|
||||
.stringMatch(command.command)
|
||||
?.replaceAll('clang/bin/clang', 'clang/bin/clang-tidy') ??
|
||||
'';
|
||||
}
|
||||
|
||||
bool isNonEmptyString(String str) => str.isNotEmpty;
|
||||
|
||||
bool containsAny(File file, Iterable<File> queries) {
|
||||
return queries.where((File query) => path.equals(query.path, file.path)).isNotEmpty;
|
||||
}
|
||||
|
||||
/// Returns a list of all non-deleted files which differ from the nearest
|
||||
/// merge-base with `master`. If it can't find a fork point, uses the default
|
||||
/// merge-base.
|
||||
Future<List<File>> getListOfChangedFiles(Directory repoPath) async {
|
||||
final ProcessRunner processRunner = ProcessRunner(defaultWorkingDirectory: repoPath);
|
||||
final ProcessRunnerResult fetchResult = await processRunner.runProcess(
|
||||
<String>['git', 'fetch', 'upstream', 'master'],
|
||||
failOk: true,
|
||||
);
|
||||
if (fetchResult.exitCode != 0) {
|
||||
await processRunner.runProcess(<String>['git', 'fetch', 'origin', 'master']);
|
||||
}
|
||||
final Set<String> result = <String>{};
|
||||
ProcessRunnerResult mergeBaseResult = await processRunner.runProcess(
|
||||
<String>['git', 'merge-base', '--fork-point', 'FETCH_HEAD', 'HEAD'],
|
||||
failOk: true);
|
||||
if (mergeBaseResult.exitCode != 0) {
|
||||
if (verbose) {
|
||||
stderr.writeln("Didn't find a fork point, falling back to default merge base.");
|
||||
}
|
||||
mergeBaseResult = await processRunner
|
||||
.runProcess(<String>['git', 'merge-base', 'FETCH_HEAD', 'HEAD'], failOk: false);
|
||||
}
|
||||
final String mergeBase = mergeBaseResult.stdout.trim();
|
||||
final ProcessRunnerResult masterResult = await processRunner
|
||||
.runProcess(<String>['git', 'diff', '--name-only', '--diff-filter=ACMRT', mergeBase]);
|
||||
result.addAll(masterResult.stdout.split('\n').where(isNonEmptyString));
|
||||
return result.map<File>((String filePath) => File(path.join(repoPath.path, filePath))).toList();
|
||||
}
|
||||
|
||||
Future<List<File>> dirContents(Directory dir) {
|
||||
final List<File> files = <File>[];
|
||||
final Completer<List<File>> completer = Completer<List<File>>();
|
||||
final Stream<FileSystemEntity> lister = dir.list(recursive: true);
|
||||
lister.listen((FileSystemEntity file) => file is File ? files.add(file) : null,
|
||||
onError: (Object e) => completer.completeError(e), onDone: () => completer.complete(files));
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
File buildFileAsRepoFile(String buildFile, Directory repoPath) {
|
||||
// Removes the "../../flutter" from the build files to make it relative to the flutter
|
||||
// dir.
|
||||
final String relativeBuildFile = path.joinAll(path.split(buildFile).sublist(3));
|
||||
final File result = File(path.join(repoPath.absolute.path, relativeBuildFile));
|
||||
print('Build file: $buildFile => ${result.path}');
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Lint actions to apply to a file.
|
||||
enum LintAction {
|
||||
/// Run the linter over the file.
|
||||
lint,
|
||||
|
||||
/// Ignore files under third_party/.
|
||||
skipThirdParty,
|
||||
|
||||
/// Ignore due to a well-formed FLUTTER_NOLINT comment.
|
||||
skipNoLint,
|
||||
|
||||
/// Fail due to a malformed FLUTTER_NOLINT comment.
|
||||
failMalformedNoLint,
|
||||
}
|
||||
|
||||
bool isThirdPartyFile(File file) {
|
||||
return path.split(file.path).contains('third_party');
|
||||
}
|
||||
|
||||
Future<LintAction> getLintAction(File file) async {
|
||||
if (isThirdPartyFile(file)) {
|
||||
return LintAction.skipThirdParty;
|
||||
}
|
||||
|
||||
// Check for FlUTTER_NOLINT at top of file.
|
||||
final RegExp exp = RegExp(r'//\s*FLUTTER_NOLINT(: $issueUrlPrefix/\d+)?');
|
||||
final Stream<String> lines = file.openRead()
|
||||
.transform(utf8.decoder)
|
||||
.transform(const LineSplitter());
|
||||
await for (final String line in lines) {
|
||||
final RegExpMatch? match = exp.firstMatch(line);
|
||||
if (match != null) {
|
||||
return match.group(1) != null
|
||||
? LintAction.skipNoLint
|
||||
: LintAction.failMalformedNoLint;
|
||||
} else if (line.isNotEmpty && line[0] != '\n' && line[0] != '/') {
|
||||
// Quick out once we find a line that isn't empty or a comment. The
|
||||
// FLUTTER_NOLINT must show up before the first real code.
|
||||
return LintAction.lint;
|
||||
}
|
||||
}
|
||||
return LintAction.lint;
|
||||
}
|
||||
|
||||
WorkerJob createLintJob(Command command, String checks, String tidyPath) {
|
||||
final String tidyArgs = calcTidyArgs(command);
|
||||
final List<String> args = <String>[command.file.path, checks, '--'];
|
||||
args.addAll(tidyArgs.split(' '));
|
||||
return WorkerJob(
|
||||
<String>[tidyPath, ...args],
|
||||
workingDirectory: command.directory,
|
||||
name: 'clang-tidy on ${command.file.path}',
|
||||
);
|
||||
}
|
||||
|
||||
void _usage(ArgParser parser, {int exitCode = 1}) {
|
||||
stderr.writeln('lint.dart [--help] [--lint-all] [--verbose] [--diff-branch]');
|
||||
stderr.writeln(parser.usage);
|
||||
exit(exitCode);
|
||||
}
|
||||
|
||||
bool verbose = false;
|
||||
|
||||
Future<void> main(List<String> arguments) async {
|
||||
final ArgParser parser = ArgParser();
|
||||
parser.addFlag('help', help: 'Print help.');
|
||||
parser.addFlag('lint-all',
|
||||
help: 'lint all of the sources, regardless of FLUTTER_NOLINT.', defaultsTo: false);
|
||||
parser.addFlag('verbose', help: 'Print verbose output.', defaultsTo: verbose);
|
||||
parser.addOption('repo', help: 'Use the given path as the repo path');
|
||||
parser.addOption('compile-commands',
|
||||
help: 'Use the given path as the source of compile_commands.json. This '
|
||||
'file is created by running tools/gn');
|
||||
parser.addOption('checks',
|
||||
help: 'Perform the given checks on the code. Defaults to the empty '
|
||||
'string, indicating all checks should be performed.',
|
||||
defaultsTo: '');
|
||||
final ArgResults options = parser.parse(arguments);
|
||||
|
||||
verbose = options['verbose'] as bool;
|
||||
|
||||
if (options['help'] as bool) {
|
||||
_usage(parser, exitCode: 0);
|
||||
}
|
||||
|
||||
if (!options.wasParsed('compile-commands')) {
|
||||
stderr.writeln('ERROR: The --compile-commands argument is required.');
|
||||
_usage(parser);
|
||||
}
|
||||
|
||||
if (!options.wasParsed('repo')) {
|
||||
stderr.writeln('ERROR: The --repo argument is required.');
|
||||
_usage(parser);
|
||||
}
|
||||
|
||||
final File buildCommandsPath = File(options['compile-commands'] as String);
|
||||
if (!buildCommandsPath.existsSync()) {
|
||||
stderr.writeln("ERROR: Build commands path ${buildCommandsPath.absolute.path} doesn't exist.");
|
||||
_usage(parser);
|
||||
}
|
||||
|
||||
final Directory repoPath = Directory(options['repo'] as String);
|
||||
if (!repoPath.existsSync()) {
|
||||
stderr.writeln("ERROR: Repo path ${repoPath.absolute.path} doesn't exist.");
|
||||
_usage(parser);
|
||||
}
|
||||
|
||||
print(_linterOutputHeader);
|
||||
|
||||
final String checksArg = options.wasParsed('checks') ? options['checks'] as String : '';
|
||||
final String checks = checksArg.isNotEmpty ? '--checks=$checksArg' : '--config=';
|
||||
final bool lintAll =
|
||||
Platform.environment['FLUTTER_LINT_ALL'] != null || options['lint-all'] as bool;
|
||||
final List<File> changedFiles =
|
||||
lintAll ? await dirContents(repoPath) : await getListOfChangedFiles(repoPath);
|
||||
|
||||
if (verbose) {
|
||||
print('Checking lint in repo at $repoPath.');
|
||||
if (checksArg.isNotEmpty) {
|
||||
print('Checking for specific checks: $checks.');
|
||||
}
|
||||
if (lintAll) {
|
||||
print('Checking all ${changedFiles.length} files the repo dir.');
|
||||
} else {
|
||||
print('Dectected ${changedFiles.length} files that have changed');
|
||||
}
|
||||
}
|
||||
|
||||
final List<dynamic> buildCommandMaps =
|
||||
jsonDecode(await buildCommandsPath.readAsString()) as List<dynamic>;
|
||||
final List<Command> buildCommands = buildCommandMaps
|
||||
.map<Command>((dynamic x) => parseCommand(x as Map<String, dynamic>))
|
||||
.toList();
|
||||
final Command firstCommand = buildCommands[0];
|
||||
final String tidyPath = calcTidyPath(firstCommand);
|
||||
assert(tidyPath.isNotEmpty);
|
||||
final List<Command> changedFileBuildCommands =
|
||||
buildCommands.where((Command x) => containsAny(x.file, changedFiles)).toList();
|
||||
|
||||
if (changedFileBuildCommands.isEmpty) {
|
||||
print('No changed files that have build commands associated with them '
|
||||
'were found.');
|
||||
exit(0);
|
||||
}
|
||||
|
||||
if (verbose) {
|
||||
print('Found ${changedFileBuildCommands.length} files that have build '
|
||||
'commands associated with them and can be lint checked.');
|
||||
}
|
||||
|
||||
final List<WorkerJob> jobs = <WorkerJob>[];
|
||||
for (final Command command in changedFileBuildCommands) {
|
||||
final String relativePath = path.relative(command.file.path, from: repoPath.parent.path);
|
||||
final LintAction action = await getLintAction(command.file);
|
||||
switch (action) {
|
||||
case LintAction.skipNoLint:
|
||||
print('🔷 ignoring $relativePath (FLUTTER_NOLINT)');
|
||||
break;
|
||||
case LintAction.failMalformedNoLint:
|
||||
print('❌ malformed opt-out $relativePath');
|
||||
print(' Required format: // FLUTTER_NOLINT: $issueUrlPrefix/ISSUE_ID');
|
||||
exitCode = 1;
|
||||
break;
|
||||
case LintAction.lint:
|
||||
print('🔶 linting $relativePath');
|
||||
jobs.add(createLintJob(command, checks, tidyPath));
|
||||
break;
|
||||
case LintAction.skipThirdParty:
|
||||
print('🔷 ignoring $relativePath (third_party)');
|
||||
break;
|
||||
}
|
||||
}
|
||||
final ProcessPool pool = ProcessPool();
|
||||
|
||||
await for (final WorkerJob job in pool.startWorkers(jobs)) {
|
||||
if (job.result.exitCode == 0) {
|
||||
continue;
|
||||
}
|
||||
if (job.exception != null) {
|
||||
print('\n❗ A clang-tidy job failed to run, aborting:\n${job.exception}');
|
||||
exitCode = 1;
|
||||
break;
|
||||
} else {
|
||||
print('❌ Failures for ${job.name}:');
|
||||
print(job.result.stdout);
|
||||
}
|
||||
exitCode = 1;
|
||||
}
|
||||
print('\n');
|
||||
if (exitCode == 0) {
|
||||
print('No lint problems found.');
|
||||
} else {
|
||||
print('Lint problems found.');
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@ fi
|
||||
cd "$SCRIPT_DIR"
|
||||
"$DART" \
|
||||
--disable-dart-dev \
|
||||
bin/lint.dart \
|
||||
"$SRC_DIR/flutter/tools/clang_tidy/bin/main.dart" \
|
||||
--compile-commands="$COMPILE_COMMANDS" \
|
||||
--repo="$SRC_DIR/flutter" \
|
||||
"$@"
|
||||
|
||||
@@ -500,6 +500,23 @@ def RunGithooksTests(build_dir):
|
||||
cwd=test_dir)
|
||||
|
||||
|
||||
def RunClangTidyTests(build_dir):
|
||||
test_dir = os.path.join(buildroot_dir, 'flutter', 'tools', 'clang_tidy')
|
||||
dart_tests = glob.glob('%s/test/*_test.dart' % test_dir)
|
||||
for dart_test_file in dart_tests:
|
||||
opts = [
|
||||
'--disable-dart-dev',
|
||||
dart_test_file,
|
||||
os.path.join(build_dir, 'compile_commands.json'),
|
||||
os.path.join(buildroot_dir, 'flutter')]
|
||||
RunEngineExecutable(
|
||||
build_dir,
|
||||
os.path.join('dart-sdk', 'bin', 'dart'),
|
||||
None,
|
||||
flags=opts,
|
||||
cwd=test_dir)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
@@ -542,6 +559,7 @@ def main():
|
||||
RunDartSmokeTest(build_dir, args.verbose_dart_snapshot)
|
||||
RunLitetestTests(build_dir)
|
||||
RunGithooksTests(build_dir)
|
||||
RunClangTidyTests(build_dir)
|
||||
RunDartTests(build_dir, dart_filter, args.verbose_dart_snapshot)
|
||||
RunConstFinderTests(build_dir)
|
||||
RunFrontEndServerTests(build_dir)
|
||||
|
||||
9
engine/src/flutter/tools/clang_tidy/README.md
Normal file
9
engine/src/flutter/tools/clang_tidy/README.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# clang_tidy
|
||||
|
||||
This is a Dart program/library that runs clang_tidy over modified files. It
|
||||
takes two mandatory arguments that point at a compile_commands.json command
|
||||
and the root of the Flutter engine repo:
|
||||
|
||||
```
|
||||
$ bin/main.dart --compile-commands <compile_commands.json-path> --repo <path-to-repo>
|
||||
```
|
||||
19
engine/src/flutter/tools/clang_tidy/bin/main.dart
Normal file
19
engine/src/flutter/tools/clang_tidy/bin/main.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
// 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.
|
||||
|
||||
// @dart = 2.12
|
||||
|
||||
// Runs clang-tidy on files with changes.
|
||||
//
|
||||
// Basic Usage:
|
||||
// dart bin/main.dart --compile-commands <path to compile_commands.json> \
|
||||
// --repo <path to git repository> \
|
||||
//
|
||||
// User environment variable FLUTTER_LINT_ALL to run on all files.
|
||||
|
||||
import 'package:clang_tidy/clang_tidy.dart';
|
||||
|
||||
Future<int> main(List<String> arguments) async {
|
||||
return ClangTidy.fromCommandLine(arguments).run();
|
||||
}
|
||||
243
engine/src/flutter/tools/clang_tidy/lib/clang_tidy.dart
Normal file
243
engine/src/flutter/tools/clang_tidy/lib/clang_tidy.dart
Normal file
@@ -0,0 +1,243 @@
|
||||
// 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.
|
||||
|
||||
import 'dart:convert' show jsonDecode;
|
||||
import 'dart:io' as io show Directory, File, stdout, stderr;
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:process_runner/process_runner.dart';
|
||||
|
||||
import 'src/command.dart';
|
||||
import 'src/git_repo.dart';
|
||||
import 'src/options.dart';
|
||||
|
||||
const String _linterOutputHeader = '''
|
||||
┌──────────────────────────┐
|
||||
│ 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
|
||||
''';
|
||||
|
||||
class _ComputeJobsResult {
|
||||
_ComputeJobsResult(this.jobs, this.sawMalformed);
|
||||
|
||||
final List<WorkerJob> jobs;
|
||||
final bool sawMalformed;
|
||||
}
|
||||
|
||||
/// A class that runs clang-tidy on all or only the changed files in a git
|
||||
/// repo.
|
||||
class ClangTidy {
|
||||
/// Given the path to the build commands for a repo and its root, builds
|
||||
/// an instance of [ClangTidy].
|
||||
///
|
||||
/// `buildCommandsPath` is the path to the build_commands.json file.
|
||||
/// `repoPath` is the path to the Engine repo.
|
||||
/// `checksArg` are specific checks for clang-tidy to do.
|
||||
/// `lintAll` when true indicates that all files should be linted.
|
||||
/// `outSink` when provided is the destination for normal log messages, which
|
||||
/// will otherwise go to stdout.
|
||||
/// `errSink` when provided is the destination for error messages, which
|
||||
/// will otherwise go to stderr.
|
||||
ClangTidy({
|
||||
required io.File buildCommandsPath,
|
||||
required io.Directory repoPath,
|
||||
String checksArg = '',
|
||||
bool lintAll = false,
|
||||
StringSink? outSink,
|
||||
StringSink? errSink,
|
||||
}) :
|
||||
options = Options(
|
||||
buildCommandsPath: buildCommandsPath,
|
||||
repoPath: repoPath,
|
||||
checksArg: checksArg,
|
||||
lintAll: lintAll,
|
||||
errSink: errSink,
|
||||
),
|
||||
_outSink = outSink ?? io.stdout,
|
||||
_errSink = errSink ?? io.stderr;
|
||||
|
||||
/// Builds an instance of [ClangTidy] from a command line.
|
||||
ClangTidy.fromCommandLine(
|
||||
List<String> args, {
|
||||
StringSink? outSink,
|
||||
StringSink? errSink,
|
||||
}) :
|
||||
options = Options.fromCommandLine(args, errSink: errSink),
|
||||
_outSink = outSink ?? io.stdout,
|
||||
_errSink = errSink ?? io.stderr;
|
||||
|
||||
/// The [Options] that specify how this [ClangTidy] operates.
|
||||
final Options options;
|
||||
final StringSink _outSink;
|
||||
final StringSink _errSink;
|
||||
|
||||
/// Runs clang-tidy on the repo as specified by the [Options].
|
||||
Future<int> run() async {
|
||||
if (options.help) {
|
||||
options.printUsage();
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (options.errorMessage != null) {
|
||||
options.printUsage(message: options.errorMessage);
|
||||
return 1;
|
||||
}
|
||||
|
||||
_outSink.writeln(_linterOutputHeader);
|
||||
|
||||
final List<io.File> changedFiles = await computeChangedFiles();
|
||||
|
||||
if (options.verbose) {
|
||||
_outSink.writeln('Checking lint in repo at ${options.repoPath.path}.');
|
||||
if (options.checksArg.isNotEmpty) {
|
||||
_outSink.writeln('Checking for specific checks: ${options.checks}.');
|
||||
}
|
||||
final int changedFilesCount = changedFiles.length;
|
||||
if (options.lintAll) {
|
||||
_outSink.writeln('Checking all $changedFilesCount files the repo dir.');
|
||||
} else {
|
||||
_outSink.writeln(
|
||||
'Dectected $changedFilesCount files that have changed',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final List<Command> changedFileBuildCommands = getLintCommandsForChangedFiles(
|
||||
options.buildCommandsPath,
|
||||
changedFiles,
|
||||
);
|
||||
|
||||
if (changedFileBuildCommands.isEmpty) {
|
||||
_outSink.writeln(
|
||||
'No changed files that have build commands associated with them were '
|
||||
'found.',
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (options.verbose) {
|
||||
_outSink.writeln(
|
||||
'Found ${changedFileBuildCommands.length} files that have build '
|
||||
'commands associated with them and can be lint checked.',
|
||||
);
|
||||
}
|
||||
|
||||
final _ComputeJobsResult computeJobsResult = await _computeJobs(
|
||||
changedFileBuildCommands,
|
||||
options.repoPath,
|
||||
options.checks,
|
||||
);
|
||||
final int computeResult = computeJobsResult.sawMalformed ? 1 : 0;
|
||||
final List<WorkerJob> jobs = computeJobsResult.jobs;
|
||||
|
||||
final int runResult = await _runJobs(jobs);
|
||||
_outSink.writeln('\n');
|
||||
if (computeResult + runResult == 0) {
|
||||
_outSink.writeln('No lint problems found.');
|
||||
} else {
|
||||
_errSink.writeln('Lint problems found.');
|
||||
}
|
||||
|
||||
return computeResult + runResult > 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
/// The files with local modifications or all the files if `lintAll` was
|
||||
/// specified.
|
||||
@visibleForTesting
|
||||
Future<List<io.File>> computeChangedFiles() async {
|
||||
if (options.lintAll) {
|
||||
return options.repoPath
|
||||
.listSync(recursive: true)
|
||||
.whereType<io.File>()
|
||||
.toList();
|
||||
}
|
||||
return GitRepo(options.repoPath).changedFiles;
|
||||
}
|
||||
|
||||
/// Given a build commands json file, and the files with local changes,
|
||||
/// compute the lint commands to run.
|
||||
@visibleForTesting
|
||||
List<Command> getLintCommandsForChangedFiles(
|
||||
io.File buildCommandsPath,
|
||||
List<io.File> changedFiles,
|
||||
) {
|
||||
final List<dynamic> buildCommandMaps = jsonDecode(
|
||||
buildCommandsPath.readAsStringSync(),
|
||||
) as List<dynamic>;
|
||||
final List<Command> buildCommands = <Command>[
|
||||
for (final dynamic c in buildCommandMaps)
|
||||
Command.fromMap(c as Map<String, dynamic>),
|
||||
];
|
||||
|
||||
return <Command>[
|
||||
for (final Command c in buildCommands)
|
||||
if (c.containsAny(changedFiles))
|
||||
c,
|
||||
];
|
||||
}
|
||||
|
||||
Future<_ComputeJobsResult> _computeJobs(
|
||||
List<Command> commands,
|
||||
io.Directory repoPath,
|
||||
String checks,
|
||||
) async {
|
||||
bool sawMalformed = false;
|
||||
final List<WorkerJob> jobs = <WorkerJob>[];
|
||||
for (final Command command in commands) {
|
||||
final String relativePath = path.relative(
|
||||
command.filePath,
|
||||
from: repoPath.parent.path,
|
||||
);
|
||||
final LintAction action = await command.lintAction;
|
||||
switch (action) {
|
||||
case LintAction.skipNoLint:
|
||||
_outSink.writeln('🔷 ignoring $relativePath (FLUTTER_NOLINT)');
|
||||
break;
|
||||
case LintAction.failMalformedNoLint:
|
||||
_errSink.writeln('❌ malformed opt-out $relativePath');
|
||||
_errSink.writeln(
|
||||
' Required format: // FLUTTER_NOLINT: $issueUrlPrefix/ISSUE_ID',
|
||||
);
|
||||
sawMalformed = true;
|
||||
break;
|
||||
case LintAction.lint:
|
||||
_outSink.writeln('🔶 linting $relativePath');
|
||||
jobs.add(command.createLintJob(checks));
|
||||
break;
|
||||
case LintAction.skipThirdParty:
|
||||
_outSink.writeln('🔷 ignoring $relativePath (third_party)');
|
||||
break;
|
||||
}
|
||||
}
|
||||
return _ComputeJobsResult(jobs, sawMalformed);
|
||||
}
|
||||
|
||||
Future<int> _runJobs(List<WorkerJob> jobs) async {
|
||||
int result = 0;
|
||||
final ProcessPool pool = ProcessPool();
|
||||
await for (final WorkerJob job in pool.startWorkers(jobs)) {
|
||||
if (job.result.exitCode == 0) {
|
||||
continue;
|
||||
}
|
||||
if (job.exception != null) {
|
||||
_errSink.writeln(
|
||||
'\n❗ A clang-tidy job failed to run, aborting:\n${job.exception}',
|
||||
);
|
||||
result = 1;
|
||||
break;
|
||||
} else {
|
||||
_errSink.writeln('❌ Failures for ${job.name}:');
|
||||
_errSink.writeln(job.result.stdout);
|
||||
}
|
||||
result = 1;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
138
engine/src/flutter/tools/clang_tidy/lib/src/command.dart
Normal file
138
engine/src/flutter/tools/clang_tidy/lib/src/command.dart
Normal file
@@ -0,0 +1,138 @@
|
||||
// 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.
|
||||
|
||||
import 'dart:convert' show utf8, LineSplitter;
|
||||
import 'dart:io' as io;
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:process_runner/process_runner.dart';
|
||||
|
||||
/// The url prefix for issues that must be attached to the directive in files
|
||||
/// that disables linting.
|
||||
const String issueUrlPrefix = 'https://github.com/flutter/flutter/issues';
|
||||
|
||||
/// Lint actions to apply to a file.
|
||||
enum LintAction {
|
||||
/// Run the linter over the file.
|
||||
lint,
|
||||
|
||||
/// Ignore files under third_party/.
|
||||
skipThirdParty,
|
||||
|
||||
/// Ignore due to a well-formed FLUTTER_NOLINT comment.
|
||||
skipNoLint,
|
||||
|
||||
/// Fail due to a malformed FLUTTER_NOLINT comment.
|
||||
failMalformedNoLint,
|
||||
}
|
||||
|
||||
/// A compilation command and methods to generate the lint command and job for
|
||||
/// it.
|
||||
class Command {
|
||||
/// Generate a [Command] from a [Map].
|
||||
Command.fromMap(Map<String, dynamic> map) :
|
||||
directory = io.Directory(map['directory'] as String).absolute,
|
||||
command = map['command'] as String {
|
||||
filePath = path.normalize(path.join(
|
||||
directory.path,
|
||||
map['file'] as String,
|
||||
));
|
||||
}
|
||||
|
||||
/// The working directory of the command.
|
||||
final io.Directory directory;
|
||||
|
||||
/// The compilation command.
|
||||
final String command ;
|
||||
|
||||
/// The file on which the command operates.
|
||||
late final String filePath;
|
||||
|
||||
static final RegExp _pathRegex = RegExp(r'\S*clang/bin/clang');
|
||||
static final RegExp _argRegex = RegExp(r'-MF \S*');
|
||||
|
||||
String? _tidyArgs;
|
||||
|
||||
/// The command line arguments of the command.
|
||||
String get tidyArgs {
|
||||
return _tidyArgs ??= (() {
|
||||
String result = command;
|
||||
result = result.replaceAll(_pathRegex, '');
|
||||
result = result.replaceAll(_argRegex, '');
|
||||
return result;
|
||||
})();
|
||||
}
|
||||
|
||||
String? _tidyPath;
|
||||
|
||||
/// The command but with clang-tidy instead of clang.
|
||||
String get tidyPath {
|
||||
return _tidyPath ??= _pathRegex.stringMatch(command)?.replaceAll(
|
||||
'clang/bin/clang',
|
||||
'clang/bin/clang-tidy',
|
||||
) ?? '';
|
||||
}
|
||||
|
||||
/// Whether this command operates on any of the files in `queries`.
|
||||
bool containsAny(List<io.File> queries) {
|
||||
return queries.indexWhere(
|
||||
(io.File query) => path.equals(query.path, filePath),
|
||||
) != -1;
|
||||
}
|
||||
|
||||
static final RegExp _nolintRegex = RegExp(
|
||||
r'//\s*FLUTTER_NOLINT(: https://github.com/flutter/flutter/issues/\d+)?',
|
||||
);
|
||||
|
||||
LintAction? _lintAction;
|
||||
|
||||
/// The type of lint that is appropriate for this command.
|
||||
Future<LintAction> get lintAction async =>
|
||||
_lintAction ??= await getLintAction(filePath);
|
||||
|
||||
/// Determine the lint action for the file at `path`.
|
||||
@visibleForTesting
|
||||
static Future<LintAction> getLintAction(String filePath) {
|
||||
if (path.split(filePath).contains('third_party')) {
|
||||
return Future<LintAction>.value(LintAction.skipThirdParty);
|
||||
}
|
||||
|
||||
final io.File file = io.File(filePath);
|
||||
final Stream<String> lines = file.openRead()
|
||||
.transform(utf8.decoder)
|
||||
.transform(const LineSplitter());
|
||||
return lintActionFromContents(lines);
|
||||
}
|
||||
|
||||
/// Determine the lint action for the file with contents `lines`.
|
||||
@visibleForTesting
|
||||
static Future<LintAction> lintActionFromContents(Stream<String> lines) async {
|
||||
// Check for FlUTTER_NOLINT at top of file.
|
||||
await for (final String line in lines) {
|
||||
final RegExpMatch? match = _nolintRegex.firstMatch(line);
|
||||
if (match != null) {
|
||||
return match.group(1) != null
|
||||
? LintAction.skipNoLint
|
||||
: LintAction.failMalformedNoLint;
|
||||
} else if (line.isNotEmpty && line[0] != '\n' && line[0] != '/') {
|
||||
// Quick out once we find a line that isn't empty or a comment. The
|
||||
// FLUTTER_NOLINT must show up before the first real code.
|
||||
return LintAction.lint;
|
||||
}
|
||||
}
|
||||
return LintAction.lint;
|
||||
}
|
||||
|
||||
/// The job for the process runner for the lint needed for this command.
|
||||
WorkerJob createLintJob(String checks) {
|
||||
final List<String> args = <String>[filePath, checks, '--'];
|
||||
args.addAll(tidyArgs.split(' '));
|
||||
return WorkerJob(
|
||||
<String>[tidyPath, ...args],
|
||||
workingDirectory: directory,
|
||||
name: 'clang-tidy on $filePath',
|
||||
);
|
||||
}
|
||||
}
|
||||
74
engine/src/flutter/tools/clang_tidy/lib/src/git_repo.dart
Normal file
74
engine/src/flutter/tools/clang_tidy/lib/src/git_repo.dart
Normal file
@@ -0,0 +1,74 @@
|
||||
// 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.
|
||||
|
||||
import 'dart:io' as io show Directory, File;
|
||||
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:process_runner/process_runner.dart';
|
||||
|
||||
/// Utility methods for working with a git repo.
|
||||
class GitRepo {
|
||||
/// The git repository rooted at `root`.
|
||||
GitRepo(this.root);
|
||||
|
||||
/// The root of the git repo.
|
||||
final io.Directory root;
|
||||
|
||||
List<io.File>? _changedFiles;
|
||||
|
||||
/// Returns a list of all non-deleted files which differ from the nearest
|
||||
/// merge-base with `master`. If it can't find a fork point, uses the default
|
||||
/// merge-base.
|
||||
///
|
||||
/// This is only computed once and cached. Subsequent invocations of the
|
||||
/// getter will return the same result.
|
||||
Future<List<io.File>> get changedFiles async =>
|
||||
_changedFiles ??= await _getChangedFiles();
|
||||
|
||||
Future<List<io.File>> _getChangedFiles() async {
|
||||
final ProcessRunner processRunner = ProcessRunner(
|
||||
defaultWorkingDirectory: root,
|
||||
);
|
||||
final ProcessRunnerResult fetchResult = await processRunner.runProcess(
|
||||
<String>['git', 'fetch', 'upstream', 'master'],
|
||||
failOk: true,
|
||||
);
|
||||
if (fetchResult.exitCode != 0) {
|
||||
await processRunner.runProcess(<String>[
|
||||
'git',
|
||||
'fetch',
|
||||
'origin',
|
||||
'master',
|
||||
]);
|
||||
}
|
||||
final Set<String> result = <String>{};
|
||||
ProcessRunnerResult mergeBaseResult = await processRunner.runProcess(
|
||||
<String>['git', 'merge-base', '--fork-point', 'FETCH_HEAD', 'HEAD'],
|
||||
failOk: true,
|
||||
);
|
||||
if (mergeBaseResult.exitCode != 0) {
|
||||
mergeBaseResult = await processRunner.runProcess(<String>[
|
||||
'git',
|
||||
'merge-base',
|
||||
'FETCH_HEAD',
|
||||
'HEAD',
|
||||
], failOk: false);
|
||||
}
|
||||
final String mergeBase = mergeBaseResult.stdout.trim();
|
||||
final ProcessRunnerResult masterResult = await processRunner
|
||||
.runProcess(<String>[
|
||||
'git',
|
||||
'diff',
|
||||
'--name-only',
|
||||
'--diff-filter=ACMRT',
|
||||
mergeBase,
|
||||
]);
|
||||
result.addAll(masterResult.stdout.split('\n').where(
|
||||
(String str) => str.isNotEmpty,
|
||||
));
|
||||
return result.map<io.File>(
|
||||
(String filePath) => io.File(path.join(root.path, filePath)),
|
||||
).toList();
|
||||
}
|
||||
}
|
||||
182
engine/src/flutter/tools/clang_tidy/lib/src/options.dart
Normal file
182
engine/src/flutter/tools/clang_tidy/lib/src/options.dart
Normal file
@@ -0,0 +1,182 @@
|
||||
// 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.
|
||||
|
||||
import 'dart:io' as io show Directory, File, Platform, stderr;
|
||||
|
||||
import 'package:args/args.dart';
|
||||
|
||||
/// A class for organizing the options to the Engine linter, and the files
|
||||
/// that it operates on.
|
||||
class Options {
|
||||
/// Builds an instance of [Options] from the arguments.
|
||||
Options({
|
||||
required this.buildCommandsPath,
|
||||
required this.repoPath,
|
||||
this.help = false,
|
||||
this.verbose = false,
|
||||
this.checksArg = '',
|
||||
this.lintAll = false,
|
||||
this.errorMessage,
|
||||
StringSink? errSink,
|
||||
}) {
|
||||
checks = checksArg.isNotEmpty ? '--checks=$checksArg' : '--config=';
|
||||
_errSink = errSink ?? io.stderr;
|
||||
}
|
||||
|
||||
factory Options._error(
|
||||
String message, {
|
||||
StringSink? errSink,
|
||||
}) {
|
||||
return Options(
|
||||
errorMessage: message,
|
||||
buildCommandsPath: io.File('none'),
|
||||
repoPath: io.Directory('none'),
|
||||
errSink: errSink,
|
||||
);
|
||||
}
|
||||
|
||||
factory Options._help({
|
||||
StringSink? errSink,
|
||||
}) {
|
||||
return Options(
|
||||
help: true,
|
||||
buildCommandsPath: io.File('none'),
|
||||
repoPath: io.Directory('none'),
|
||||
errSink: errSink,
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds an [Options] instance with an [ArgResults] instance.
|
||||
factory Options._fromArgResults(
|
||||
ArgResults options, {
|
||||
StringSink? errSink,
|
||||
}) {
|
||||
return Options(
|
||||
help: options['help'] as bool,
|
||||
verbose: options['verbose'] as bool,
|
||||
buildCommandsPath: io.File(options['compile-commands'] as String),
|
||||
repoPath: io.Directory(options['repo'] as String),
|
||||
checksArg: options.wasParsed('checks') ? options['checks'] as String : '',
|
||||
lintAll: io.Platform.environment['FLUTTER_LINT_ALL'] != null ||
|
||||
options['lint-all'] as bool,
|
||||
errSink: errSink,
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds an instance of [Options] from the given `arguments`.
|
||||
factory Options.fromCommandLine(
|
||||
List<String> arguments, {
|
||||
StringSink? errSink,
|
||||
}) {
|
||||
final ArgResults argResults = _argParser.parse(arguments);
|
||||
final String? message = _checkArguments(argResults);
|
||||
if (message != null) {
|
||||
return Options._error(message, errSink: errSink);
|
||||
}
|
||||
if (argResults['help'] as bool) {
|
||||
return Options._help(errSink: errSink);
|
||||
}
|
||||
return Options._fromArgResults(
|
||||
argResults,
|
||||
errSink: errSink,
|
||||
);
|
||||
}
|
||||
|
||||
static final ArgParser _argParser = ArgParser()
|
||||
..addFlag(
|
||||
'help',
|
||||
help: 'Print help.',
|
||||
)
|
||||
..addFlag(
|
||||
'lint-all',
|
||||
help: 'lint all of the sources, regardless of FLUTTER_NOLINT.',
|
||||
defaultsTo: false,
|
||||
)
|
||||
..addFlag(
|
||||
'verbose',
|
||||
help: 'Print verbose output.',
|
||||
defaultsTo: false,
|
||||
)
|
||||
..addOption(
|
||||
'repo',
|
||||
help: 'Use the given path as the repo path',
|
||||
)
|
||||
..addOption(
|
||||
'compile-commands',
|
||||
help: 'Use the given path as the source of compile_commands.json. This '
|
||||
'file is created by running tools/gn',
|
||||
)
|
||||
..addOption(
|
||||
'checks',
|
||||
help: 'Perform the given checks on the code. Defaults to the empty '
|
||||
'string, indicating all checks should be performed.',
|
||||
defaultsTo: '',
|
||||
);
|
||||
|
||||
/// Whether to print a help message and exit.
|
||||
final bool help;
|
||||
|
||||
/// Whether to run with verbose output.
|
||||
final bool verbose;
|
||||
|
||||
/// The location of the compile_commands.json file.
|
||||
final io.File buildCommandsPath;
|
||||
|
||||
/// The root of the flutter/engine repository.
|
||||
final io.Directory repoPath;
|
||||
|
||||
/// Arguments to plumb through to clang-tidy formatted as a command line
|
||||
/// argument.
|
||||
final String checksArg;
|
||||
|
||||
/// Check arguments to plumb through to clang-tidy.
|
||||
late final String checks;
|
||||
|
||||
/// Whether all files should be linted.
|
||||
final bool lintAll;
|
||||
|
||||
/// If there was a problem with the command line arguments, this string
|
||||
/// contains the error message.
|
||||
final String? errorMessage;
|
||||
|
||||
late final StringSink _errSink;
|
||||
|
||||
/// Print command usage with an additional message.
|
||||
void printUsage({String? message}) {
|
||||
if (message != null) {
|
||||
_errSink.writeln(message);
|
||||
}
|
||||
_errSink.writeln(
|
||||
'Usage: bin/main.dart [--help] [--lint-all] [--verbose] [--diff-branch]',
|
||||
);
|
||||
_errSink.writeln(_argParser.usage);
|
||||
}
|
||||
|
||||
/// Command line argument validation.
|
||||
static String? _checkArguments(ArgResults argResults) {
|
||||
if (argResults.wasParsed('help')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!argResults.wasParsed('compile-commands')) {
|
||||
return 'ERROR: The --compile-commands argument is required.';
|
||||
}
|
||||
|
||||
if (!argResults.wasParsed('repo')) {
|
||||
return 'ERROR: The --repo argument is required.';
|
||||
}
|
||||
|
||||
final io.File buildCommandsPath = io.File(argResults['compile-commands'] as String);
|
||||
if (!buildCommandsPath.existsSync()) {
|
||||
return "ERROR: Build commands path ${buildCommandsPath.absolute.path} doesn't exist.";
|
||||
}
|
||||
|
||||
final io.Directory repoPath = io.Directory(argResults['repo'] as String);
|
||||
if (!repoPath.existsSync()) {
|
||||
return "ERROR: Repo path ${repoPath.absolute.path} doesn't exist.";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
54
engine/src/flutter/tools/clang_tidy/pubspec.yaml
Normal file
54
engine/src/flutter/tools/clang_tidy/pubspec.yaml
Normal file
@@ -0,0 +1,54 @@
|
||||
# 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.
|
||||
|
||||
name: clang_tidy
|
||||
publish_to: none
|
||||
environment:
|
||||
sdk: '>=2.12.0-0 <3.0.0'
|
||||
|
||||
# Do not add any dependencies that require more than what is provided in
|
||||
# //third_party/pkg, //third_party/dart/pkg, or
|
||||
# //third_party/dart/third_party/pkg. In particular, package:test is not usable
|
||||
# here.
|
||||
|
||||
# If you do add packages here, make sure you can run `pub get --offline`, and
|
||||
# check the .packages and .package_config to make sure all the paths are
|
||||
# relative to this directory into //third_party/dart
|
||||
|
||||
dependencies:
|
||||
args: any
|
||||
meta: any
|
||||
path: any
|
||||
process_runner: any
|
||||
|
||||
dev_dependencies:
|
||||
async_helper: any
|
||||
expect: any
|
||||
litetest: any
|
||||
|
||||
dependency_overrides:
|
||||
args:
|
||||
path: ../../../third_party/dart/third_party/pkg/args
|
||||
async:
|
||||
path: ../../../third_party/dart/third_party/pkg/async
|
||||
async_helper:
|
||||
path: ../../../third_party/dart/pkg/async_helper
|
||||
collection:
|
||||
path: ../../../third_party/dart/third_party/pkg/collection
|
||||
expect:
|
||||
path: ../../../third_party/dart/pkg/expect
|
||||
file:
|
||||
path: ../../../third_party/pkg/file/packages/file
|
||||
litetest:
|
||||
path: ../../testing/litetest
|
||||
meta:
|
||||
path: ../../../third_party/dart/pkg/meta
|
||||
path:
|
||||
path: ../../../third_party/dart/third_party/pkg/path
|
||||
platform:
|
||||
path: ../../../third_party/pkg/platform
|
||||
process:
|
||||
path: ../../../third_party/pkg/process
|
||||
process_runner:
|
||||
path: ../../../third_party/pkg/process_runner
|
||||
248
engine/src/flutter/tools/clang_tidy/test/clang_tidy_test.dart
Normal file
248
engine/src/flutter/tools/clang_tidy/test/clang_tidy_test.dart
Normal file
@@ -0,0 +1,248 @@
|
||||
// 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.
|
||||
|
||||
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:litetest/litetest.dart';
|
||||
|
||||
Future<int> main(List<String> args) async {
|
||||
if (args.length < 2) {
|
||||
io.stderr.writeln(
|
||||
'Usage: clang_tidy_test.dart [build commands] [repo root]',
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
final String buildCommands = args[0];
|
||||
final String repoRoot = args[1];
|
||||
|
||||
test('--help gives help', () async {
|
||||
final StringBuffer outBuffer = StringBuffer();
|
||||
final StringBuffer errBuffer = StringBuffer();
|
||||
final ClangTidy clangTidy = ClangTidy.fromCommandLine(
|
||||
<String>[
|
||||
'--help',
|
||||
],
|
||||
outSink: outBuffer,
|
||||
errSink: errBuffer,
|
||||
);
|
||||
|
||||
final int result = await clangTidy.run();
|
||||
|
||||
expect(clangTidy.options.help, isTrue);
|
||||
expect(result, equals(0));
|
||||
expect(errBuffer.toString(), contains('Usage: '));
|
||||
});
|
||||
|
||||
test('Error when --compile-commands is missing', () async {
|
||||
final StringBuffer outBuffer = StringBuffer();
|
||||
final StringBuffer errBuffer = StringBuffer();
|
||||
final ClangTidy clangTidy = ClangTidy.fromCommandLine(
|
||||
<String>[],
|
||||
outSink: outBuffer,
|
||||
errSink: errBuffer,
|
||||
);
|
||||
|
||||
final int result = await clangTidy.run();
|
||||
|
||||
expect(clangTidy.options.help, isFalse);
|
||||
expect(result, equals(1));
|
||||
expect(errBuffer.toString(), contains(
|
||||
'ERROR: The --compile-commands argument is required.',
|
||||
));
|
||||
});
|
||||
|
||||
test('Error when --repo is missing', () async {
|
||||
final StringBuffer outBuffer = StringBuffer();
|
||||
final StringBuffer errBuffer = StringBuffer();
|
||||
final ClangTidy clangTidy = ClangTidy.fromCommandLine(
|
||||
<String>[
|
||||
'--compile-commands',
|
||||
'/unused',
|
||||
],
|
||||
outSink: outBuffer,
|
||||
errSink: errBuffer,
|
||||
);
|
||||
|
||||
final int result = await clangTidy.run();
|
||||
|
||||
expect(clangTidy.options.help, isFalse);
|
||||
expect(result, equals(1));
|
||||
expect(errBuffer.toString(), contains(
|
||||
'ERROR: The --repo argument is required.',
|
||||
));
|
||||
});
|
||||
|
||||
test('Error when --compile-commands path does not exist', () async {
|
||||
final StringBuffer outBuffer = StringBuffer();
|
||||
final StringBuffer errBuffer = StringBuffer();
|
||||
final ClangTidy clangTidy = ClangTidy.fromCommandLine(
|
||||
<String>[
|
||||
'--compile-commands',
|
||||
'/does/not/exist',
|
||||
'--repo',
|
||||
'/unused',
|
||||
],
|
||||
outSink: outBuffer,
|
||||
errSink: errBuffer,
|
||||
);
|
||||
|
||||
final int result = await clangTidy.run();
|
||||
|
||||
expect(clangTidy.options.help, isFalse);
|
||||
expect(result, equals(1));
|
||||
expect(errBuffer.toString(), contains(
|
||||
"ERROR: Build commands path /does/not/exist doesn't exist.",
|
||||
));
|
||||
});
|
||||
|
||||
test('Error when --repo path does not exist', () async {
|
||||
final StringBuffer outBuffer = StringBuffer();
|
||||
final StringBuffer errBuffer = StringBuffer();
|
||||
final ClangTidy clangTidy = ClangTidy.fromCommandLine(
|
||||
<String>[
|
||||
'--compile-commands',
|
||||
// This just has to exist.
|
||||
io.Platform.executable,
|
||||
'--repo',
|
||||
'/does/not/exist',
|
||||
],
|
||||
outSink: outBuffer,
|
||||
errSink: errBuffer,
|
||||
);
|
||||
|
||||
final int result = await clangTidy.run();
|
||||
|
||||
expect(clangTidy.options.help, isFalse);
|
||||
expect(result, equals(1));
|
||||
expect(errBuffer.toString(), contains(
|
||||
"ERROR: Repo path /does/not/exist doesn't exist.",
|
||||
));
|
||||
});
|
||||
|
||||
test('lintAll=true checks all files', () async {
|
||||
final StringBuffer outBuffer = StringBuffer();
|
||||
final StringBuffer errBuffer = StringBuffer();
|
||||
final ClangTidy clangTidy = ClangTidy(
|
||||
buildCommandsPath: io.File(buildCommands),
|
||||
repoPath: io.Directory(repoRoot),
|
||||
lintAll: true,
|
||||
outSink: outBuffer,
|
||||
errSink: errBuffer,
|
||||
);
|
||||
final List<io.File> fileList = await clangTidy.computeChangedFiles();
|
||||
expect(fileList.length, greaterThan(1000));
|
||||
});
|
||||
|
||||
test('lintAll=false does not check all files', () async {
|
||||
final StringBuffer outBuffer = StringBuffer();
|
||||
final StringBuffer errBuffer = StringBuffer();
|
||||
final ClangTidy clangTidy = ClangTidy(
|
||||
buildCommandsPath: io.File(buildCommands),
|
||||
repoPath: io.Directory(repoRoot),
|
||||
outSink: outBuffer,
|
||||
errSink: errBuffer,
|
||||
);
|
||||
final List<io.File> fileList = await clangTidy.computeChangedFiles();
|
||||
expect(fileList.length, lessThan(300));
|
||||
});
|
||||
|
||||
test('No Commands are produced when no files changed', () async {
|
||||
final StringBuffer outBuffer = StringBuffer();
|
||||
final StringBuffer errBuffer = StringBuffer();
|
||||
final ClangTidy clangTidy = ClangTidy(
|
||||
buildCommandsPath: io.File(buildCommands),
|
||||
repoPath: io.Directory(repoRoot),
|
||||
lintAll: true,
|
||||
outSink: outBuffer,
|
||||
errSink: errBuffer,
|
||||
);
|
||||
final List<Command> commands = clangTidy.getLintCommandsForChangedFiles(
|
||||
clangTidy.options.buildCommandsPath,
|
||||
<io.File>[],
|
||||
);
|
||||
|
||||
expect(commands, isEmpty);
|
||||
});
|
||||
|
||||
test('A Command is produced when a file is changed', () async {
|
||||
final StringBuffer outBuffer = StringBuffer();
|
||||
final StringBuffer errBuffer = StringBuffer();
|
||||
final ClangTidy clangTidy = ClangTidy(
|
||||
buildCommandsPath: io.File(buildCommands),
|
||||
repoPath: io.Directory(repoRoot),
|
||||
lintAll: true,
|
||||
outSink: outBuffer,
|
||||
errSink: errBuffer,
|
||||
);
|
||||
final List<io.File> fileList = await clangTidy.computeChangedFiles();
|
||||
final io.File file = fileList.firstWhere((io.File f) {
|
||||
return f.path.endsWith('.cc');
|
||||
});
|
||||
final List<Command> commands = clangTidy.getLintCommandsForChangedFiles(
|
||||
clangTidy.options.buildCommandsPath,
|
||||
<io.File>[file],
|
||||
);
|
||||
|
||||
expect(commands, isNotEmpty);
|
||||
expect(commands.first.tidyPath, contains('clang/bin/clang-tidy'));
|
||||
});
|
||||
|
||||
test('Command getLintAction flags third_party files', () async {
|
||||
final LintAction lintAction = await Command.getLintAction(
|
||||
'/some/file/in/a/third_party/dependency',
|
||||
);
|
||||
|
||||
expect(lintAction, equals(LintAction.skipThirdParty));
|
||||
});
|
||||
|
||||
test('Command getLintActionFromContents flags FLUTTER_NOLINT', () async {
|
||||
final LintAction lintAction = await Command.lintActionFromContents(
|
||||
Stream<String>.fromIterable(<String>[
|
||||
'// Copyright 2013 The Flutter Authors. All rights reserved.\n',
|
||||
'// Use of this source code is governed by a BSD-style license that can be\n',
|
||||
'// found in the LICENSE file.\n',
|
||||
'\n',
|
||||
'// FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/68332\n',
|
||||
'\n',
|
||||
'#include "flutter/shell/version/version.h"\n',
|
||||
]),
|
||||
);
|
||||
|
||||
expect(lintAction, equals(LintAction.skipNoLint));
|
||||
});
|
||||
|
||||
test('Command getLintActionFromContents flags malformed FLUTTER_NOLINT', () async {
|
||||
final LintAction lintAction = await Command.lintActionFromContents(
|
||||
Stream<String>.fromIterable(<String>[
|
||||
'// Copyright 2013 The Flutter Authors. All rights reserved.\n',
|
||||
'// Use of this source code is governed by a BSD-style license that can be\n',
|
||||
'// found in the LICENSE file.\n',
|
||||
'\n',
|
||||
'// FLUTTER_NOLINT: https://gir/flutter/issues/68332\n',
|
||||
'\n',
|
||||
'#include "flutter/shell/version/version.h"\n',
|
||||
]),
|
||||
);
|
||||
|
||||
expect(lintAction, equals(LintAction.failMalformedNoLint));
|
||||
});
|
||||
|
||||
test('Command getLintActionFromContents flags that we should lint', () async {
|
||||
final LintAction lintAction = await Command.lintActionFromContents(
|
||||
Stream<String>.fromIterable(<String>[
|
||||
'// Copyright 2013 The Flutter Authors. All rights reserved.\n',
|
||||
'// Use of this source code is governed by a BSD-style license that can be\n',
|
||||
'// found in the LICENSE file.\n',
|
||||
'\n',
|
||||
'#include "flutter/shell/version/version.h"\n',
|
||||
]),
|
||||
);
|
||||
|
||||
expect(lintAction, equals(LintAction.lint));
|
||||
});
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -22,6 +22,7 @@ ALL_PACKAGES = [
|
||||
os.path.join("src", "flutter", "testing", "smoke_test_failure"),
|
||||
os.path.join("src", "flutter", "testing", "symbols"),
|
||||
os.path.join("src", "flutter", "tools", "android_lint"),
|
||||
os.path.join("src", "flutter", "tools", "clang_tidy"),
|
||||
os.path.join("src", "flutter", "tools", "const_finder"),
|
||||
os.path.join("src", "flutter", "tools", "githooks"),
|
||||
os.path.join("src", "flutter", "tools", "licenses"),
|
||||
|
||||
Reference in New Issue
Block a user