Prepare to migrate API doc samples and snippets to null safety (#72040)

This commit is contained in:
Michael Goderbauer
2020-12-11 13:39:36 -08:00
committed by GitHub
parent 74298a76e7
commit ff05ca2503
179 changed files with 1280 additions and 264 deletions

View File

@@ -8,9 +8,11 @@
// bin/cache/dart-sdk/bin/dart dev/bots/analyze-sample-code.dart
import 'dart:io';
import 'dart:isolate';
import 'package:args/args.dart';
import 'package:path/path.dart' as path;
import 'package:watcher/watcher.dart';
final String _flutterRoot = path.dirname(path.dirname(path.dirname(path.fromUri(Platform.script))));
final String _defaultFlutterPackage = path.join(_flutterRoot, 'packages', 'flutter', 'lib');
@@ -37,6 +39,11 @@ void main(List<String> arguments) {
negatable: false,
help: 'Print help for this command.',
);
argParser.addOption(
'interactive',
abbr: 'i',
help: 'Analyzes the sample code in the specified file interactivly.',
);
final ArgResults parsedArguments = argParser.parse(arguments);
@@ -69,15 +76,20 @@ void main(List<String> arguments) {
}
tempDirectory.createSync();
}
try {
exitCode = SampleChecker(
flutterPackage,
tempDirectory: tempDirectory,
verbose: parsedArguments['verbose'] as bool,
).checkSamples();
} on SampleCheckerException catch (e) {
stderr.write(e);
exit(1);
if (parsedArguments['interactive'] != null) {
_runInteractive(tempDirectory, flutterPackage, parsedArguments['interactive'] as String);
} else {
try {
exitCode = SampleChecker(
flutterPackage,
tempDirectory: tempDirectory,
verbose: parsedArguments['verbose'] as bool,
).checkSamples();
} on SampleCheckerException catch (e) {
stderr.write(e);
exit(1);
}
}
}
@@ -141,6 +153,9 @@ class SampleChecker {
/// A RegExp that matches a Dart constructor.
static final RegExp _constructorRegExp = RegExp(r'(const\s+)?_*[A-Z][a-zA-Z0-9<>._]*\(');
/// A RegExp that matches a dart version specification in an example preamble.
static final RegExp _dartVersionRegExp = RegExp(r'\/\/ \/\/ @dart = ([0-9]+\.[0-9]+)');
/// Whether or not to print verbose output.
final bool verbose;
@@ -186,8 +201,8 @@ class SampleChecker {
/// Computes the headers needed for each sample file.
List<Line> get headers {
return _headers ??= <String>[
'// @dart = 2.9',
'// generated code',
'// ignore_for_file: unused_import',
"import 'dart:async';",
"import 'dart:convert';",
"import 'dart:math' as math;",
@@ -211,7 +226,7 @@ class SampleChecker {
try {
final Map<String, Section> sections = <String, Section>{};
final Map<String, Sample> snippets = <String, Sample>{};
_extractSamples(sections, snippets);
_extractSamples(_listDartFiles(_flutterPackage, recursive: true), sectionMap: sections, sampleMap: snippets);
errors = _analyze(_tempDirectory, sections, snippets);
} finally {
if (errors.isNotEmpty) {
@@ -305,13 +320,13 @@ class SampleChecker {
return outputFile;
}
/// Extracts the samples from the Dart files in [_flutterPackage], writes them
/// Extracts the samples from the Dart files in [files], writes them
/// to disk, and adds them to the appropriate [sectionMap] or [sampleMap].
void _extractSamples(Map<String, Section> sectionMap, Map<String, Sample> sampleMap) {
void _extractSamples(List<File> files, {Map<String, Section> sectionMap, Map<String, Sample> sampleMap, bool silent = false}) {
final List<Section> sections = <Section>[];
final List<Sample> samples = <Sample>[];
for (final File file in _listDartFiles(_flutterPackage, recursive: true)) {
for (final File file in files) {
final String relativeFilePath = path.relative(file.path, from: _flutterPackage.path);
final List<String> sampleLines = file.readAsLinesSync();
final List<Section> preambleSections = <Section>[];
@@ -323,6 +338,7 @@ class SampleChecker {
bool inSnippet = false;
// Whether or not we're in a '```dart' segment.
bool inDart = false;
String dartVersionOverride;
int lineNumber = 0;
final List<String> block = <String>[];
List<String> snippetArgs = <String>[];
@@ -353,10 +369,16 @@ class SampleChecker {
} else if (inPreamble) {
if (line.isEmpty) {
inPreamble = false;
preambleSections.add(_processBlock(startLine, block));
// If there's only a dartVersionOverride in the preamble, don't add
// it as a section. The dartVersionOverride was processed below.
if (dartVersionOverride == null || block.isNotEmpty) {
preambleSections.add(_processBlock(startLine, block));
}
block.clear();
} else if (!line.startsWith('// ')) {
throw SampleCheckerException('Unexpected content in sample code preamble.', file: relativeFilePath, line: lineNumber);
} else if (_dartVersionRegExp.hasMatch(line)) {
dartVersionOverride = line.substring(3);
} else {
block.add(line.substring(3));
}
@@ -371,11 +393,8 @@ class SampleChecker {
if (_codeBlockEndRegex.hasMatch(trimmedLine)) {
inDart = false;
final Section processed = _processBlock(startLine, block);
if (preambleSections.isEmpty) {
sections.add(processed);
} else {
sections.add(Section.combine(preambleSections..add(processed)));
}
final Section combinedSection = preambleSections.isEmpty ? processed : Section.combine(preambleSections..add(processed));
sections.add(combinedSection.copyWith(dartVersionOverride: dartVersionOverride));
block.clear();
} else if (trimmedLine == _dartDocPrefix) {
block.add('');
@@ -434,14 +453,19 @@ class SampleChecker {
}
}
}
print('Found ${sections.length} sample code sections.');
if (!silent)
print('Found ${sections.length} sample code sections.');
for (final Section section in sections) {
sectionMap[_writeSection(section).path] = section;
final String path = _writeSection(section).path;
if (sectionMap != null)
sectionMap[path] = section;
}
for (final Sample sample in samples) {
final File snippetFile = _writeSample(sample);
sample.contents = snippetFile.readAsLinesSync();
sampleMap[snippetFile.absolute.path] = sample;
if (sampleMap != null) {
sample.contents = snippetFile.readAsLinesSync();
sampleMap[snippetFile.absolute.path] = sample;
}
}
}
@@ -492,7 +516,7 @@ class SampleChecker {
pubSpec.writeAsStringSync('''
name: analyze_sample_code
environment:
sdk: '>=2.10.0 <3.0.0'
sdk: ">=2.12.0-0 <3.0.0"
dependencies:
flutter:
sdk: flutter
@@ -512,6 +536,7 @@ linter:
final String sectionId = _createNameFromSource('snippet', section.start.filename, section.start.line);
final File outputFile = File(path.join(_tempDirectory.path, '$sectionId.dart'))..createSync(recursive: true);
final List<Line> mainContents = <Line>[
if (section.dartVersionOverride != null) Line(section.dartVersionOverride) else const Line(''),
...headers,
const Line(''),
Line('// From: ${section.start.filename}:${section.start.line}'),
@@ -582,7 +607,7 @@ linter:
caseSensitive: false,
);
bool unknownAnalyzerErrors = false;
final int headerLength = headers.length + 2;
final int headerLength = headers.length + 3;
for (final String error in errors) {
final Match parts = errorPattern.matchAsPrefix(error);
if (parts != null) {
@@ -803,7 +828,7 @@ class Line {
/// A class to represent a section of sample code, marked by "{@tool snippet}...{@end-tool}".
class Section {
const Section(this.code);
const Section(this.code, {this.dartVersionOverride});
factory Section.combine(List<Section> sections) {
final List<Line> code = sections
.expand((Section section) => section.code)
@@ -846,6 +871,11 @@ class Section {
}
Line get start => code.firstWhere((Line line) => line.filename != null);
final List<Line> code;
final String dartVersionOverride;
Section copyWith({String dartVersionOverride}) {
return Section(code, dartVersionOverride: dartVersionOverride);
}
}
/// A class to represent a sample in the dartdoc comments, marked by
@@ -908,3 +938,46 @@ class AnalysisError {
}
}
}
Future<void> _runInteractive(Directory tempDir, Directory flutterPackage, String filePath) async {
print('Starting up in interactive mode...');
filePath = path.isAbsolute(filePath) ? filePath : path.join(path.current, filePath);
final File file = File(filePath);
if (!file.existsSync()) {
throw 'Path ${file.absolute.path} does not exist.';
}
if (!path.isWithin(_flutterRoot, file.absolute.path)) {
throw 'Path ${file.absolute.path} is not within the flutter root: $_flutterRoot';
}
if (tempDir == null) {
tempDir = Directory.systemTemp.createTempSync('flutter_analyze_sample_code.');
ProcessSignal.sigint.watch().listen((_) {
print('Deleting temp files...');
tempDir.deleteSync(recursive: true);
exit(0);
});
print('Using temp dir ${tempDir.path}');
}
final SampleChecker checker = SampleChecker(flutterPackage, tempDirectory: tempDir)
.._createConfigurationFiles(tempDir)
.._extractSamples(<File>[file], silent: true);
await Isolate.spawn(_watcher, <dynamic>[checker, file]);
await Process.start(
_flutter,
<String>['--no-wrap', 'analyze', '--no-preamble', '--no-congratulate', '--watch', '.'],
workingDirectory: tempDir.absolute.path,
mode: ProcessStartMode.inheritStdio
);
}
void _watcher(List<dynamic> args) {
final File file = args.last as File;
final SampleChecker checker = args.first as SampleChecker;
Watcher(file.absolute.path).events.listen((_) {
checker._extractSamples(<File>[file], silent: true);
});
}