Switch document generation to use the snippets package (#87231)

Switch document generation to use the snippets package instead of the snippets code in the Flutter repo. In the process, some bugs in sample code analysis have been fixed, and I've fixed some more errors in the samples.

This will allow the snippets package to be developed separately from the Flutter repo, and reduce the code in the Flutter repo.

The snippets code is deleted in this PR.

I also converted some comments in the snippet templates to be regular comments instead of doc comments, because having a doc comment block before the imports causes the Dart import sorter to lose the comment. They should have been regular comments in the first place.

The snippets package resides in the assets-for-api-docs repo.

The sample analysis has also been converted to be run in parallel, and I've bumped the Dartdoc version to 1.0.2.
This commit is contained in:
Greg Spencer
2021-08-11 19:48:29 -07:00
committed by GitHub
parent 0340319a96
commit 10e4b04010
47 changed files with 347 additions and 1378 deletions

View File

@@ -7,8 +7,10 @@
// To run this, from the root of the Flutter repository:
// bin/cache/dart-sdk/bin/dart dev/bots/analyze_sample_code.dart
// @dart= 2.12
// @dart= 2.14
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
@@ -16,12 +18,22 @@ import 'package:args/args.dart';
import 'package:path/path.dart' as path;
import 'package:watcher/watcher.dart';
// If you update this version, also update it in dev/bots/docs.sh
const String _snippetsActivateVersion = '0.2.2';
final String _flutterRoot = path.dirname(path.dirname(path.dirname(path.fromUri(Platform.script))));
final String _defaultFlutterPackage = path.join(_flutterRoot, 'packages', 'flutter', 'lib');
final String _defaultDartUiLocation = path.join(_flutterRoot, 'bin', 'cache', 'pkg', 'sky_engine', 'lib', 'ui');
final String _flutter = path.join(_flutterRoot, 'bin', Platform.isWindows ? 'flutter.bat' : 'flutter');
void main(List<String> arguments) {
/// Finds the location of the pub executable, with the assumption that it is
/// in the same location as the Dart executable used to run this script.
String get _pubExecutable {
final File dartExecutable = File(Platform.resolvedExecutable);
return path.join(path.dirname(dartExecutable.absolute.path), Platform.isWindows ? 'pub.exe' : 'pub');
}
Future<void> main(List<String> arguments) async {
final ArgParser argParser = ArgParser();
argParser.addOption(
'temp',
@@ -61,6 +73,13 @@ void main(List<String> arguments) {
abbr: 'i',
help: 'Analyzes the sample code in the specified file interactively.',
);
argParser.addFlag(
'global-activate-snippets',
defaultsTo: true,
negatable: true,
help: 'Whether or not to "pub global activate" the snippets package. If set, will '
'activate version $_snippetsActivateVersion',
);
final ArgResults parsedArguments = argParser.parse(arguments);
@@ -107,8 +126,25 @@ void main(List<String> arguments) {
tempDirectory.createSync();
}
if (parsedArguments['global-activate-snippets']! as bool) {
try {
Process.runSync(
_pubExecutable,
<String>[
'global',
'activate',
'snippets',
_snippetsActivateVersion,
],
workingDirectory: _flutterRoot,
);
} on ProcessException catch (e) {
stderr.writeln('Unable to global activate snippets package at version $_snippetsActivateVersion: $e');
exit(1);
}
}
if (parsedArguments['interactive'] != null) {
_runInteractive(
await _runInteractive(
tempDir: tempDirectory,
flutterPackage: flutterPackage,
filePath: parsedArguments['interactive'] as String,
@@ -116,7 +152,7 @@ void main(List<String> arguments) {
);
} else {
try {
exitCode = SampleChecker(
exitCode = await SampleChecker(
flutterPackage,
tempDirectory: tempDirectory,
verbose: parsedArguments['verbose'] as bool,
@@ -129,6 +165,95 @@ void main(List<String> arguments) {
}
}
typedef TaskQueueClosure<T> = Future<T> Function();
class _TaskQueueItem<T> {
_TaskQueueItem(this._closure, this._completer, {this.onComplete});
final TaskQueueClosure<T> _closure;
final Completer<T> _completer;
void Function()? onComplete;
Future<void> run() async {
try {
_completer.complete(await _closure());
} catch (e) {
_completer.completeError(e);
} finally {
onComplete?.call();
}
}
}
/// A task queue of Futures to be completed in parallel, throttling
/// the number of simultaneous tasks.
///
/// The tasks return results of type T.
class TaskQueue<T> {
/// Creates a task queue with a maximum number of simultaneous jobs.
/// The [maxJobs] parameter defaults to the number of CPU cores on the
/// system.
TaskQueue({int? maxJobs})
: maxJobs = maxJobs ?? Platform.numberOfProcessors;
/// The maximum number of jobs that this queue will run simultaneously.
final int maxJobs;
final Queue<_TaskQueueItem<T>> _pendingTasks = Queue<_TaskQueueItem<T>>();
final Set<_TaskQueueItem<T>> _activeTasks = <_TaskQueueItem<T>>{};
final Set<Completer<void>> _completeListeners = <Completer<void>>{};
/// Returns a future that completes when all tasks in the [TaskQueue] are
/// complete.
Future<void> get tasksComplete {
// In case this is called when there are no tasks, we want it to
// signal complete immediately.
if (_activeTasks.isEmpty && _pendingTasks.isEmpty) {
return Future<void>.value();
}
final Completer<void> completer = Completer<void>();
_completeListeners.add(completer);
return completer.future;
}
/// Adds a single closure to the task queue, returning a future that
/// completes when the task completes.
Future<T> add(TaskQueueClosure<T> task) {
final Completer<T> completer = Completer<T>();
_pendingTasks.add(_TaskQueueItem<T>(task, completer));
if (_activeTasks.length < maxJobs) {
_processTask();
}
return completer.future;
}
// Process a single task.
void _processTask() {
if (_pendingTasks.isNotEmpty && _activeTasks.length <= maxJobs) {
final _TaskQueueItem<T> item = _pendingTasks.removeFirst();
_activeTasks.add(item);
item.onComplete = () {
_activeTasks.remove(item);
_processTask();
};
item.run();
} else {
_checkForCompletion();
}
}
void _checkForCompletion() {
if (_activeTasks.isEmpty && _pendingTasks.isEmpty) {
for (final Completer<void> completer in _completeListeners) {
if (!completer.isCompleted) {
completer.complete();
}
}
_completeListeners.clear();
}
}
}
class SampleCheckerException implements Exception {
SampleCheckerException(this.message, {this.file, this.line});
final String message;
@@ -147,6 +272,12 @@ class SampleCheckerException implements Exception {
}
}
class AnalysisResult {
const AnalysisResult(this.exitCode, this.errors);
final int exitCode;
final Map<String, List<AnalysisError>> errors;
}
/// Checks samples and code snippets for analysis errors.
///
/// Extracts dartdoc content from flutter package source code, identifies code
@@ -237,25 +368,6 @@ class SampleChecker {
/// generate them.
int _expressionId = 0;
/// The exit code from the analysis process.
int _exitCode = 0;
// Once the snippets tool has been precompiled by Dart, this contains the AOT
// snapshot.
String? _snippetsSnapshotPath;
/// Finds the location of the snippets script.
String get _snippetsExecutable {
final String platformScriptPath = path.dirname(path.fromUri(Platform.script));
return path.canonicalize(path.join(platformScriptPath, '..', 'snippets', 'lib', 'main.dart'));
}
/// Finds the location of the Dart executable.
String get _dartExecutable {
final File dartExecutable = File(Platform.resolvedExecutable);
return dartExecutable.absolute.path;
}
static List<File> _listDartFiles(Directory directory, {bool recursive = false}) {
return directory.listSync(recursive: recursive, followLinks: false).whereType<File>().where((File file) => path.extension(file.path) == '.dart').toList();
}
@@ -282,9 +394,8 @@ class SampleChecker {
List<Line>? _headers;
/// Checks all the samples in the Dart files in [_flutterPackage] for errors.
int checkSamples() {
_exitCode = 0;
Map<String, List<AnalysisError>> errors = <String, List<AnalysisError>>{};
Future<int> checkSamples() async {
AnalysisResult? analysisResult;
try {
final Map<String, Section> sections = <String, Section>{};
final Map<String, Sample> snippets = <String, Sample>{};
@@ -295,14 +406,14 @@ class SampleChecker {
..._listDartFiles(_flutterPackage, recursive: true),
if (_dartUiLocation != null && _dartUiLocation!.existsSync()) ... _listDartFiles(_dartUiLocation!, recursive: true),
];
_extractSamples(filesToAnalyze, sectionMap: sections, sampleMap: snippets);
errors = _analyze(_tempDirectory, sections, snippets);
await _extractSamples(filesToAnalyze, sectionMap: sections, sampleMap: snippets);
analysisResult = _analyze(_tempDirectory, sections, snippets);
} finally {
if (errors.isNotEmpty) {
for (final String filePath in errors.keys) {
errors[filePath]!.forEach(stderr.writeln);
if (analysisResult != null && analysisResult.errors.isNotEmpty) {
for (final String filePath in analysisResult.errors.keys) {
analysisResult.errors[filePath]!.forEach(stderr.writeln);
}
stderr.writeln('\nFound ${errors.length} sample code errors.');
stderr.writeln('\nFound ${analysisResult.errors.length} sample code errors.');
}
if (_keepTmp) {
print('Leaving temporary directory ${_tempDirectory.path} around for your perusal.');
@@ -313,15 +424,8 @@ class SampleChecker {
stderr.writeln('Failed to delete ${_tempDirectory.path}: $e');
}
}
// If we made a snapshot, remove it (so as not to clutter up the tree).
if (_snippetsSnapshotPath != null) {
final File snapshot = File(_snippetsSnapshotPath!);
if (snapshot.existsSync()) {
snapshot.deleteSync();
}
}
}
return _exitCode;
return analysisResult.exitCode;
}
/// Creates a name for the snippets tool to use for the snippet ID from a
@@ -333,37 +437,37 @@ class SampleChecker {
return sampleId;
}
// Precompiles the snippets tool if _snippetsSnapshotPath isn't set yet, and
// runs the precompiled version if it is set.
ProcessResult _runSnippetsScript(List<String> args) {
// The cached JSON Flutter version information from 'flutter --version --machine'.
String? _flutterVersion;
Future<ProcessResult> _runSnippetsScript(List<String> args) async {
final String workingDirectory = path.join(_flutterRoot, 'dev', 'docs');
if (_snippetsSnapshotPath == null) {
_snippetsSnapshotPath = '$_snippetsExecutable.snapshot';
return Process.runSync(
_dartExecutable,
<String>[
'--snapshot=$_snippetsSnapshotPath',
'--snapshot-kind=app-jit',
path.canonicalize(_snippetsExecutable),
...args,
],
workingDirectory: workingDirectory,
);
} else {
return Process.runSync(
_dartExecutable,
<String>[
path.canonicalize(_snippetsSnapshotPath!),
...args,
],
workingDirectory: workingDirectory,
);
if (_flutterVersion == null) {
// Capture the flutter version information once so that the snippets tool doesn't
// have to run it for every snippet.
final ProcessResult versionResult = Process.runSync(_flutter, <String>['--version', '--machine']);
_flutterVersion = versionResult.stdout as String? ?? '';
}
return Process.run(
_pubExecutable,
<String>[
'global',
'run',
'snippets',
...args,
],
workingDirectory: workingDirectory,
environment: <String, String>{
if (!Platform.environment.containsKey('FLUTTER_ROOT')) 'FLUTTER_ROOT': _flutterRoot,
if (_flutterVersion!.isNotEmpty) 'FLUTTER_VERSION': _flutterVersion!,
},
includeParentEnvironment: true,
);
}
/// Writes out the given sample to an output file in the [_tempDirectory] and
/// returns the output file.
File _writeSample(Sample sample) {
Future<File> _writeSample(Sample sample) async {
// Generate the snippet.
final String sampleId = _createNameFromSource('sample', sample.start.filename, sample.start.line);
final String inputName = '$sampleId.input';
@@ -374,11 +478,14 @@ class SampleChecker {
final List<String> args = <String>[
'--output=${outputFile.absolute.path}',
'--input=${inputFile.absolute.path}',
// Formatting the output will fail on analysis errors, and we want it to fail
// here, not there.
'--no-format-output',
...sample.args,
];
if (verbose)
print('Generating sample for ${sample.start.filename}:${sample.start.line}');
final ProcessResult process = _runSnippetsScript(args);
final ProcessResult process = await _runSnippetsScript(args);
if (verbose)
stderr.write('${process.stderr}');
if (process.exitCode != 0) {
@@ -394,12 +501,12 @@ class SampleChecker {
/// Extracts the samples from the Dart files in [files], writes them
/// to disk, and adds them to the appropriate [sectionMap] or [sampleMap].
void _extractSamples(
Future<void> _extractSamples(
List<File> files, {
required Map<String, Section> sectionMap,
required Map<String, Sample> sampleMap,
bool silent = false,
}) {
}) async {
final List<Section> sections = <Section>[];
final List<Sample> samples = <Sample>[];
int dartpadCount = 0;
@@ -545,13 +652,19 @@ class SampleChecker {
if (sectionMap != null)
sectionMap[path] = section;
}
final TaskQueue<File> sampleQueue = TaskQueue<File>();
for (final Sample sample in samples) {
final File snippetFile = _writeSample(sample);
final Future<File> futureFile = sampleQueue.add(() => _writeSample(sample));
if (sampleMap != null) {
sample.contents = snippetFile.readAsLinesSync();
sampleMap[snippetFile.absolute.path] = sample;
sampleQueue.add(() async {
final File snippetFile = await futureFile;
sample.contents = await snippetFile.readAsLines();
sampleMap[snippetFile.absolute.path] = sample;
return futureFile;
});
}
}
await sampleQueue.tasksComplete;
}
/// Helper to process arguments given as a (possibly quoted) string.
@@ -596,9 +709,11 @@ class SampleChecker {
/// Creates the configuration files necessary for the analyzer to consider
/// the temporary directory a package, and sets which lint rules to enforce.
void _createConfigurationFiles(Directory directory) {
final File pubSpec = File(path.join(directory.path, 'pubspec.yaml'))..createSync(recursive: true);
final File pubSpec = File(path.join(directory.path, 'pubspec.yaml'));
if (!pubSpec.existsSync()) {
pubSpec.createSync(recursive: true);
pubSpec.writeAsStringSync('''
pubSpec.writeAsStringSync('''
name: analyze_sample_code
environment:
sdk: ">=2.12.0-0 <3.0.0"
@@ -611,11 +726,13 @@ dependencies:
dev_dependencies:
flutter_lints: ^1.0.3
''');
}
// Import the analysis options from the Flutter root.
final File analysisOptions = File(path.join(directory.path, 'analysis_options.yaml'));
analysisOptions.writeAsStringSync('''
if (!analysisOptions.existsSync()) {
analysisOptions.createSync(recursive: true);
analysisOptions.writeAsStringSync('''
include: package:flutter_lints/flutter.yaml
linter:
@@ -623,6 +740,7 @@ linter:
# Samples want to print things pretty often.
avoid_print: false
''');
}
}
/// Writes out a sample section to the disk and returns the file.
@@ -641,7 +759,7 @@ linter:
}
/// Invokes the analyzer on the given [directory] and returns the stdout.
List<String> _runAnalyzer(Directory directory, {bool silent = true}) {
int _runAnalyzer(Directory directory, {bool silent = true, required List<String> output}) {
if (!silent)
print('Starting analysis of code samples.');
_createConfigurationFiles(directory);
@@ -654,7 +772,8 @@ linter:
final List<String> stdout = result.stdout.toString().trim().split('\n');
// Remove output from building the flutter tool.
stderr.removeWhere((String line) {
return line.startsWith('Building flutter tool...');
return line.startsWith('Building flutter tool...')
|| line.startsWith('Waiting for another flutter command to release the startup lock...');
});
// Check out the stderr to see if the analyzer had it's own issues.
if (stderr.isNotEmpty && stderr.first.contains(RegExp(r' issues? found\. \(ran in '))) {
@@ -672,19 +791,21 @@ linter:
if (stdout.isNotEmpty && stdout.first.startsWith('Running "flutter pub get" in ')) {
stdout.removeAt(0);
}
_exitCode = result.exitCode;
return stdout;
output.addAll(stdout);
return result.exitCode;
}
/// Starts the analysis phase of checking the samples by invoking the analyzer
/// and parsing its output to create a map of filename to [AnalysisError]s.
Map<String, List<AnalysisError>> _analyze(
AnalysisResult _analyze(
Directory directory,
Map<String, Section> sections,
Map<String, Sample> samples, {
bool silent = false,
}) {
final List<String> errors = _runAnalyzer(directory, silent: silent);
final List<String> errors = <String>[];
int exitCode = _runAnalyzer(directory, silent: silent, output: errors);
final Map<String, List<AnalysisError>> analysisErrors = <String, List<AnalysisError>>{};
void addAnalysisError(File file, AnalysisError error) {
if (analysisErrors.containsKey(file.path)) {
@@ -825,15 +946,15 @@ linter:
);
}
}
if (_exitCode == 1 && analysisErrors.isEmpty && !unknownAnalyzerErrors) {
_exitCode = 0;
if (exitCode == 1 && analysisErrors.isEmpty && !unknownAnalyzerErrors) {
exitCode = 0;
}
if (_exitCode == 0) {
if (exitCode == 0) {
if (!silent)
print('No analysis errors in samples!');
assert(analysisErrors.isEmpty);
}
return analysisErrors;
return AnalysisResult(exitCode, analysisErrors);
}
/// Process one block of sample code (the part inside of "```" markers).
@@ -1070,17 +1191,17 @@ Future<void> _runInteractive({
}
print('Starting up in interactive mode on ${path.relative(filePath, from: _flutterRoot)} ...');
void analyze(SampleChecker checker, File file) {
Future<void> analyze(SampleChecker checker, File file) async {
final Map<String, Section> sections = <String, Section>{};
final Map<String, Sample> snippets = <String, Sample>{};
checker._extractSamples(<File>[file], silent: true, sectionMap: sections, sampleMap: snippets);
final Map<String, List<AnalysisError>> errors = checker._analyze(checker._tempDirectory, sections, snippets, silent: true);
await checker._extractSamples(<File>[file], silent: true, sectionMap: sections, sampleMap: snippets);
final AnalysisResult analysisResult = checker._analyze(checker._tempDirectory, sections, snippets, silent: true);
stderr.writeln('\u001B[2J\u001B[H'); // Clears the old results from the terminal.
if (errors.isNotEmpty) {
for (final String filePath in errors.keys) {
errors[filePath]!.forEach(stderr.writeln);
if (analysisResult.errors.isNotEmpty) {
for (final String filePath in analysisResult.errors.keys) {
analysisResult.errors[filePath]!.forEach(stderr.writeln);
}
stderr.writeln('\nFound ${errors.length} errors.');
stderr.writeln('\nFound ${analysisResult.errors.length} errors.');
} else {
stderr.writeln('\nNo issues found.');
}
@@ -1088,7 +1209,7 @@ Future<void> _runInteractive({
final SampleChecker checker = SampleChecker(flutterPackage, tempDirectory: tempDir)
.._createConfigurationFiles(tempDir);
analyze(checker, file);
await analyze(checker, file);
print('Type "q" to quit, or "r" to delete temp dir and manually reload.');

View File

@@ -13,14 +13,26 @@ function script_location() {
script_location="$(readlink "$script_location")"
[[ "$script_location" != /* ]] && script_location="$DIR/$script_location"
done
echo "$(cd -P "$(dirname "$script_location")" >/dev/null && pwd)"
cd -P "$(dirname "$script_location")" >/dev/null && pwd
}
function generate_docs() {
# Install and activate dartdoc.
# NOTE: When updating to a new dartdoc version, please also update
# `dartdoc_options.yaml` to include newly introduced error and warning types.
"$PUB" global activate dartdoc 1.0.0
"$PUB" global activate dartdoc 1.0.2
# Install and activate the snippets tool, which resides in the
# assets-for-api-docs repo:
# https://github.com/flutter/assets-for-api-docs/tree/master/packages/snippets
# >>> If you update this version, also update it in dev/bots/analyze_sample_code.dart <<<
"$PUB" global activate snippets 0.2.2
# Install and activate the snippets tool, which resides in the
# assets-for-api-docs repo:
# https://github.com/flutter/assets-for-api-docs/tree/master/packages/snippets
# >>> If you update this version, also update it in dev/bots/analyze_sample_code.dart <<<
"$PUB" global activate snippets 0.2.1
# This script generates a unified doc set, and creates
# a custom index.html, placing everything into dev/docs/doc.
@@ -96,9 +108,9 @@ function move_offline_into_place() {
mv flutter.docs.zip doc/offline/flutter.docs.zip
du -sh doc/offline/flutter.docs.zip
if [[ "$LUCI_BRANCH" == "stable" ]]; then
echo -e "<entry>\n <version>${FLUTTER_VERSION}</version>\n <url>https://api.flutter.dev/offline/flutter.docset.tar.gz</url>\n</entry>" > doc/offline/flutter.xml
echo -e "<entry>\n <version>${FLUTTER_VERSION_STRING}</version>\n <url>https://api.flutter.dev/offline/flutter.docset.tar.gz</url>\n</entry>" > doc/offline/flutter.xml
else
echo -e "<entry>\n <version>${FLUTTER_VERSION}</version>\n <url>https://master-api.flutter.dev/offline/flutter.docset.tar.gz</url>\n</entry>" > doc/offline/flutter.xml
echo -e "<entry>\n <version>${FLUTTER_VERSION_STRING}</version>\n <url>https://master-api.flutter.dev/offline/flutter.docset.tar.gz</url>\n</entry>" > doc/offline/flutter.xml
fi
mv flutter.docset.tar.gz doc/offline/flutter.docset.tar.gz
du -sh doc/offline/flutter.docset.tar.gz
@@ -125,9 +137,11 @@ DART="$DART_BIN/dart"
PUB="$DART_BIN/pub"
export PATH="$FLUTTER_BIN:$DART_BIN:$PATH"
# Make sure dart is installed by invoking flutter to download it.
"$FLUTTER" --version
FLUTTER_VERSION=$(cat "$FLUTTER_ROOT/version")
# Make sure dart is installed by invoking Flutter to download it.
# This also creates the 'version' file.
FLUTTER_VERSION=$("$FLUTTER" --version --machine)
export FLUTTER_VERSION
FLUTTER_VERSION_STRING=$(cat "$FLUTTER_ROOT/version")
# If the pub cache directory exists in the root, then use that.
FLUTTER_PUB_CACHE="$FLUTTER_ROOT/.pub-cache"

View File

@@ -746,7 +746,6 @@ Future<void> _runFrameworkTests() async {
print('${green}Running package tests$reset for directories other than packages/flutter');
await _pubRunTest(path.join(flutterRoot, 'dev', 'bots'));
await _pubRunTest(path.join(flutterRoot, 'dev', 'devicelab'), ensurePrecompiledTool: false); // See https://github.com/flutter/flutter/issues/86209
await _pubRunTest(path.join(flutterRoot, 'dev', 'snippets'));
// TODO(fujino): Move this to its own test shard
await _pubRunTest(path.join(flutterRoot, 'dev', 'conductor'), forceSingleCore: true);
await _runFlutterTest(path.join(flutterRoot, 'dev', 'integration_tests', 'android_semantics_testing'));

View File

@@ -11,11 +11,13 @@ library dart.ui;
/// Annotation used by Flutter's Dart compiler to indicate that an
/// [Object.toString] override should not be replaced with a supercall.
///
/// {@tool sample}
/// {@tool sample --template=stateless_widget_material}
/// A sample if using keepToString to prevent replacement by a supercall.
///
/// ```dart
/// class MyStringBuffer {
/// error;
///
/// StringBuffer _buffer = StringBuffer();
///
/// @keepToString

View File

@@ -20,11 +20,10 @@ void main() {
<String>['analyze_sample_code.dart', '--no-include-dart-ui', 'test/analyze-sample-code-test-input'],
);
final List<String> stdoutLines = process.stdout.toString().split('\n');
final List<String> stderrLines = process.stderr.toString().split('\n')
..removeWhere((String line) => line.startsWith('Analyzer output:') || line.startsWith('Building flutter tool...'));
final List<String> stderrLines = process.stderr.toString().split('\n');
expect(process.exitCode, isNot(equals(0)));
expect(stderrLines, <String>[
'In sample starting at dev/bots/test/analyze-sample-code-test-input/known_broken_documentation.dart:125: child: Text(title),',
expect(stderrLines, containsAll(<String>[
'In sample starting at dev/bots/test/analyze-sample-code-test-input/known_broken_documentation.dart:125: child: Text(title),',
">>> error: The final variable 'title' can't be read because it is potentially unassigned at this point (read_potentially_unassigned_final)",
'dev/bots/test/analyze-sample-code-test-input/known_broken_documentation.dart:30:9: new Opacity(',
'>>> info: Unnecessary new keyword (unnecessary_new)',
@@ -38,32 +37,35 @@ void main() {
">>> error: A value of type 'Null' can't be assigned to a variable of type 'int' (invalid_assignment)",
'dev/bots/test/analyze-sample-code-test-input/known_broken_documentation.dart:120:24: const SizedBox(),',
'>>> error: Unexpected comma at end of sample code. (missing_identifier)',
'',
'Found 2 sample code errors.',
''
]);
expect(stdoutLines, <String>[
]));
expect(stdoutLines, containsAll(<String>[
'Found 9 snippet code blocks, 0 sample code sections, and 2 dartpad sections.',
'Starting analysis of code samples.',
'',
]);
]));
});
test('Analyzes dart:ui code', () {
final ProcessResult process = Process.runSync(
'../../bin/cache/dart-sdk/bin/dart',
<String>[
'analyze_sample_code.dart',
'--dart-ui-location',
'test/analyze-sample-code-test-dart-ui',
'--dart-ui-location=test/analyze-sample-code-test-dart-ui',
'test/analyze-sample-code-test-input',
],
);
final List<String> stdoutLines = process.stdout.toString().split('\n');
final List<String> stderrLines = process.stderr.toString().split('\n');
expect(process.exitCode, isNot(equals(0)));
expect(stdoutLines, equals(<String>[
expect(stderrLines, containsAll(<String>[
'In sample starting at dev/bots/test/analyze-sample-code-test-dart-ui/ui.dart:15:class MyStatelessWidget extends StatelessWidget {',
">>> error: Missing concrete implementation of 'StatelessWidget.build' (non_abstract_class_inherits_abstract_member)",
'In sample starting at dev/bots/test/analyze-sample-code-test-dart-ui/ui.dart:15:class MyStringBuffer {',
">>> error: Classes can't be declared inside other classes (class_in_class)",
]));
expect(stdoutLines, containsAll(<String>[
// There is one sample code section in the test's dummy dart:ui code.
'Found 9 snippet code blocks, 1 sample code sections, and 2 dartpad sections.',
'',
'Starting analysis of code samples.',
]));
});
}