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

@@ -67,29 +67,27 @@ String getChannelName({
final RegExp gitBranchRegexp = RegExp(r'^## (?<branch>.*)');
final ProcessResult gitResult = processManager.runSync(
<String>['git', 'status', '-b', '--porcelain'],
// Use the FLUTTER_ROOT, if defined.
workingDirectory: platform.environment['FLUTTER_ROOT']?.trim() ??
filesystem.currentDirectory.path,
// Adding extra debugging output to help debug why git status inexplicably fails
// (random non-zero error code) about 2% of the time.
environment: <String, String>{'GIT_TRACE': '2', 'GIT_TRACE_SETUP': '2'});
<String>['git', 'status', '-b', '--porcelain'],
// Use the FLUTTER_ROOT, if defined.
workingDirectory:
platform.environment['FLUTTER_ROOT']?.trim() ?? filesystem.currentDirectory.path,
// Adding extra debugging output to help debug why git status inexplicably fails
// (random non-zero error code) about 2% of the time.
environment: <String, String>{'GIT_TRACE': '2', 'GIT_TRACE_SETUP': '2'},
);
if (gitResult.exitCode != 0) {
throw GitStatusFailed(gitResult);
}
final RegExpMatch? gitBranchMatch = gitBranchRegexp
.firstMatch((gitResult.stdout as String).trim().split('\n').first);
final RegExpMatch? gitBranchMatch = gitBranchRegexp.firstMatch(
(gitResult.stdout as String).trim().split('\n').first,
);
return gitBranchMatch == null
? '<unknown>'
: gitBranchMatch.namedGroup('branch')!.split('...').first;
}
const List<String> sampleTypes = <String>[
'snippet',
'sample',
'dartpad',
];
const List<String> sampleTypes = <String>['snippet', 'sample', 'dartpad'];
// This is a hack to workaround the fact that git status inexplicably fails
// (with random non-zero error code) about 2% of the time.
@@ -104,8 +102,7 @@ String getChannelNameWithRetries({
return getChannelName(platform: platform, processManager: processManager);
} on GitStatusFailed catch (e) {
retryCount += 1;
stderr.write(
'git status failed, retrying ($retryCount)\nError report:\n$e');
stderr.write('git status failed, retrying ($retryCount)\nError report:\n$e');
}
}
@@ -123,18 +120,16 @@ void main(List<String> argList) {
defaultsTo: 'dartpad',
allowed: sampleTypes,
allowedHelp: <String, String>{
'dartpad':
'Produce a code sample application for using in Dartpad.',
'sample':
'Produce a code sample application.',
'snippet':
'Produce a nicely formatted piece of sample code.',
'dartpad': 'Produce a code sample application for using in Dartpad.',
'sample': 'Produce a code sample application.',
'snippet': 'Produce a nicely formatted piece of sample code.',
},
help: 'The type of snippet to produce.',
);
parser.addOption(
_kOutputOption,
help: 'The output name for the generated sample application. Overrides '
help:
'The output name for the generated sample application. Overrides '
'the naming generated by the --$_kPackageOption/--$_kLibraryOption/--$_kElementOption '
'arguments. Metadata will be written alongside in a .json file. '
'The basename of this argument is used as the ID. If this is a '
@@ -194,8 +189,9 @@ void main(List<String> argList) {
if (args[_kInputOption] == null) {
stderr.writeln(parser.usage);
errorExit(
'The --$_kInputOption option must be specified, either on the command '
'line, or in the INPUT environment variable.');
'The --$_kInputOption option must be specified, either on the command '
'line, or in the INPUT environment variable.',
);
return;
}
@@ -221,8 +217,7 @@ void main(List<String> argList) {
if (outputPath.isAbsolute) {
output = outputPath;
} else {
output =
filesystem.file(path.join(outputDirectory.path, outputPath.path));
output = filesystem.file(path.join(outputDirectory.path, outputPath.path));
}
} else {
final List<String> idParts = <String>[];
@@ -239,9 +234,11 @@ void main(List<String> argList) {
idParts.add(serial);
}
if (idParts.isEmpty) {
errorExit('Unable to determine ID. At least one of --$_kPackageOption, '
'--$_kLibraryOption, --$_kElementOption, -$_kSerialOption, or the environment variables '
'PACKAGE_NAME, LIBRARY_NAME, ELEMENT_NAME, or INVOCATION_INDEX must be non-empty.');
errorExit(
'Unable to determine ID. At least one of --$_kPackageOption, '
'--$_kLibraryOption, --$_kElementOption, -$_kSerialOption, or the environment variables '
'PACKAGE_NAME, LIBRARY_NAME, ELEMENT_NAME, or INVOCATION_INDEX must be non-empty.',
);
return;
}
id = idParts.join('.');
@@ -249,9 +246,8 @@ void main(List<String> argList) {
}
output.parent.createSync(recursive: true);
final int? sourceLine = environment['SOURCE_LINE'] != null
? int.tryParse(environment['SOURCE_LINE']!)
: null;
final int? sourceLine =
environment['SOURCE_LINE'] != null ? int.tryParse(environment['SOURCE_LINE']!) : null;
final String sourcePath = environment['SOURCE_PATH'] ?? 'unknown.dart';
final SnippetDartdocParser sampleParser = SnippetDartdocParser(filesystem);
final SourceElement element = sampleParser.parseFromDartdocToolFile(
@@ -262,8 +258,7 @@ void main(List<String> argList) {
type: sampleType,
);
final Map<String, Object?> metadata = <String, Object?>{
'channel': getChannelNameWithRetries(
platform: platform, processManager: processManager),
'channel': getChannelNameWithRetries(platform: platform, processManager: processManager),
'serial': serial,
'id': id,
'package': packageName,
@@ -273,11 +268,7 @@ void main(List<String> argList) {
for (final CodeSample sample in element.samples) {
sample.metadata.addAll(metadata);
snippetGenerator.generateCode(
sample,
output: output,
formatOutput: formatOutput,
);
snippetGenerator.generateCode(sample, output: output, formatOutput: formatOutput);
print(snippetGenerator.generateHtml(sample));
}

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,

View File

@@ -18,32 +18,44 @@ void main() {
);
});
test('config directory is correct', () async {
expect(config.configDirectory.path,
matches(RegExp(r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config')));
expect(
config.configDirectory.path,
matches(RegExp(r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config')),
);
});
test('skeleton directory is correct', () async {
expect(
config.skeletonsDirectory.path,
matches(RegExp(
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons')));
config.skeletonsDirectory.path,
matches(RegExp(r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons')),
);
});
test('html skeleton file for sample is correct', () async {
expect(
config.getHtmlSkeletonFile('snippet').path,
matches(RegExp(
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]snippet.html')));
config.getHtmlSkeletonFile('snippet').path,
matches(
RegExp(
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]snippet.html',
),
),
);
});
test('html skeleton file for app with no dartpad is correct', () async {
expect(
config.getHtmlSkeletonFile('sample').path,
matches(RegExp(
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]sample.html')));
config.getHtmlSkeletonFile('sample').path,
matches(
RegExp(r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]sample.html'),
),
);
});
test('html skeleton file for app with dartpad is correct', () async {
expect(
config.getHtmlSkeletonFile('dartpad').path,
matches(RegExp(
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]dartpad-sample.html')));
config.getHtmlSkeletonFile('dartpad').path,
matches(
RegExp(
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]dartpad-sample.html',
),
),
);
});
});
}

View File

@@ -8,8 +8,7 @@ import 'dart:io';
import 'package:process/process.dart';
class FakeProcessManager extends LocalProcessManager {
FakeProcessManager(
{this.stdout = '', this.stderr = '', this.exitCode = 0, this.pid = 1});
FakeProcessManager({this.stdout = '', this.stderr = '', this.exitCode = 0, this.pid = 1});
int runs = 0;
String stdout;

View File

@@ -29,20 +29,18 @@ String? _getStandardStateLocation() {
return env['ANALYZER_STATE_LOCATION_OVERRIDE'];
}
final String? home =
io.Platform.isWindows ? env['LOCALAPPDATA'] : env['HOME'];
return home != null && io.FileSystemEntity.isDirectorySync(home)
? join(home, _SERVER_DIR)
: null;
final String? home = io.Platform.isWindows ? env['LOCALAPPDATA'] : env['HOME'];
return home != null && io.FileSystemEntity.isDirectorySync(home) ? join(home, _SERVER_DIR) : null;
}
/// A `dart:io` based implementation of [ResourceProvider].
class FileSystemResourceProvider implements ResourceProvider {
FileSystemResourceProvider(this.filesystem, {String? stateLocation})
: _stateLocation = stateLocation ?? _getStandardStateLocation();
: _stateLocation = stateLocation ?? _getStandardStateLocation();
static final FileSystemResourceProvider instance =
FileSystemResourceProvider(const file.LocalFileSystem());
static final FileSystemResourceProvider instance = FileSystemResourceProvider(
const file.LocalFileSystem(),
);
/// The path to the base folder where state is stored.
final String? _stateLocation;
@@ -77,8 +75,7 @@ class FileSystemResourceProvider implements ResourceProvider {
@override
Folder? getStateLocation(String pluginId) {
if (_stateLocation != null) {
final file.Directory directory =
filesystem.directory(join(_stateLocation, pluginId));
final file.Directory directory = filesystem.directory(join(_stateLocation, pluginId));
directory.createSync(recursive: true);
return _PhysicalFolder(directory);
}
@@ -221,14 +218,15 @@ class _PhysicalFolder extends _PhysicalResource implements Folder {
const _PhysicalFolder(io.Directory super.directory);
@override
Stream<WatchEvent> get changes =>
DirectoryWatcher(_entry.path).events.handleError((Object error) {},
test: (dynamic error) =>
error is io.FileSystemException &&
// Don't suppress "Directory watcher closed," so the outer
// listener can see the interruption & act on it.
!error.message
.startsWith('Directory watcher closed unexpectedly'));
Stream<WatchEvent> get changes => DirectoryWatcher(_entry.path).events.handleError(
(Object error) {},
test:
(dynamic error) =>
error is io.FileSystemException &&
// Don't suppress "Directory watcher closed," so the outer
// listener can see the interruption & act on it.
!error.message.startsWith('Directory watcher closed unexpectedly'),
);
@override
bool get isRoot {
@@ -317,8 +315,7 @@ class _PhysicalFolder extends _PhysicalResource implements Folder {
@override
Folder resolveSymbolicLinksSync() {
try {
return _PhysicalFolder(
io.Directory(_directory.resolveSymbolicLinksSync()));
return _PhysicalFolder(io.Directory(_directory.resolveSymbolicLinksSync()));
} on io.FileSystemException catch (exception) {
throw _wrapException(exception);
}
@@ -416,8 +413,7 @@ abstract class _PhysicalResource implements Resource {
shortName == r'COM2' ||
shortName == r'COM3' ||
shortName == r'COM4') {
throw FileSystemException(
path, 'Windows device drivers cannot be read.');
throw FileSystemException(path, 'Windows device drivers cannot be read.');
}
}
}

View File

@@ -31,10 +31,10 @@ void main() {
setUp(() {
// Create a new filesystem.
memoryFileSystem = MemoryFileSystem();
tmpDir = memoryFileSystem.systemTempDirectory
.createTempSync('flutter_snippets_test.');
final Directory flutterRoot =
memoryFileSystem.directory(path.join(tmpDir.absolute.path, 'flutter'));
tmpDir = memoryFileSystem.systemTempDirectory.createTempSync('flutter_snippets_test.');
final Directory flutterRoot = memoryFileSystem.directory(
path.join(tmpDir.absolute.path, 'flutter'),
);
FlutterInformation.instance = FakeFlutterInformation(flutterRoot);
});
@@ -53,7 +53,9 @@ import 'packages:alpha/alpha.dart'; // first
void main() {}
''');
expect(result, equals('''
expect(
result,
equals('''
// Unit comment
// first import
@@ -64,7 +66,8 @@ import 'packages:beta/beta.dart'; // second
import 'packages:gamma/gamma.dart'; // third
void main() {}
'''));
'''),
);
});
test('Sorting dart and packages works', () async {
final String result = sortImports('''
@@ -84,7 +87,9 @@ import 'dart:async';
void main() {}
''');
expect(result, equals('''
expect(
result,
equals('''
// Unit comment
// first dart
@@ -98,6 +103,7 @@ import 'packages:beta/beta.dart'; // second
import 'packages:gamma/gamma.dart'; // third
void main() {}
'''));
'''),
);
});
}

View File

@@ -62,28 +62,30 @@ void main() {
setUp(() {
// Create a new filesystem.
memoryFileSystem = MemoryFileSystem();
tmpDir = memoryFileSystem.systemTempDirectory
.createTempSync('flutter_snippets_test.');
flutterRoot = memoryFileSystem
.directory(path.join(tmpDir.absolute.path, 'flutter'));
tmpDir = memoryFileSystem.systemTempDirectory.createTempSync('flutter_snippets_test.');
flutterRoot = memoryFileSystem.directory(path.join(tmpDir.absolute.path, 'flutter'));
configuration = FlutterRepoSnippetConfiguration(
flutterRoot: flutterRoot, filesystem: memoryFileSystem);
flutterRoot: flutterRoot,
filesystem: memoryFileSystem,
);
configuration.skeletonsDirectory.createSync(recursive: true);
<String>['dartpad', 'sample', 'snippet'].forEach(writeSkeleton);
FlutterInformation.instance = FakeFlutterInformation(flutterRoot);
generator = SnippetGenerator(
configuration: configuration,
filesystem: memoryFileSystem,
flutterRoot: configuration.skeletonsDirectory.parent);
configuration: configuration,
filesystem: memoryFileSystem,
flutterRoot: configuration.skeletonsDirectory.parent,
);
});
test('parses from comments', () async {
final File inputFile = _createSnippetSourceFile(tmpDir, memoryFileSystem);
final Iterable<SourceElement> elements = getFileElements(inputFile,
resourceProvider: FileSystemResourceProvider(memoryFileSystem));
final Iterable<SourceElement> elements = getFileElements(
inputFile,
resourceProvider: FileSystemResourceProvider(memoryFileSystem),
);
expect(elements, isNotEmpty);
final SnippetDartdocParser sampleParser =
SnippetDartdocParser(memoryFileSystem);
final SnippetDartdocParser sampleParser = SnippetDartdocParser(memoryFileSystem);
sampleParser.parseFromComments(elements);
sampleParser.parseAndAddAssumptions(elements, inputFile);
expect(elements.length, equals(7));
@@ -94,60 +96,72 @@ void main() {
final String code = generator.generateCode(element.samples.first);
expect(code, contains('// Description'));
expect(
code,
contains(RegExp(
'''^String elementName = '${element.elementName}';\$''',
multiLine: true)));
code,
contains(
RegExp('''^String elementName = '${element.elementName}';\$''', multiLine: true),
),
);
final String html = generator.generateHtml(element.samples.first);
expect(
html,
contains(RegExp(
'''^<pre>String elementName = &#39;${element.elementName}&#39;;.*\$''',
multiLine: true)));
html,
contains(
RegExp(
'''^<pre>String elementName = &#39;${element.elementName}&#39;;.*\$''',
multiLine: true,
),
),
);
expect(
html,
contains(
'<div class="snippet-description">{@end-inject-html}Description{@inject-html}</div>\n'));
html,
contains(
'<div class="snippet-description">{@end-inject-html}Description{@inject-html}</div>\n',
),
);
}
expect(sampleCount, equals(8));
});
test('parses dartpad samples from linked file', () async {
final File inputFile = _createDartpadSourceFile(
tmpDir, memoryFileSystem, flutterRoot,
linked: true);
final Iterable<SourceElement> elements = getFileElements(inputFile,
resourceProvider: FileSystemResourceProvider(memoryFileSystem));
tmpDir,
memoryFileSystem,
flutterRoot,
linked: true,
);
final Iterable<SourceElement> elements = getFileElements(
inputFile,
resourceProvider: FileSystemResourceProvider(memoryFileSystem),
);
expect(elements, isNotEmpty);
final SnippetDartdocParser sampleParser =
SnippetDartdocParser(memoryFileSystem);
final SnippetDartdocParser sampleParser = SnippetDartdocParser(memoryFileSystem);
sampleParser.parseFromComments(elements);
expect(elements.length, equals(1));
int sampleCount = 0;
for (final SourceElement element in elements) {
expect(element.samples.length, greaterThanOrEqualTo(1));
sampleCount += element.samples.length;
final String code =
generator.generateCode(element.samples.first, formatOutput: false);
final String code = generator.generateCode(element.samples.first, formatOutput: false);
expect(code, contains('// Description'));
expect(
code,
contains(RegExp('^void ${element.name}Sample\\(\\) \\{.*\$',
multiLine: true)));
code,
contains(RegExp('^void ${element.name}Sample\\(\\) \\{.*\$', multiLine: true)),
);
final String html = generator.generateHtml(element.samples.first);
expect(
html,
contains(RegExp(
'''^<iframe class="snippet-dartpad" src="https://dartpad.dev/.*sample_id=${element.name}.0.*></iframe>.*\$''',
multiLine: true)));
html,
contains(
RegExp(
'''^<iframe class="snippet-dartpad" src="https://dartpad.dev/.*sample_id=${element.name}.0.*></iframe>.*\$''',
multiLine: true,
),
),
);
}
expect(sampleCount, equals(1));
});
test('parses assumptions', () async {
final File inputFile = _createSnippetSourceFile(tmpDir, memoryFileSystem);
final SnippetDartdocParser sampleParser =
SnippetDartdocParser(memoryFileSystem);
final List<SourceLine> assumptions =
sampleParser.parseAssumptions(inputFile);
final SnippetDartdocParser sampleParser = SnippetDartdocParser(memoryFileSystem);
final List<SourceLine> assumptions = sampleParser.parseAssumptions(inputFile);
expect(assumptions.length, equals(1));
expect(assumptions.first.text, equals('int integer = 3;'));
});
@@ -245,8 +259,11 @@ class DocumentedClass {
}
File _createDartpadSourceFile(
Directory tmpDir, FileSystem filesystem, Directory flutterRoot,
{bool linked = false}) {
Directory tmpDir,
FileSystem filesystem,
Directory flutterRoot, {
bool linked = false,
}) {
final File linkedFile =
filesystem.file(path.join(flutterRoot.absolute.path, 'linked_file.dart'))
..createSync(recursive: true)
@@ -262,10 +279,11 @@ void DocumentedClassSample() {
}
''');
final String source = linked
? '''
final String source =
linked
? '''
/// ** See code in ${path.relative(linkedFile.path, from: flutterRoot.absolute.path)} **'''
: '''
: '''
/// ```dart
/// void DocumentedClassSample() {
/// String elementName = 'DocumentedClass';

View File

@@ -65,34 +65,36 @@ void main() {
setUp(() {
// Create a new filesystem.
memoryFileSystem = MemoryFileSystem();
tmpDir = memoryFileSystem.systemTempDirectory
.createTempSync('flutter_snippets_test.');
tmpDir = memoryFileSystem.systemTempDirectory.createTempSync('flutter_snippets_test.');
configuration = FlutterRepoSnippetConfiguration(
flutterRoot: memoryFileSystem
.directory(path.join(tmpDir.absolute.path, 'flutter')),
filesystem: memoryFileSystem);
flutterRoot: memoryFileSystem.directory(path.join(tmpDir.absolute.path, 'flutter')),
filesystem: memoryFileSystem,
);
configuration.skeletonsDirectory.createSync(recursive: true);
<String>['dartpad', 'sample', 'snippet'].forEach(writeSkeleton);
FlutterInformation.instance =
FakeFlutterInformation(configuration.flutterRoot);
FlutterInformation.instance = FakeFlutterInformation(configuration.flutterRoot);
generator = SnippetGenerator(
configuration: configuration,
filesystem: memoryFileSystem,
flutterRoot: configuration.skeletonsDirectory.parent);
configuration: configuration,
filesystem: memoryFileSystem,
flutterRoot: configuration.skeletonsDirectory.parent,
);
});
test('generates samples', () async {
final File inputFile = memoryFileSystem
.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
..createSync(recursive: true)
..writeAsStringSync(r'''
final File inputFile =
memoryFileSystem.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
..createSync(recursive: true)
..writeAsStringSync(r'''
A description of the sample.
On several lines.
** See code in examples/api/widgets/foo/foo_example.0.dart **
''');
final String examplePath = path.join(configuration.flutterRoot.path, 'examples/api/widgets/foo/foo_example.0.dart');
final String examplePath = path.join(
configuration.flutterRoot.path,
'examples/api/widgets/foo/foo_example.0.dart',
);
memoryFileSystem.file(examplePath)
..create(recursive: true)
..writeAsStringSync('''
@@ -102,12 +104,11 @@ On several lines.
void main() {
runApp(MaterialApp(title: 'foo'));
}\n'''
);
final File outputFile = memoryFileSystem
.file(path.join(tmpDir.absolute.path, 'snippet_out.txt'));
final SnippetDartdocParser sampleParser =
SnippetDartdocParser(memoryFileSystem);
}\n''');
final File outputFile = memoryFileSystem.file(
path.join(tmpDir.absolute.path, 'snippet_out.txt'),
);
final SnippetDartdocParser sampleParser = SnippetDartdocParser(memoryFileSystem);
const String sourcePath = 'packages/flutter/lib/src/widgets/foo.dart';
const int sourceLine = 222;
final SourceElement element = sampleParser.parseFromDartdocToolFile(
@@ -119,26 +120,22 @@ void main() {
);
expect(element.samples, isNotEmpty);
element.samples.first.metadata.addAll(<String, Object?>{
'channel': 'stable',
});
final String code = generator.generateCode(
element.samples.first,
output: outputFile,
);
element.samples.first.metadata.addAll(<String, Object?>{'channel': 'stable'});
final String code = generator.generateCode(element.samples.first, output: outputFile);
expect(code, contains("runApp(MaterialApp(title: 'foo'));"));
final String html = generator.generateHtml(
element.samples.first,
);
final String html = generator.generateHtml(element.samples.first);
expect(html, contains('<div>HTML Bits</div>'));
expect(html, contains('<div>More HTML Bits</div>'));
expect(html, contains(r'''runApp(MaterialApp(title: &#39;foo&#39;));'''));
expect(html, isNot(contains('sample_channel=stable')));
expect(
html,
contains('A description of the sample.\n'
'\n'
'On several lines.{@inject-html}</div>'));
html,
contains(
'A description of the sample.\n'
'\n'
'On several lines.{@inject-html}</div>',
),
);
expect(html, contains('void main() {'));
final String outputContents = outputFile.readAsStringSync();
@@ -146,10 +143,10 @@ void main() {
});
test('generates snippets', () async {
final File inputFile = memoryFileSystem
.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
..createSync(recursive: true)
..writeAsStringSync(r'''
final File inputFile =
memoryFileSystem.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
..createSync(recursive: true)
..writeAsStringSync(r'''
A description of the snippet.
On several lines.
@@ -161,8 +158,7 @@ void main() {
```
''');
final SnippetDartdocParser sampleParser =
SnippetDartdocParser(memoryFileSystem);
final SnippetDartdocParser sampleParser = SnippetDartdocParser(memoryFileSystem);
const String sourcePath = 'packages/flutter/lib/src/widgets/foo.dart';
const int sourceLine = 222;
final SourceElement element = sampleParser.parseFromDartdocToolFile(
@@ -173,9 +169,7 @@ void main() {
type: 'snippet',
);
expect(element.samples, isNotEmpty);
element.samples.first.metadata.addAll(<String, Object>{
'channel': 'stable',
});
element.samples.first.metadata.addAll(<String, Object>{'channel': 'stable'});
final String code = generator.generateCode(element.samples.first);
expect(code, contains('// A description of the snippet.'));
final String html = generator.generateHtml(element.samples.first);
@@ -183,25 +177,30 @@ void main() {
expect(html, contains('<div>More HTML Bits</div>'));
expect(html, contains(r' print(&#39;The actual $name.&#39;);'));
expect(
html,
contains(
'<div class="snippet-description">{@end-inject-html}A description of the snippet.\n\n'
'On several lines.{@inject-html}</div>\n'));
html,
contains(
'<div class="snippet-description">{@end-inject-html}A description of the snippet.\n\n'
'On several lines.{@inject-html}</div>\n',
),
);
expect(html, contains('main() {'));
});
test('generates dartpad samples', () async {
final File inputFile = memoryFileSystem
.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
..createSync(recursive: true)
..writeAsStringSync(r'''
final File inputFile =
memoryFileSystem.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
..createSync(recursive: true)
..writeAsStringSync(r'''
A description of the snippet.
On several lines.
** See code in examples/api/widgets/foo/foo_example.0.dart **
''');
final String examplePath = path.join(configuration.flutterRoot.path, 'examples/api/widgets/foo/foo_example.0.dart');
final String examplePath = path.join(
configuration.flutterRoot.path,
'examples/api/widgets/foo/foo_example.0.dart',
);
memoryFileSystem.file(examplePath)
..create(recursive: true)
..writeAsStringSync('''
@@ -211,11 +210,9 @@ On several lines.
void main() {
runApp(MaterialApp(title: 'foo'));
}\n'''
);
}\n''');
final SnippetDartdocParser sampleParser =
SnippetDartdocParser(memoryFileSystem);
final SnippetDartdocParser sampleParser = SnippetDartdocParser(memoryFileSystem);
const String sourcePath = 'packages/flutter/lib/src/widgets/foo.dart';
const int sourceLine = 222;
final SourceElement element = sampleParser.parseFromDartdocToolFile(
@@ -226,25 +223,25 @@ void main() {
type: 'dartpad',
);
expect(element.samples, isNotEmpty);
element.samples.first.metadata.addAll(<String, Object>{
'channel': 'stable',
});
element.samples.first.metadata.addAll(<String, Object>{'channel': 'stable'});
final String code = generator.generateCode(element.samples.first);
expect(code, contains("runApp(MaterialApp(title: 'foo'));"));
final String html = generator.generateHtml(element.samples.first);
expect(html, contains('<div>HTML Bits (DartPad-style)</div>'));
expect(html, contains('<div>More HTML Bits</div>'));
expect(
html,
contains(
'<iframe class="snippet-dartpad" src="https://dartpad.dev/embed-flutter.html?split=60&run=true&sample_id=MyElement.0&sample_channel=stable"></iframe>\n'));
html,
contains(
'<iframe class="snippet-dartpad" src="https://dartpad.dev/embed-flutter.html?split=60&run=true&sample_id=MyElement.0&sample_channel=stable"></iframe>\n',
),
);
});
test('generates sample metadata', () async {
final File inputFile = memoryFileSystem
.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
..createSync(recursive: true)
..writeAsStringSync(r'''
final File inputFile =
memoryFileSystem.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
..createSync(recursive: true)
..writeAsStringSync(r'''
A description of the snippet.
On several lines.
@@ -256,13 +253,14 @@ void main() {
```
''');
final File outputFile = memoryFileSystem
.file(path.join(tmpDir.absolute.path, 'snippet_out.dart'));
final File expectedMetadataFile = memoryFileSystem
.file(path.join(tmpDir.absolute.path, 'snippet_out.json'));
final File outputFile = memoryFileSystem.file(
path.join(tmpDir.absolute.path, 'snippet_out.dart'),
);
final File expectedMetadataFile = memoryFileSystem.file(
path.join(tmpDir.absolute.path, 'snippet_out.json'),
);
final SnippetDartdocParser sampleParser =
SnippetDartdocParser(memoryFileSystem);
final SnippetDartdocParser sampleParser = SnippetDartdocParser(memoryFileSystem);
const String sourcePath = 'packages/flutter/lib/src/widgets/foo.dart';
const int sourceLine = 222;
final SourceElement element = sampleParser.parseFromDartdocToolFile(
@@ -273,20 +271,16 @@ void main() {
type: 'sample',
);
expect(element.samples, isNotEmpty);
element.samples.first.metadata
.addAll(<String, Object>{'channel': 'stable'});
element.samples.first.metadata.addAll(<String, Object>{'channel': 'stable'});
generator.generateCode(element.samples.first, output: outputFile);
expect(expectedMetadataFile.existsSync(), isTrue);
final Map<String, dynamic> json =
jsonDecode(expectedMetadataFile.readAsStringSync())
as Map<String, dynamic>;
jsonDecode(expectedMetadataFile.readAsStringSync()) as Map<String, dynamic>;
expect(json['id'], equals('MyElement.0'));
expect(json['channel'], equals('stable'));
expect(json['file'], equals('snippet_out.dart'));
expect(json['description'],
equals('A description of the snippet.\n\nOn several lines.'));
expect(json['sourcePath'],
equals('packages/flutter/lib/src/widgets/foo.dart'));
expect(json['description'], equals('A description of the snippet.\n\nOn several lines.'));
expect(json['sourcePath'], equals('packages/flutter/lib/src/widgets/foo.dart'));
});
});
@@ -299,21 +293,20 @@ void main() {
setUp(() {
fakeProcessManager = FakeProcessManager();
memoryFileSystem = MemoryFileSystem();
tmpDir = memoryFileSystem.systemTempDirectory
.createTempSync('flutter_snippets_test.');
flutterRoot = memoryFileSystem
.directory(path.join(tmpDir.absolute.path, 'flutter'))
tmpDir = memoryFileSystem.systemTempDirectory.createTempSync('flutter_snippets_test.');
flutterRoot = memoryFileSystem.directory(path.join(tmpDir.absolute.path, 'flutter'))
..createSync(recursive: true);
});
test('command line arguments are parsed and passed to generator', () {
final FakePlatform platform = FakePlatform(environment: <String, String>{
'PACKAGE_NAME': 'dart:ui',
'LIBRARY_NAME': 'library',
'ELEMENT_NAME': 'element',
'FLUTTER_ROOT': flutterRoot.absolute.path,
// The details here don't really matter other than the flutter root.
'FLUTTER_VERSION': '''
final FakePlatform platform = FakePlatform(
environment: <String, String>{
'PACKAGE_NAME': 'dart:ui',
'LIBRARY_NAME': 'library',
'ELEMENT_NAME': 'element',
'FLUTTER_ROOT': flutterRoot.absolute.path,
// The details here don't really matter other than the flutter root.
'FLUTTER_VERSION': '''
{
"frameworkVersion": "2.5.0-6.0.pre.55",
"channel": "use_snippets_pkg",
@@ -324,7 +317,8 @@ void main() {
"dartSdkVersion": "2.14.0 (build 2.14.0-393.0.dev)",
"flutterRoot": "${flutterRoot.absolute.path}"
}''',
});
},
);
final FlutterInformation flutterInformation = FlutterInformation(
filesystem: memoryFileSystem,
processManager: fakeProcessManager,
@@ -341,38 +335,37 @@ void main() {
snippets_main.platform = platform;
snippets_main.filesystem = memoryFileSystem;
snippets_main.processManager = fakeProcessManager;
final File input = memoryFileSystem
.file(tmpDir.childFile('input.snippet'))
final File input = memoryFileSystem.file(tmpDir.childFile('input.snippet'))
..writeAsString('/// Test file');
snippets_main.main(
<String>['--input=${input.absolute.path}']);
snippets_main.main(<String>['--input=${input.absolute.path}']);
final Map<String, dynamic> metadata =
mockSnippetGenerator.sample.metadata;
final Map<String, dynamic> metadata = mockSnippetGenerator.sample.metadata;
// Ignore the channel, because channel is really just the branch, and will be
// different on development workstations.
metadata.remove('channel');
expect(
metadata,
equals(<String, dynamic>{
'id': 'dart_ui.library.element',
'element': 'element',
'sourcePath': 'unknown.dart',
'sourceLine': 1,
'serial': '',
'package': 'dart:ui',
'library': 'library',
}));
metadata,
equals(<String, dynamic>{
'id': 'dart_ui.library.element',
'element': 'element',
'sourcePath': 'unknown.dart',
'sourceLine': 1,
'serial': '',
'package': 'dart:ui',
'library': 'library',
}),
);
snippets_main.main(<String>[]);
expect(
errorMessage,
equals(
'The --input option must be specified, either on the command line, or in the INPUT environment variable.'));
errorMessage,
equals(
'The --input option must be specified, either on the command line, or in the INPUT environment variable.',
),
);
errorMessage = '';
snippets_main
.main(<String>['--input=${input.absolute.path}', '--type=snippet']);
snippets_main.main(<String>['--input=${input.absolute.path}', '--type=snippet']);
expect(errorMessage, equals(''));
errorMessage = '';
@@ -381,16 +374,14 @@ void main() {
snippets_main.main(<String>[
'--input=${input.absolute.path}',
'--type=snippet',
'--no-format-output'
'--no-format-output',
]);
expect(mockSnippetGenerator.formatOutput, equals(false));
errorMessage = '';
input.deleteSync();
snippets_main.main(
<String>['--input=${input.absolute.path}']);
expect(errorMessage,
equals('The input file ${input.absolute.path} does not exist.'));
snippets_main.main(<String>['--input=${input.absolute.path}']);
expect(errorMessage, equals('The input file ${input.absolute.path} does not exist.'));
errorMessage = '';
});
});

View File

@@ -45,29 +45,23 @@ void main() {
test('calls out to flutter if FLUTTER_VERSION is not set', () async {
fakeProcessManager.stdout = testVersionInfo;
final Map<String, dynamic> info =
flutterInformation.getFlutterInformation();
final Map<String, dynamic> info = flutterInformation.getFlutterInformation();
expect(fakeProcessManager.runs, equals(1));
expect(
info['frameworkVersion'], equals(Version.parse('2.5.0-2.0.pre.63')));
expect(info['frameworkVersion'], equals(Version.parse('2.5.0-2.0.pre.63')));
});
test("doesn't call out to flutter if FLUTTER_VERSION is set", () async {
fakePlatform.environment['FLUTTER_VERSION'] = testVersionInfo;
final Map<String, dynamic> info =
flutterInformation.getFlutterInformation();
final Map<String, dynamic> info = flutterInformation.getFlutterInformation();
expect(fakeProcessManager.runs, equals(0));
expect(
info['frameworkVersion'], equals(Version.parse('2.5.0-2.0.pre.63')));
expect(info['frameworkVersion'], equals(Version.parse('2.5.0-2.0.pre.63')));
});
test('getFlutterRoot calls out to flutter if FLUTTER_ROOT is not set',
() async {
test('getFlutterRoot calls out to flutter if FLUTTER_ROOT is not set', () async {
fakeProcessManager.stdout = testVersionInfo;
final Directory root = flutterInformation.getFlutterRoot();
expect(fakeProcessManager.runs, equals(1));
expect(root.path, equals('/home/user/flutter'));
});
test("getFlutterRoot doesn't call out to flutter if FLUTTER_ROOT is set",
() async {
test("getFlutterRoot doesn't call out to flutter if FLUTTER_ROOT is set", () async {
fakePlatform.environment['FLUTTER_ROOT'] = '/home/user/flutter';
final Directory root = flutterInformation.getFlutterRoot();
expect(fakeProcessManager.runs, equals(0));
@@ -75,11 +69,9 @@ void main() {
});
test('parses version properly', () async {
fakePlatform.environment['FLUTTER_VERSION'] = testVersionInfo;
final Map<String, dynamic> info =
flutterInformation.getFlutterInformation();
final Map<String, dynamic> info = flutterInformation.getFlutterInformation();
expect(info['frameworkVersion'], isNotNull);
expect(
info['frameworkVersion'], equals(Version.parse('2.5.0-2.0.pre.63')));
expect(info['frameworkVersion'], equals(Version.parse('2.5.0-2.0.pre.63')));
expect(info['dartSdkVersion'], isNotNull);
expect(info['dartSdkVersion'], equals(Version.parse('2.14.0-360.0.dev')));
});