Auto-format Framework (#160545)

This auto-formats all *.dart files in the repository outside of the
`engine` subdirectory and enforces that these files stay formatted with
a presubmit check.

**Reviewers:** Please carefully review all the commits except for the
one titled "formatted". The "formatted" commit was auto-generated by
running `dev/tools/format.sh -a -f`. The other commits were hand-crafted
to prepare the repo for the formatting change. I recommend reviewing the
commits one-by-one via the "Commits" tab and avoiding Github's "Files
changed" tab as it will likely slow down your browser because of the
size of this PR.

---------

Co-authored-by: Kate Lovett <katelovett@google.com>
Co-authored-by: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com>
This commit is contained in:
Michael Goderbauer
2024-12-19 12:06:21 -08:00
committed by GitHub
parent 8e0993eda8
commit 5491c8c146
4411 changed files with 455108 additions and 415991 deletions

View File

@@ -27,8 +27,7 @@ Iterable<List<SourceLine>> getFileDocumentationComments(File file) {
/// Gets an iterable over all of the blocks of documentation comments from an
/// iterable over the [SourceElement]s involved.
Iterable<List<SourceLine>> getDocumentationComments(
Iterable<SourceElement> elements) {
Iterable<List<SourceLine>> getDocumentationComments(Iterable<SourceElement> elements) {
return elements
.where((SourceElement element) => element.comment.isNotEmpty)
.map<List<SourceLine>>((SourceElement element) => element.comment);
@@ -50,13 +49,13 @@ Iterable<SourceElement> getCommentElements(Iterable<SourceElement> elements) {
/// The `file` argument is used to tag the lines with a filename that they came from.
Iterable<SourceElement> getElementsFromString(String content, File file) {
final ParseStringResult parseResult = parseString(
featureSet: FeatureSet.fromEnableFlags2(
sdkLanguageVersion: FlutterInformation.instance.getDartSdkVersion(),
flags: <String>[],
),
content: content);
final _SourceVisitor<CompilationUnit> visitor =
_SourceVisitor<CompilationUnit>(file);
featureSet: FeatureSet.fromEnableFlags2(
sdkLanguageVersion: FlutterInformation.instance.getDartSdkVersion(),
flags: <String>[],
),
content: content,
);
final _SourceVisitor<CompilationUnit> visitor = _SourceVisitor<CompilationUnit>(file);
visitor.visitCompilationUnit(parseResult.unit);
visitor.assignLineNumbers();
return visitor.elements;
@@ -66,18 +65,17 @@ Iterable<SourceElement> getElementsFromString(String content, File file) {
///
/// Takes an optional [ResourceProvider] to allow reading from a memory
/// filesystem.
Iterable<SourceElement> getFileElements(File file,
{afs.ResourceProvider? resourceProvider}) {
Iterable<SourceElement> getFileElements(File file, {afs.ResourceProvider? resourceProvider}) {
resourceProvider ??= afs.PhysicalResourceProvider.INSTANCE;
final ParseStringResult parseResult = parseFile(
featureSet: FeatureSet.fromEnableFlags2(
sdkLanguageVersion: FlutterInformation.instance.getDartSdkVersion(),
flags: <String>[],
),
path: file.absolute.path,
resourceProvider: resourceProvider);
final _SourceVisitor<CompilationUnit> visitor =
_SourceVisitor<CompilationUnit>(file);
featureSet: FeatureSet.fromEnableFlags2(
sdkLanguageVersion: FlutterInformation.instance.getDartSdkVersion(),
flags: <String>[],
),
path: file.absolute.path,
resourceProvider: resourceProvider,
);
final _SourceVisitor<CompilationUnit> visitor = _SourceVisitor<CompilationUnit>(file);
visitor.visitCompilationUnit(parseResult.unit);
visitor.assignLineNumbers();
return visitor.elements;
@@ -100,13 +98,11 @@ class _SourceVisitor<T> extends RecursiveAstVisitor<T> {
for (final SourceElement element in elements) {
final List<SourceLine> newLines = <SourceLine>[];
for (final SourceLine line in element.comment) {
final CharacterLocation intervalLine =
lineInfo.getLocation(line.startChar);
final CharacterLocation intervalLine = lineInfo.getLocation(line.startChar);
newLines.add(line.copyWith(line: intervalLine.lineNumber));
}
final int elementLine = lineInfo.getLocation(element.startPos).lineNumber;
replacedElements
.add(element.copyWith(comment: newLines, startLine: elementLine));
replacedElements.add(element.copyWith(comment: newLines, startLine: elementLine));
removedElements.add(element);
}
elements.removeAll(removedElements);
@@ -117,13 +113,15 @@ class _SourceVisitor<T> extends RecursiveAstVisitor<T> {
final List<SourceLine> result = <SourceLine>[];
if (comment.tokens.isNotEmpty) {
for (final Token token in comment.tokens) {
result.add(SourceLine(
token.toString(),
element: element,
file: file,
startChar: token.charOffset,
endChar: token.charEnd,
));
result.add(
SourceLine(
token.toString(),
element: element,
file: file,
startChar: token.charOffset,
endChar: token.charEnd,
),
);
}
}
return result;
@@ -157,10 +155,8 @@ class _SourceVisitor<T> extends RecursiveAstVisitor<T> {
continue;
}
List<SourceLine> comment = <SourceLine>[];
if (node.documentationComment != null &&
node.documentationComment!.tokens.isNotEmpty) {
comment = _processComment(
declaration.name.lexeme, node.documentationComment!);
if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) {
comment = _processComment(declaration.name.lexeme, node.documentationComment!);
}
elements.add(
SourceElement(
@@ -180,8 +176,7 @@ class _SourceVisitor<T> extends RecursiveAstVisitor<T> {
T? visitGenericTypeAlias(GenericTypeAlias node) {
if (isPublic(node.name.lexeme)) {
List<SourceLine> comment = <SourceLine>[];
if (node.documentationComment != null &&
node.documentationComment!.tokens.isNotEmpty) {
if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) {
comment = _processComment(node.name.lexeme, node.documentationComment!);
}
elements.add(
@@ -204,11 +199,12 @@ class _SourceVisitor<T> extends RecursiveAstVisitor<T> {
continue;
}
List<SourceLine> comment = <SourceLine>[];
if (node.documentationComment != null &&
node.documentationComment!.tokens.isNotEmpty) {
if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) {
assert(enclosingClass.isNotEmpty);
comment = _processComment('$enclosingClass.${declaration.name.lexeme}',
node.documentationComment!);
comment = _processComment(
'$enclosingClass.${declaration.name.lexeme}',
node.documentationComment!,
);
}
elements.add(
SourceElement(
@@ -228,15 +224,11 @@ class _SourceVisitor<T> extends RecursiveAstVisitor<T> {
@override
T? visitConstructorDeclaration(ConstructorDeclaration node) {
final String fullName =
'$enclosingClass${node.name == null ? '' : '.${node.name}'}';
if (isPublic(enclosingClass) &&
(node.name == null || isPublic(node.name!.lexeme))) {
final String fullName = '$enclosingClass${node.name == null ? '' : '.${node.name}'}';
if (isPublic(enclosingClass) && (node.name == null || isPublic(node.name!.lexeme))) {
List<SourceLine> comment = <SourceLine>[];
if (node.documentationComment != null &&
node.documentationComment!.tokens.isNotEmpty) {
comment = _processComment(
'$enclosingClass.$fullName', node.documentationComment!);
if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) {
comment = _processComment('$enclosingClass.$fullName', node.documentationComment!);
}
elements.add(
SourceElement(
@@ -258,10 +250,8 @@ class _SourceVisitor<T> extends RecursiveAstVisitor<T> {
List<SourceLine> comment = <SourceLine>[];
// Skip functions that are defined inside of methods.
if (!isInsideMethod(node)) {
if (node.documentationComment != null &&
node.documentationComment!.tokens.isNotEmpty) {
comment =
_processComment(node.name.lexeme, node.documentationComment!);
if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) {
comment = _processComment(node.name.lexeme, node.documentationComment!);
}
elements.add(
SourceElement(
@@ -282,11 +272,12 @@ class _SourceVisitor<T> extends RecursiveAstVisitor<T> {
T? visitMethodDeclaration(MethodDeclaration node) {
if (isPublic(node.name.lexeme) && isPublic(enclosingClass)) {
List<SourceLine> comment = <SourceLine>[];
if (node.documentationComment != null &&
node.documentationComment!.tokens.isNotEmpty) {
if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) {
assert(enclosingClass.isNotEmpty);
comment = _processComment(
'$enclosingClass.${node.name.lexeme}', node.documentationComment!);
'$enclosingClass.${node.name.lexeme}',
node.documentationComment!,
);
}
elements.add(
SourceElement(
@@ -315,8 +306,7 @@ class _SourceVisitor<T> extends RecursiveAstVisitor<T> {
if (!node.name.lexeme.startsWith('_')) {
enclosingClass = node.name.lexeme;
List<SourceLine> comment = <SourceLine>[];
if (node.documentationComment != null &&
node.documentationComment!.tokens.isNotEmpty) {
if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) {
comment = _processComment(node.name.lexeme, node.documentationComment!);
}
elements.add(
@@ -340,8 +330,7 @@ class _SourceVisitor<T> extends RecursiveAstVisitor<T> {
if (!node.name.lexeme.startsWith('_')) {
enclosingClass = node.name.lexeme;
List<SourceLine> comment = <SourceLine>[];
if (node.documentationComment != null &&
node.documentationComment!.tokens.isNotEmpty) {
if (node.documentationComment != null && node.documentationComment!.tokens.isNotEmpty) {
comment = _processComment(node.name.lexeme, node.documentationComment!);
}
elements.add(

View File

@@ -27,8 +27,7 @@ class SnippetConfiguration {
/// Gets the skeleton file to use for the given [SampleType] and DartPad
/// preference.
File getHtmlSkeletonFile(String type) {
final String filename =
type == 'dartpad' ? 'dartpad-sample.html' : '$type.html';
final String filename = type == 'dartpad' ? 'dartpad-sample.html' : '$type.html';
return filesystem.file(path.join(skeletonsDirectory.path, filename));
}
}
@@ -37,17 +36,22 @@ class SnippetConfiguration {
/// locations based in the current location of the snippets main.dart.
class FlutterRepoSnippetConfiguration extends SnippetConfiguration {
FlutterRepoSnippetConfiguration({required this.flutterRoot, super.filesystem})
: super(
configDirectory: _underRoot(filesystem, flutterRoot,
const <String>['dev', 'snippets', 'config']),
skeletonsDirectory: _underRoot(filesystem, flutterRoot,
const <String>['dev', 'snippets', 'config', 'skeletons']),
);
: super(
configDirectory: _underRoot(filesystem, flutterRoot, const <String>[
'dev',
'snippets',
'config',
]),
skeletonsDirectory: _underRoot(filesystem, flutterRoot, const <String>[
'dev',
'snippets',
'config',
'skeletons',
]),
);
final Directory flutterRoot;
static Directory _underRoot(
FileSystem fs, Directory flutterRoot, List<String> dirs) =>
fs.directory(path.canonicalize(
path.joinAll(<String>[flutterRoot.absolute.path, ...dirs])));
static Directory _underRoot(FileSystem fs, Directory flutterRoot, List<String> dirs) =>
fs.directory(path.canonicalize(path.joinAll(<String>[flutterRoot.absolute.path, ...dirs])));
}

View File

@@ -27,8 +27,7 @@ class SourceLine {
final int indent;
final String text;
String toStringWithColumn(int column) =>
'$file:$line:${column + indent}: $text';
String toStringWithColumn(int column) => '$file:$line:${column + indent}: $text';
SourceLine copyWith({
String? element,
@@ -71,14 +70,10 @@ class SkeletonInjection {
/// A base class to represent a block of any kind of sample code, marked by
/// "{@tool (snippet|sample|dartdoc) ...}...{@end-tool}".
abstract class CodeSample {
CodeSample(
this.args,
this.input, {
required this.index,
required SourceLine lineProto,
}) : assert(args.isNotEmpty),
_lineProto = lineProto,
sourceFile = null;
CodeSample(this.args, this.input, {required this.index, required SourceLine lineProto})
: assert(args.isNotEmpty),
_lineProto = lineProto,
sourceFile = null;
CodeSample.fromFile(
this.args,
@@ -86,8 +81,8 @@ abstract class CodeSample {
this.sourceFile, {
required this.index,
required SourceLine lineProto,
}) : assert(args.isNotEmpty),
_lineProto = lineProto;
}) : assert(args.isNotEmpty),
_lineProto = lineProto;
final File? sourceFile;
final List<String> args;
@@ -102,8 +97,7 @@ abstract class CodeSample {
bool doneStrippingHeaders = false;
try {
for (final String line in sourceFile!.readAsLinesSync()) {
if (!doneStrippingHeaders &&
RegExp(r'^\s*(\/\/.*)?$').hasMatch(line)) {
if (!doneStrippingHeaders && RegExp(r'^\s*(\/\/.*)?$').hasMatch(line)) {
continue;
}
// Stop skipping lines after the first line that isn't stripped.
@@ -121,14 +115,12 @@ abstract class CodeSample {
r'(\/\/\*\*+\n)?\/\/\* [▼▲]+.*$(\n\/\/\*\*+)?\n\n?',
multiLine: true,
);
_sourceFileContents =
stripped.join('\n').replaceAll(sectionMarkerRegExp, '');
_sourceFileContents = stripped.join('\n').replaceAll(sectionMarkerRegExp, '');
}
return _sourceFileContents ?? '';
}
Iterable<String> get inputStrings =>
input.map<String>((SourceLine line) => line.text);
Iterable<String> get inputStrings => input.map<String>((SourceLine line) => line.text);
String get inputAsString => inputStrings.join('\n');
/// The index of this sample within the dartdoc comment it came from.
@@ -151,9 +143,7 @@ abstract class CodeSample {
String toString() {
final StringBuffer buf = StringBuffer('${args.join(' ')}:\n');
for (final SourceLine line in input) {
buf.writeln(
'${(line.line == -1 ? '??' : line.line).toString().padLeft(4)}: ${line.text} ',
);
buf.writeln('${(line.line == -1 ? '??' : line.line).toString().padLeft(4)}: ${line.text} ');
}
return buf.toString();
}
@@ -167,17 +157,9 @@ abstract class CodeSample {
/// Snippets are code that is not meant to be run as a complete application, but
/// rather as a code usage example.
class SnippetSample extends CodeSample {
SnippetSample(
List<SourceLine> input, {
required int index,
required SourceLine lineProto,
}) : assumptions = <SourceLine>[],
super(
<String>['snippet'],
input,
index: index,
lineProto: lineProto,
);
SnippetSample(List<SourceLine> input, {required int index, required SourceLine lineProto})
: assumptions = <SourceLine>[],
super(<String>['snippet'], input, index: index, lineProto: lineProto);
factory SnippetSample.combine(
List<SnippetSample> sections, {
@@ -189,25 +171,16 @@ class SnippetSample extends CodeSample {
return SnippetSample(code, index: index, lineProto: lineProto);
}
factory SnippetSample.fromStrings(SourceLine firstLine, List<String> code,
{required int index}) {
factory SnippetSample.fromStrings(SourceLine firstLine, List<String> code, {required int index}) {
final List<SourceLine> codeLines = <SourceLine>[];
int startPos = firstLine.startChar;
for (int i = 0; i < code.length; ++i) {
codeLines.add(
firstLine.copyWith(
text: code[i],
line: firstLine.line + i,
startChar: startPos,
),
firstLine.copyWith(text: code[i], line: firstLine.line + i, startChar: startPos),
);
startPos += code[i].length + 1;
}
return SnippetSample(
codeLines,
index: index,
lineProto: firstLine,
);
return SnippetSample(codeLines, index: index, lineProto: firstLine);
}
factory SnippetSample.surround(
@@ -233,8 +206,7 @@ class SnippetSample extends CodeSample {
String get template => '';
@override
SourceLine get start =>
input.firstWhere((SourceLine line) => line.file != null);
SourceLine get start => input.firstWhere((SourceLine line) => line.file != null);
@override
String get type => 'snippet';
@@ -253,8 +225,8 @@ class ApplicationSample extends CodeSample {
required List<String> args,
required int index,
required SourceLine lineProto,
}) : assert(args.isNotEmpty),
super(args, input, index: index, lineProto: lineProto);
}) : assert(args.isNotEmpty),
super(args, input, index: index, lineProto: lineProto);
ApplicationSample.fromFile({
List<SourceLine> input = const <SourceLine>[],
@@ -262,9 +234,8 @@ class ApplicationSample extends CodeSample {
required File sourceFile,
required int index,
required SourceLine lineProto,
}) : assert(args.isNotEmpty),
super.fromFile(args, input, sourceFile,
index: index, lineProto: lineProto);
}) : assert(args.isNotEmpty),
super.fromFile(args, input, sourceFile, index: index, lineProto: lineProto);
@override
String get type => 'sample';
@@ -278,12 +249,8 @@ class ApplicationSample extends CodeSample {
/// [DartpadSample] represents one `{@tool dartpad ...}...{@end-tool}` block in
/// the source file.
class DartpadSample extends ApplicationSample {
DartpadSample({
super.input,
required super.args,
required super.index,
required super.lineProto,
}) : assert(args.isNotEmpty);
DartpadSample({super.input, required super.args, required super.index, required super.lineProto})
: assert(args.isNotEmpty);
DartpadSample.fromFile({
super.input,
@@ -291,8 +258,8 @@ class DartpadSample extends ApplicationSample {
required super.sourceFile,
required super.index,
required super.lineProto,
}) : assert(args.isNotEmpty),
super.fromFile();
}) : assert(args.isNotEmpty),
super.fromFile();
@override
String get type => 'dartpad';
@@ -328,14 +295,14 @@ enum SourceElementType {
/// Converts the enum type [SourceElementType] to a human readable string.
String sourceElementTypeAsString(SourceElementType type) {
return switch (type) {
SourceElementType.classType => 'class',
SourceElementType.fieldType => 'field',
SourceElementType.methodType => 'method',
SourceElementType.constructorType => 'constructor',
SourceElementType.typedefType => 'typedef',
SourceElementType.classType => 'class',
SourceElementType.fieldType => 'field',
SourceElementType.methodType => 'method',
SourceElementType.constructorType => 'constructor',
SourceElementType.typedefType => 'typedef',
SourceElementType.topLevelVariableType => 'variable',
SourceElementType.functionType => 'function',
SourceElementType.unknownType => 'unknown',
SourceElementType.functionType => 'function',
SourceElementType.unknownType => 'unknown',
};
}
@@ -360,8 +327,7 @@ class SourceElement {
}) {
comment ??= <SourceLine>[];
samples ??= <CodeSample>[];
final List<String> commentLines =
comment.map<String>((SourceLine line) => line.text).toList();
final List<String> commentLines = comment.map<String>((SourceLine line) => line.text).toList();
final String commentString = commentLines.join('\n');
return SourceElement._(
type,
@@ -394,10 +360,10 @@ class SourceElement {
String commentStringWithoutTools = '',
String commentStringWithoutCode = '',
List<String> commentLines = const <String>[],
}) : _commentString = commentString,
_commentStringWithoutTools = commentStringWithoutTools,
_commentStringWithoutCode = commentStringWithoutCode,
_commentLines = commentLines;
}) : _commentString = commentString,
_commentStringWithoutTools = commentStringWithoutTools,
_commentStringWithoutCode = commentStringWithoutCode,
_commentLines = commentLines;
final String _commentString;
final String _commentStringWithoutTools;
@@ -408,14 +374,15 @@ class SourceElement {
// of any dartdoc tools.
static String _getCommentStringWithoutTools(String string) {
return string.replaceAll(
RegExp(r'(\{@tool ([^}]*)\}.*?\{@end-tool\}|/// ?)', dotAll: true), '');
RegExp(r'(\{@tool ([^}]*)\}.*?\{@end-tool\}|/// ?)', dotAll: true),
'',
);
}
// Includes the description text inside of an "@tool"-based sample, but not
// the code itself, or any dartdoc tags.
static String _getCommentStringWithoutCode(String string) {
return string.replaceAll(
RegExp(r'([`]{3}.*?[`]{3}|\{@\w+[^}]*\}|/// ?)', dotAll: true), '');
return string.replaceAll(RegExp(r'([`]{3}.*?[`]{3}|\{@\w+[^}]*\}|/// ?)', dotAll: true), '');
}
/// The type of the element
@@ -477,7 +444,8 @@ class SourceElement {
int get dartpadSampleCount => samples.whereType<DartpadSample>().length;
/// The number of [ApplicationSample]s in the dartdoc comment for this element.
int get applicationSampleCount => samples.where((CodeSample sample) {
int get applicationSampleCount =>
samples.where((CodeSample sample) {
return sample is ApplicationSample && sample is! DartpadSample;
}).length;
@@ -494,8 +462,7 @@ class SourceElement {
/// Count of comment characters, not including any code samples in the
/// comment, after collapsing each run of whitespace to a single space.
int get charCount =>
commentStringWithoutCode.replaceAll(RegExp(r'\s+'), ' ').length;
int get charCount => commentStringWithoutCode.replaceAll(RegExp(r'\s+'), ' ').length;
/// Whether or not this element's documentation has a "See also:" section in it.
bool get hasSeeAlso => commentStringWithoutTools.contains('See also:');

View File

@@ -26,8 +26,7 @@ String sortImports(String contents) {
),
);
final List<AnalysisError> errors = <AnalysisError>[];
final _ImportOrganizer organizer =
_ImportOrganizer(contents, parseResult.unit, errors);
final _ImportOrganizer organizer = _ImportOrganizer(contents, parseResult.unit, errors);
final List<_SourceEdit> edits = organizer.organize();
// Sort edits in reverse order
edits.sort((_SourceEdit a, _SourceEdit b) {
@@ -48,8 +47,7 @@ String sortImports(String contents) {
// this class should probably be replaced.
// https://github.com/flutter/flutter/issues/86197
class _ImportOrganizer {
_ImportOrganizer(this.initialCode, this.unit, this.errors)
: code = initialCode {
_ImportOrganizer(this.initialCode, this.unit, this.errors) : code = initialCode {
endOfLine = getEOL(code);
hasUnresolvedIdentifierError = errors.any((AnalysisError error) {
return error.errorCode.isUnresolvedIdentifier;
@@ -88,8 +86,11 @@ class _ImportOrganizer {
final List<_SourceEdit> edits = <_SourceEdit>[];
if (code != initialCode) {
final int suffixLength = findCommonSuffix(initialCode, code);
final _SourceEdit edit = _SourceEdit(0, initialCode.length - suffixLength,
code.substring(0, code.length - suffixLength));
final _SourceEdit edit = _SourceEdit(
0,
initialCode.length - suffixLength,
code.substring(0, code.length - suffixLength),
);
edits.add(edit);
}
return edits;
@@ -110,28 +111,26 @@ class _ImportOrganizer {
int offset = directive.offset;
int end = directive.end;
final Token? leadingComment =
getLeadingComment(unit, directive, lineInfo);
final Token? trailingComment =
getTrailingComment(unit, directive, lineInfo, end);
final Token? leadingComment = getLeadingComment(unit, directive, lineInfo);
final Token? trailingComment = getTrailingComment(unit, directive, lineInfo, end);
String? leadingCommentText;
if (leadingComment != null) {
leadingCommentText =
code.substring(leadingComment.offset, directive.offset);
leadingCommentText = code.substring(leadingComment.offset, directive.offset);
offset = leadingComment.offset;
}
String? trailingCommentText;
if (trailingComment != null) {
trailingCommentText =
code.substring(directive.end, trailingComment.end);
trailingCommentText = code.substring(directive.end, trailingComment.end);
end = trailingComment.end;
}
String? documentationText;
final Comment? documentationComment = directive.documentationComment;
if (documentationComment != null) {
documentationText = code.substring(
documentationComment.offset, documentationComment.end);
documentationComment.offset,
documentationComment.end,
);
}
String? annotationText;
final Token? beginToken = directive.metadata.beginToken;
@@ -140,8 +139,9 @@ class _ImportOrganizer {
annotationText = code.substring(beginToken.offset, endToken.end);
}
final String text = code.substring(
directive.firstTokenAfterCommentAndMetadata.offset,
directive.end);
directive.firstTokenAfterCommentAndMetadata.offset,
directive.end,
);
final String uriContent = directive.uri.stringValue ?? '';
directives.add(
_DirectiveInfo(
@@ -264,7 +264,10 @@ class _ImportOrganizer {
/// comments and not returned unless they contain blank lines, in which case
/// only the last part of the comment will be returned.
static Token? getLeadingComment(
CompilationUnit unit, UriBasedDirective directive, LineInfo lineInfo) {
CompilationUnit unit,
UriBasedDirective directive,
LineInfo lineInfo,
) {
if (directive.beginToken.precedingComments == null) {
return null;
}
@@ -292,8 +295,7 @@ class _ImportOrganizer {
// as they will be attached to the end of it.
Token? comment = firstComment;
while (comment != null &&
previousDirectiveLine ==
lineInfo.getLocation(comment.offset).lineNumber) {
previousDirectiveLine == lineInfo.getLocation(comment.offset).lineNumber) {
comment = comment.next;
}
return comment;
@@ -306,8 +308,12 @@ class _ImportOrganizer {
///
/// To be considered a trailing comment, the comment must be on the same line
/// as the directive.
static Token? getTrailingComment(CompilationUnit unit,
UriBasedDirective directive, LineInfo lineInfo, int end) {
static Token? getTrailingComment(
CompilationUnit unit,
UriBasedDirective directive,
LineInfo lineInfo,
int end,
) {
final int line = lineInfo.getLocation(end).lineNumber;
Token? comment = directive.endToken.next!.precedingComments;
while (comment != null) {
@@ -395,7 +401,7 @@ enum _DirectivePriority {
EXPORT_PKG,
EXPORT_OTHER,
EXPORT_REL,
PART
PART,
}
/// SourceEdit

View File

@@ -18,17 +18,17 @@ import 'util.dart';
/// Generates the snippet HTML, as well as saving the output snippet main to
/// the output directory.
class SnippetGenerator {
SnippetGenerator(
{SnippetConfiguration? configuration,
FileSystem filesystem = const LocalFileSystem(),
Directory? flutterRoot})
: flutterRoot =
flutterRoot ?? FlutterInformation.instance.getFlutterRoot(),
configuration = configuration ??
FlutterRepoSnippetConfiguration(
filesystem: filesystem,
flutterRoot: flutterRoot ??
FlutterInformation.instance.getFlutterRoot());
SnippetGenerator({
SnippetConfiguration? configuration,
FileSystem filesystem = const LocalFileSystem(),
Directory? flutterRoot,
}) : flutterRoot = flutterRoot ?? FlutterInformation.instance.getFlutterRoot(),
configuration =
configuration ??
FlutterRepoSnippetConfiguration(
filesystem: filesystem,
flutterRoot: flutterRoot ?? FlutterInformation.instance.getFlutterRoot(),
);
final Directory flutterRoot;
@@ -40,8 +40,7 @@ class SnippetGenerator {
/// A Dart formatted used to format the snippet code and finished application
/// code.
static DartFormatter formatter =
DartFormatter(pageWidth: 80, fixes: StyleFix.all);
static DartFormatter formatter = DartFormatter(pageWidth: 80, fixes: StyleFix.all);
/// Interpolates the [injections] into an HTML skeleton file.
///
@@ -49,10 +48,7 @@ class SnippetGenerator {
///
/// Takes into account the [type] and doesn't substitute in the id and the app
/// if not a [SnippetType.sample] snippet.
String interpolateSkeleton(
CodeSample sample,
String skeleton,
) {
String interpolateSkeleton(CodeSample sample, String skeleton) {
final List<String> codeParts = <String>[];
const HtmlEscape htmlEscape = HtmlEscape();
String? language;
@@ -72,15 +68,15 @@ class SnippetGenerator {
// Only insert a div for the description if there actually is some text there.
// This means that the {{description}} marker in the skeleton needs to
// be inside of an {@inject-html} block.
final String description = sample.description.trim().isNotEmpty
? '<div class="snippet-description">{@end-inject-html}${sample.description.trim()}{@inject-html}</div>'
: '';
final String description =
sample.description.trim().isNotEmpty
? '<div class="snippet-description">{@end-inject-html}${sample.description.trim()}{@inject-html}</div>'
: '';
// DartPad only supports stable or main as valid channels. Use main
// if not on stable so that local runs will work (although they will
// still take their sample code from the master docs server).
final String channel =
sample.metadata['channel'] == 'stable' ? 'stable' : 'main';
final String channel = sample.metadata['channel'] == 'stable' ? 'stable' : 'main';
final Map<String, String> substitutions = <String, String>{
'description': description,
@@ -97,23 +93,21 @@ class SnippetGenerator {
..['serial'] = sample.metadata['serial']?.toString() ?? '0'
..['app'] = htmlEscape.convert(sample.output);
}
return skeleton.replaceAllMapped(
RegExp('{{(${substitutions.keys.join('|')})}}'), (Match match) {
return skeleton.replaceAllMapped(RegExp('{{(${substitutions.keys.join('|')})}}'), (
Match match,
) {
return substitutions[match[1]]!;
});
}
/// Consolidates all of the snippets and the assumptions into one snippet, in
/// order to create a compilable result.
Iterable<SourceLine> consolidateSnippets(List<CodeSample> samples,
{bool addMarkers = false}) {
Iterable<SourceLine> consolidateSnippets(List<CodeSample> samples, {bool addMarkers = false}) {
if (samples.isEmpty) {
return <SourceLine>[];
}
final Iterable<SnippetSample> snippets = samples.whereType<SnippetSample>();
final List<SourceLine> snippetLines = <SourceLine>[
...snippets.first.assumptions,
];
final List<SourceLine> snippetLines = <SourceLine>[...snippets.first.assumptions];
for (final SnippetSample sample in snippets) {
parseInput(sample);
snippetLines.addAll(_processBlocks(sample));
@@ -122,15 +116,13 @@ class SnippetGenerator {
}
/// A RegExp that matches a Dart constructor.
static final RegExp _constructorRegExp =
RegExp(r'(const\s+)?_*[A-Z][a-zA-Z0-9<>._]*\(');
static final RegExp _constructorRegExp = RegExp(r'(const\s+)?_*[A-Z][a-zA-Z0-9<>._]*\(');
/// A serial number so that we can create unique expression names when we
/// generate them.
int _expressionId = 0;
List<SourceLine> _surround(
String prefix, Iterable<SourceLine> body, String suffix) {
List<SourceLine> _surround(String prefix, Iterable<SourceLine> body, String suffix) {
return <SourceLine>[
if (prefix.isNotEmpty) SourceLine(prefix),
...body,
@@ -143,9 +135,10 @@ class SnippetGenerator {
/// processed separately. Uses a primitive heuristic to make sample blocks
/// into valid Dart code.
List<SourceLine> _processBlocks(CodeSample sample) {
final List<SourceLine> block = sample.parts
.expand<SourceLine>((SkeletonInjection injection) => injection.contents)
.toList();
final List<SourceLine> block =
sample.parts
.expand<SourceLine>((SkeletonInjection injection) => injection.contents)
.toList();
if (block.isEmpty) {
return <SourceLine>[];
}
@@ -154,23 +147,18 @@ class SnippetGenerator {
List<SourceLine> _processBlock(List<SourceLine> block) {
final String firstLine = block.first.text;
if (firstLine.startsWith('new ') ||
firstLine.startsWith(_constructorRegExp)) {
if (firstLine.startsWith('new ') || firstLine.startsWith(_constructorRegExp)) {
_expressionId += 1;
return _surround('dynamic expression$_expressionId = ', block, ';');
} else if (firstLine.startsWith('await ')) {
_expressionId += 1;
return _surround(
'Future<void> expression$_expressionId() async { ', block, ' }');
} else if (block.first.text.startsWith('class ') ||
block.first.text.startsWith('enum ')) {
return _surround('Future<void> expression$_expressionId() async { ', block, ' }');
} else if (block.first.text.startsWith('class ') || block.first.text.startsWith('enum ')) {
return block;
} else if ((block.first.text.startsWith('_') ||
block.first.text.startsWith('final ')) &&
} else if ((block.first.text.startsWith('_') || block.first.text.startsWith('final ')) &&
block.first.text.contains(' = ')) {
_expressionId += 1;
return _surround(
'void expression$_expressionId() { ', block.toList(), ' }');
return _surround('void expression$_expressionId() { ', block.toList(), ' }');
} else {
final List<SourceLine> buffer = <SourceLine>[];
int blocks = 0;
@@ -218,8 +206,9 @@ class SnippetGenerator {
final List<SourceLine> description = <SourceLine>[];
final List<SkeletonInjection> components = <SkeletonInjection>[];
String? language;
final RegExp codeStartEnd =
RegExp(r'^\s*```(?<language>[-\w]+|[-\w]+ (?<section>[-\w]+))?\s*$');
final RegExp codeStartEnd = RegExp(
r'^\s*```(?<language>[-\w]+|[-\w]+ (?<section>[-\w]+))?\s*$',
);
for (final SourceLine line in sample.input) {
final RegExpMatch? match = codeStartEnd.firstMatch(line.text);
if (match != null) {
@@ -228,12 +217,15 @@ class SnippetGenerator {
if (match.namedGroup('language') != null) {
language = match[1];
if (match.namedGroup('section') != null) {
components.add(SkeletonInjection(
'code-${match.namedGroup('section')}', <SourceLine>[],
language: language!));
} else {
components.add(
SkeletonInjection('code', <SourceLine>[], language: language!));
SkeletonInjection(
'code-${match.namedGroup('section')}',
<SourceLine>[],
language: language!,
),
);
} else {
components.add(SkeletonInjection('code', <SourceLine>[], language: language!));
}
} else {
language = null;
@@ -249,8 +241,7 @@ class SnippetGenerator {
}
final List<String> descriptionLines = <String>[];
bool lastWasWhitespace = false;
for (final String line in description
.map<String>((SourceLine line) => line.text.trimRight())) {
for (final String line in description.map<String>((SourceLine line) => line.text.trimRight())) {
final bool onlyWhitespace = line.trim().isEmpty;
if (onlyWhitespace && descriptionLines.isEmpty) {
// Don't add whitespace lines until we see something without whitespace.
@@ -266,8 +257,7 @@ class SnippetGenerator {
}
sample.description = descriptionLines.join('\n').trimRight();
sample.parts = <SkeletonInjection>[
if (sample is SnippetSample)
SkeletonInjection('#assumptions', sample.assumptions),
if (sample is SnippetSample) SkeletonInjection('#assumptions', sample.assumptions),
...components,
];
return sample.parts;
@@ -282,8 +272,7 @@ class SnippetGenerator {
/// Returns a string with the HTML needed to embed in a web page for showing a
/// sample on the web page.
String generateHtml(CodeSample sample) {
final String skeleton =
_loadFileAsUtf8(configuration.getHtmlSkeletonFile(sample.type));
final String skeleton = _loadFileAsUtf8(configuration.getHtmlSkeletonFile(sample.type));
return interpolateSkeleton(sample, skeleton);
}
@@ -295,8 +284,8 @@ class SnippetGenerator {
return sample.description.splitMapJoin(
'\n',
onMatch: (Match match) => match.group(0)!,
onNonMatch: (String nonmatch) =>
nonmatch.trimRight().isEmpty ? '//' : '// ${nonmatch.trimRight()}',
onNonMatch:
(String nonmatch) => nonmatch.trimRight().isEmpty ? '//' : '// ${nonmatch.trimRight()}',
);
}
@@ -328,13 +317,11 @@ class SnippetGenerator {
final String app = sample.sourceFileContents;
sample.output = app;
if (formatOutput) {
final DartFormatter formatter =
DartFormatter(pageWidth: 80, fixes: StyleFix.all);
final DartFormatter formatter = DartFormatter(pageWidth: 80, fixes: StyleFix.all);
try {
sample.output = formatter.format(sample.output);
} on FormatterException catch (exception) {
io.stderr
.write('Code to format:\n${_addLineNumbers(sample.output)}\n');
io.stderr.write('Code to format:\n${_addLineNumbers(sample.output)}\n');
errorExit('Unable to format sample code: $exception');
}
sample.output = sortImports(sample.output);
@@ -342,39 +329,44 @@ class SnippetGenerator {
if (output != null) {
output.writeAsStringSync(sample.output);
final File metadataFile = configuration.filesystem.file(path.join(
final File metadataFile = configuration.filesystem.file(
path.join(
path.dirname(output.path),
'${path.basenameWithoutExtension(output.path)}.json'));
'${path.basenameWithoutExtension(output.path)}.json',
),
);
sample.metadata['file'] = path.basename(output.path);
final Map<String, Object?> metadata = sample.metadata;
if (metadata.containsKey('description')) {
metadata['description'] = (metadata['description']! as String)
.replaceAll(RegExp(r'^// ?', multiLine: true), '');
metadata['description'] = (metadata['description']! as String).replaceAll(
RegExp(r'^// ?', multiLine: true),
'',
);
}
metadataFile.writeAsStringSync(jsonEncoder.convert(metadata));
}
case SnippetSample _:
String app;
if (sample.sourceFile == null) {
String templateContents;
if (includeAssumptions) {
templateContents =
'${headers.map<String>((SourceLine line) {
return line.text;
}).join('\n')}\n{{#assumptions}}\n{{description}}\n{{code}}';
} else {
templateContents = '{{description}}\n{{code}}';
}
app = interpolateTemplate(
snippetData,
templateContents,
sample.metadata,
addCopyright: copyright != null,
);
String app;
if (sample.sourceFile == null) {
String templateContents;
if (includeAssumptions) {
templateContents =
'${headers.map<String>((SourceLine line) {
return line.text;
}).join('\n')}\n{{#assumptions}}\n{{description}}\n{{code}}';
} else {
app = sample.inputAsString;
templateContents = '{{description}}\n{{code}}';
}
sample.output = app;
app = interpolateTemplate(
snippetData,
templateContents,
sample.metadata,
addCopyright: copyright != null,
);
} else {
app = sample.inputAsString;
}
sample.output = app;
}
return sample.output;
}
@@ -393,33 +385,35 @@ class SnippetGenerator {
///
/// Not used for "sample" and "dartpad" samples, which use their own template.
List<SourceLine> get headers {
return _headers ??= <String>[
'// generated code',
'// ignore_for_file: unused_import',
'// ignore_for_file: unused_element',
'// ignore_for_file: unused_local_variable',
"import 'dart:async';",
"import 'dart:convert';",
"import 'dart:math' as math;",
"import 'dart:typed_data';",
"import 'dart:ui' as ui;",
"import 'package:flutter_test/flutter_test.dart';",
for (final File file in _listDartFiles(FlutterInformation.instance
.getFlutterRoot()
.childDirectory('packages')
.childDirectory('flutter')
.childDirectory('lib'))) ...<String>[
'',
'// ${file.path}',
"import 'package:flutter/${path.basename(file.path)}';",
],
].map<SourceLine>((String code) => SourceLine(code)).toList();
return _headers ??=
<String>[
'// generated code',
'// ignore_for_file: unused_import',
'// ignore_for_file: unused_element',
'// ignore_for_file: unused_local_variable',
"import 'dart:async';",
"import 'dart:convert';",
"import 'dart:math' as math;",
"import 'dart:typed_data';",
"import 'dart:ui' as ui;",
"import 'package:flutter_test/flutter_test.dart';",
for (final File file in _listDartFiles(
FlutterInformation.instance
.getFlutterRoot()
.childDirectory('packages')
.childDirectory('flutter')
.childDirectory('lib'),
)) ...<String>[
'',
'// ${file.path}',
"import 'package:flutter/${path.basename(file.path)}';",
],
].map<SourceLine>((String code) => SourceLine(code)).toList();
}
List<SourceLine>? _headers;
static List<File> _listDartFiles(Directory directory,
{bool recursive = false}) {
static List<File> _listDartFiles(Directory directory, {bool recursive = false}) {
return directory
.listSync(recursive: recursive, followLinks: false)
.whereType<File>()

View File

@@ -29,8 +29,9 @@ class SnippetDartdocParser {
static const String _dartDocPrefixWithSpace = '$_dartDocPrefix ';
/// A RegExp that matches the beginning of a dartdoc snippet or sample.
static final RegExp _dartDocSampleBeginRegex =
RegExp(r'\{@tool (?<type>sample|snippet|dartpad)(?:| (?<args>[^}]*))\}');
static final RegExp _dartDocSampleBeginRegex = RegExp(
r'\{@tool (?<type>sample|snippet|dartpad)(?:| (?<args>[^}]*))\}',
);
/// A RegExp that matches the end of a dartdoc snippet or sample.
static final RegExp _dartDocSampleEndRegex = RegExp(r'\{@end-tool\}');
@@ -42,8 +43,7 @@ class SnippetDartdocParser {
static final RegExp _codeBlockEndRegex = RegExp(r'///\s+```\s*$');
/// A RegExp that matches a linked sample pointer.
static final RegExp _filePointerRegex =
RegExp(r'\*\* See code in (?<file>[^\]]+) \*\*');
static final RegExp _filePointerRegex = RegExp(r'\*\* See code in (?<file>[^\]]+) \*\*');
/// Parses the assumptions in the "Examples can assume:" block at the top of
/// the `assumptionsFile` and adds them to the code samples contained in the
@@ -54,8 +54,9 @@ class SnippetDartdocParser {
bool silent = true,
}) {
final List<SourceLine> assumptions = parseAssumptions(assumptionsFile);
for (final CodeSample sample in elements
.expand<CodeSample>((SourceElement element) => element.samples)) {
for (final CodeSample sample in elements.expand<CodeSample>(
(SourceElement element) => element.samples,
)) {
if (sample is SnippetSample) {
sample.assumptions = assumptions;
}
@@ -91,22 +92,21 @@ class SnippetDartdocParser {
// Snippet input comes in with the comment markers stripped, so we add them
// back to make it conform to the source format, so we can use the same
// parser for editing samples as we do for processing docs.
...input
.readAsLinesSync()
.map<String>((String line) => '/// $line'.trimRight()),
...input.readAsLinesSync().map<String>((String line) => '/// $line'.trimRight()),
'/// {@end-tool}',
];
for (final String line in inputStrings) {
lines.add(
SourceLine(line,
element: element ?? '', line: lineNumber, file: sourceFile),
);
lines.add(SourceLine(line, element: element ?? '', line: lineNumber, file: sourceFile));
lineNumber++;
}
// No need to get assumptions: dartdoc won't give that to us.
final SourceElement newElement = SourceElement(
SourceElementType.unknownType, element!, -1,
file: input, comment: lines);
SourceElementType.unknownType,
element!,
-1,
file: input,
comment: lines,
);
parseFromComments(<SourceElement>[newElement], silent: silent);
for (final CodeSample sample in newElement.samples) {
sample.metadata.addAll(<String, Object?>{
@@ -144,14 +144,16 @@ class SnippetDartdocParser {
continue;
}
if (inPreamble) {
preamble.add(SourceLine(
line.substring(3),
startChar: charPosition,
endChar: charPosition + line.length + 1,
element: '#assumptions',
file: file,
line: lineNumber,
));
preamble.add(
SourceLine(
line.substring(3),
startChar: charPosition,
endChar: charPosition + line.length + 1,
element: '#assumptions',
file: file,
line: lineNumber,
),
);
}
lineNumber++;
charPosition += line.length + 1;
@@ -162,10 +164,7 @@ class SnippetDartdocParser {
/// This parses the code snippets from the documentation comments in the given
/// `elements`, and sets the resulting samples as the `samples` member of
/// each element in the supplied iterable.
void parseFromComments(
Iterable<SourceElement> elements, {
bool silent = true,
}) {
void parseFromComments(Iterable<SourceElement> elements, {bool silent = true}) {
int dartpadCount = 0;
int sampleCount = 0;
int snippetCount = 0;
@@ -188,10 +187,12 @@ class SnippetDartdocParser {
}
if (!silent) {
print('Found:\n'
' $snippetCount snippet code blocks,\n'
' $sampleCount non-dartpad sample code sections, and\n'
' $dartpadCount dartpad sections.\n');
print(
'Found:\n'
' $snippetCount snippet code blocks,\n'
' $sampleCount non-dartpad sample code sections, and\n'
' $dartpadCount dartpad sections.\n',
);
}
}
@@ -216,19 +217,16 @@ class SnippetDartdocParser {
final String trimmedLine = line.text.trim();
if (inSnippet) {
if (!trimmedLine.startsWith(_dartDocPrefix)) {
throw SnippetException('Snippet section unterminated.',
file: line.file?.path, line: line.line);
throw SnippetException(
'Snippet section unterminated.',
file: line.file?.path,
line: line.line,
);
}
if (_dartDocSampleEndRegex.hasMatch(trimmedLine)) {
switch (snippetArgs.first) {
case 'snippet':
samples.add(
SnippetSample(
block,
index: index++,
lineProto: line,
),
);
samples.add(SnippetSample(block, index: index++, lineProto: line));
case 'sample':
if (linkedFile != null) {
samples.add(
@@ -243,12 +241,7 @@ class SnippetDartdocParser {
break;
}
samples.add(
ApplicationSample(
input: block,
args: snippetArgs,
index: index++,
lineProto: line,
),
ApplicationSample(input: block, args: snippetArgs, index: index++, lineProto: line),
);
case 'dartpad':
if (linkedFile != null) {
@@ -264,16 +257,10 @@ class SnippetDartdocParser {
break;
}
samples.add(
DartpadSample(
input: block,
args: snippetArgs,
index: index++,
lineProto: line,
),
DartpadSample(input: block, args: snippetArgs, index: index++, lineProto: line),
);
default:
throw SnippetException(
'Unknown snippet type ${snippetArgs.first}');
throw SnippetException('Unknown snippet type ${snippetArgs.first}');
}
snippetArgs = <String>[];
block = <SourceLine>[];
@@ -299,18 +286,19 @@ class SnippetDartdocParser {
}
final RegExpMatch match = _filePointerRegex.firstMatch(trimmedLine)!;
linkedFile = filesystem.file(
path.join(flutterRoot.absolute.path, match.namedGroup('file')));
path.join(flutterRoot.absolute.path, match.namedGroup('file')),
);
} else {
block.add(line.copyWith(
text: line.text.replaceFirst(RegExp(r'\s*/// ?'), '')));
block.add(line.copyWith(text: line.text.replaceFirst(RegExp(r'\s*/// ?'), '')));
}
} else {
if (_dartDocSampleEndRegex.hasMatch(trimmedLine)) {
if (inDart) {
throw SnippetException(
"Dart section didn't terminate before end of sample",
file: line.file?.path,
line: line.line);
"Dart section didn't terminate before end of sample",
file: line.file?.path,
line: line.line,
);
}
}
if (inDart) {
@@ -344,10 +332,10 @@ class SnippetDartdocParser {
}
}
if (!inSnippet && !inDart) {
final RegExpMatch? sampleMatch =
_dartDocSampleBeginRegex.firstMatch(trimmedLine);
final RegExpMatch? sampleMatch = _dartDocSampleBeginRegex.firstMatch(trimmedLine);
if (sampleMatch != null) {
inSnippet = sampleMatch.namedGroup('type') == 'snippet' ||
inSnippet =
sampleMatch.namedGroup('type') == 'snippet' ||
sampleMatch.namedGroup('type') == 'sample' ||
sampleMatch.namedGroup('type') == 'dartpad';
if (inSnippet) {
@@ -355,12 +343,10 @@ class SnippetDartdocParser {
// There are arguments to the snippet tool to keep track of.
snippetArgs = <String>[
sampleMatch.namedGroup('type')!,
..._splitUpQuotedArgs(sampleMatch.namedGroup('args')!)
..._splitUpQuotedArgs(sampleMatch.namedGroup('args')!),
];
} else {
snippetArgs = <String>[
sampleMatch.namedGroup('type')!,
];
snippetArgs = <String>[sampleMatch.namedGroup('type')!];
}
}
}
@@ -398,10 +384,11 @@ class SnippetDartdocParser {
// Match group 3 (value) is a quoted arg, if any, without the quotes.
// Match group 4 (unquoted) is the unquoted arg, if any.
final RegExp argMatcher = RegExp(
r'(?<option>[-_a-zA-Z0-9]+=)?' // option name
r'(?:' // Start a new non-capture group for the two possibilities.
r'''(?<quote>["'])(?<value>(?:\\{2})*|(?:.*?[^\\](?:\\{2})*))\2|''' // value with quotes.
r'(?<unquoted>[^ ]+))'); // without quotes.
r'(?<option>[-_a-zA-Z0-9]+=)?' // option name
r'(?:' // Start a new non-capture group for the two possibilities.
r'''(?<quote>["'])(?<value>(?:\\{2})*|(?:.*?[^\\](?:\\{2})*))\2|''' // value with quotes.
r'(?<unquoted>[^ ]+))',
); // without quotes.
final Iterable<RegExpMatch> matches = argMatcher.allMatches(argsAsString);
// Remove quotes around args, then for any args that look like assignments
@@ -410,8 +397,7 @@ class SnippetDartdocParser {
// functionality of "option=value".
return matches.map<String>((RegExpMatch match) {
String option = '';
if (match.namedGroup('option') != null &&
!match.namedGroup('option')!.startsWith('-')) {
if (match.namedGroup('option') != null && !match.namedGroup('option')!.startsWith('-')) {
option = '--';
}
if (match.namedGroup('quote') != null) {

View File

@@ -63,11 +63,9 @@ class FlutterInformation {
return getFlutterInformation()['flutterRoot'] as Directory;
}
Version getFlutterVersion() =>
getFlutterInformation()['frameworkVersion'] as Version;
Version getFlutterVersion() => getFlutterInformation()['frameworkVersion'] as Version;
Version getDartSdkVersion() =>
getFlutterInformation()['dartSdkVersion'] as Version;
Version getDartSdkVersion() => getFlutterInformation()['dartSdkVersion'] as Version;
Map<String, dynamic>? _cachedFlutterInformation;
@@ -82,31 +80,37 @@ class FlutterInformation {
} else {
String flutterCommand;
if (platform.environment['FLUTTER_ROOT'] != null) {
flutterCommand = filesystem
.directory(platform.environment['FLUTTER_ROOT'])
.childDirectory('bin')
.childFile('flutter')
.absolute
.path;
flutterCommand =
filesystem
.directory(platform.environment['FLUTTER_ROOT'])
.childDirectory('bin')
.childFile('flutter')
.absolute
.path;
} else {
flutterCommand = 'flutter';
}
io.ProcessResult result;
try {
result = processManager.runSync(
<String>[flutterCommand, '--version', '--machine'],
stdoutEncoding: utf8);
result = processManager.runSync(<String>[
flutterCommand,
'--version',
'--machine',
], stdoutEncoding: utf8);
} on io.ProcessException catch (e) {
throw SnippetException(
'Unable to determine Flutter information. Either set FLUTTER_ROOT, or place flutter command in your path.\n$e');
'Unable to determine Flutter information. Either set FLUTTER_ROOT, or place flutter command in your path.\n$e',
);
}
if (result.exitCode != 0) {
throw SnippetException(
'Unable to determine Flutter information, because of abnormal exit to flutter command.');
'Unable to determine Flutter information, because of abnormal exit to flutter command.',
);
}
flutterVersionJson = (result.stdout as String).replaceAll(
'Waiting for another flutter command to release the startup lock...',
'');
'Waiting for another flutter command to release the startup lock...',
'',
);
}
final Map<String, dynamic> flutterVersion =
@@ -115,25 +119,25 @@ class FlutterInformation {
flutterVersion['frameworkVersion'] == null ||
flutterVersion['dartSdkVersion'] == null) {
throw SnippetException(
'Flutter command output has unexpected format, unable to determine flutter root location.');
'Flutter command output has unexpected format, unable to determine flutter root location.',
);
}
final Map<String, dynamic> info = <String, dynamic>{};
info['flutterRoot'] =
filesystem.directory(flutterVersion['flutterRoot']! as String);
info['frameworkVersion'] =
Version.parse(flutterVersion['frameworkVersion'] as String);
info['flutterRoot'] = filesystem.directory(flutterVersion['flutterRoot']! as String);
info['frameworkVersion'] = Version.parse(flutterVersion['frameworkVersion'] as String);
final RegExpMatch? dartVersionRegex =
RegExp(r'(?<base>[\d.]+)(?:\s+\(build (?<detail>[-.\w]+)\))?')
.firstMatch(flutterVersion['dartSdkVersion'] as String);
final RegExpMatch? dartVersionRegex = RegExp(
r'(?<base>[\d.]+)(?:\s+\(build (?<detail>[-.\w]+)\))?',
).firstMatch(flutterVersion['dartSdkVersion'] as String);
if (dartVersionRegex == null) {
throw SnippetException(
'Flutter command output has unexpected format, unable to parse dart SDK version ${flutterVersion['dartSdkVersion']}.');
'Flutter command output has unexpected format, unable to parse dart SDK version ${flutterVersion['dartSdkVersion']}.',
);
}
info['dartSdkVersion'] = Version.parse(
dartVersionRegex.namedGroup('detail') ??
dartVersionRegex.namedGroup('base')!);
dartVersionRegex.namedGroup('detail') ?? dartVersionRegex.namedGroup('base')!,
);
_cachedFlutterInformation = info;
return info;
@@ -154,31 +158,28 @@ String interpolateTemplate(
return '';
}
// We don't wrap some sections, because otherwise they generate invalid files.
final String result = <String>[
...contents,
].join('\n');
final String result = <String>[...contents].join('\n');
final RegExp wrappingNewlines = RegExp(r'^\n*(.*)\n*$', dotAll: true);
return result.replaceAllMapped(
wrappingNewlines, (Match match) => match.group(1)!);
return result.replaceAllMapped(wrappingNewlines, (Match match) => match.group(1)!);
}
return '${addCopyright ? '{{copyright}}\n\n' : ''}$template'
.replaceAllMapped(RegExp(r'{{([^}]+)}}'), (Match match) {
final String name = match[1]!;
final int componentIndex = injections
.indexWhere((SkeletonInjection injection) => injection.name == name);
if (metadata[name] != null && componentIndex == -1) {
// If the match isn't found in the injections, then just return the
// metadata entry.
return wrapSectionMarker((metadata[name]! as String).split('\n'),
name: name);
}
return wrapSectionMarker(
componentIndex >= 0
? injections[componentIndex].stringContents
: <String>[],
name: name);
}).replaceAll(RegExp(r'\n\n+'), '\n\n');
final String name = match[1]!;
final int componentIndex = injections.indexWhere(
(SkeletonInjection injection) => injection.name == name,
);
if (metadata[name] != null && componentIndex == -1) {
// If the match isn't found in the injections, then just return the
// metadata entry.
return wrapSectionMarker((metadata[name]! as String).split('\n'), name: name);
}
return wrapSectionMarker(
componentIndex >= 0 ? injections[componentIndex].stringContents : <String>[],
name: name,
);
})
.replaceAll(RegExp(r'\n\n+'), '\n\n');
}
class SampleStats {
@@ -213,8 +214,7 @@ class SampleStats {
}
Iterable<CodeSample> getSamplesInElements(Iterable<SourceElement>? elements) {
return elements
?.expand<CodeSample>((SourceElement element) => element.samples) ??
return elements?.expand<CodeSample>((SourceElement element) => element.samples) ??
const <CodeSample>[];
}
@@ -231,25 +231,24 @@ SampleStats getSampleStats(SourceElement element) {
final int applications = element.applicationSampleCount;
final String sampleCount = <String>[
if (snippets > 0) '$snippets snippet${snippets != 1 ? 's' : ''}',
if (applications > 0)
'$applications application sample${applications != 1 ? 's' : ''}',
if (dartpads > 0) '$dartpads dartpad sample${dartpads != 1 ? 's' : ''}'
if (applications > 0) '$applications application sample${applications != 1 ? 's' : ''}',
if (dartpads > 0) '$dartpads dartpad sample${dartpads != 1 ? 's' : ''}',
].join(', ');
final int wordCount = element.wordCount;
final int lineCount = element.lineCount;
final int linkCount = element.referenceCount;
final String description = <String>[
'Documentation has $wordCount ${wordCount == 1 ? 'word' : 'words'} on ',
'$lineCount ${lineCount == 1 ? 'line' : 'lines'}',
if (linkCount > 0 && element.hasSeeAlso) ', ',
if (linkCount > 0 && !element.hasSeeAlso) ' and ',
if (linkCount > 0)
'refers to $linkCount other ${linkCount == 1 ? 'symbol' : 'symbols'}',
if (linkCount > 0 && element.hasSeeAlso) ', and ',
if (linkCount == 0 && element.hasSeeAlso) 'and ',
if (element.hasSeeAlso) 'has a "See also:" section',
'.',
].join();
final String description =
<String>[
'Documentation has $wordCount ${wordCount == 1 ? 'word' : 'words'} on ',
'$lineCount ${lineCount == 1 ? 'line' : 'lines'}',
if (linkCount > 0 && element.hasSeeAlso) ', ',
if (linkCount > 0 && !element.hasSeeAlso) ' and ',
if (linkCount > 0) 'refers to $linkCount other ${linkCount == 1 ? 'symbol' : 'symbols'}',
if (linkCount > 0 && element.hasSeeAlso) ', and ',
if (linkCount == 0 && element.hasSeeAlso) 'and ',
if (element.hasSeeAlso) 'has a "See also:" section',
'.',
].join();
return SampleStats(
totalSamples: total,
dartpadSamples: dartpads,