Skip to content

Remove @example. #3715

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ dartdoc:
markdown: doc/Second.md
name: Great
categoryOrder: ["First Category", "Second Category"]
examplePathPrefix: 'subdir/with/examples'
includeExternal: ['bin/unusually_located_library.dart']
nodoc: ['lib/sekret/*.dart']
linkTo:
Expand All @@ -150,8 +149,6 @@ Unrecognized options will be ignored. Supported options:
defined in dartdoc_options.yaml, those declared categories in the source code will be invisible.
* **categoryOrder**: Specify the order of topics for display in the sidebar and
the package page.
* **examplePathPrefix**: Specify the location of the example directory for resolving `@example`
directives.
* **exclude**: Specify a list of library names to avoid generating docs for,
overriding any specified in include. All libraries listed must be local to this package, unlike
the command line `--exclude`. See also `nodoc`.
Expand Down
21 changes: 0 additions & 21 deletions doc/directives.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,27 +28,6 @@ own documentation page, listing all of the categorized elements.

TODO(srawlins): Document.

## `{@example}` - Examples (deprecated)

Examples from the file system can be inlined by using the `{@example}`
directive. The file path, the region, and the example language can all be
specified with the following syntax:

```none
/// {@example PATH [region=NAME] [lang=NAME]}
```

All example file names must have the extension, `.md`, and this extension must
not be specified in the example `PATH`. `PATH` must be specified as a relative
path from the root of the project for which documentation is being generated.
Given `dir/file.dart` as `PATH`, an example will be extracted from
`dir/file.dart.md`, relative to the project root directory.

During doc generation, dartdoc will replace the `{@example}` directive with the
contents of the example file, verbatim.

TODO(srawlins): Document region, lang, `--example-path-prefix`.

## `{@inject-html}` - Injected HTML

HTML can be rendered unmodified by including it between `{@inject-html}` and
Expand Down
10 changes: 0 additions & 10 deletions lib/src/dartdoc_options.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1293,10 +1293,6 @@ class DartdocOptionContext extends DartdocOptionContextBase
CategoryConfiguration get categories =>
optionSet['categories'].valueAt(context);

// TODO(srawlins): Remove when we remove support for `{@example}`.
String? get examplePathPrefix =>
optionSet['examplePathPrefix'].valueAt(context);

// TODO(srawlins): This memoization saved a lot of time in unit testing, but
// is the first value in this class to be memoized. Memoize others?
late final Set<String> exclude =
Expand Down Expand Up @@ -1554,12 +1550,6 @@ List<DartdocOption> createDartdocOptions(
convertYamlToType: CategoryConfiguration.fromYamlMap,
help: 'A list of all categories, their display names, and markdown '
'documentation in the order they are to be displayed.'),
// TODO(srawlins): Remove when we remove support for `{@example}`.
DartdocOptionArgFile<String?>('examplePathPrefix', null, resourceProvider,
optionIs: OptionKind.dir,
help: '(deprecated) Prefix for @example paths; defaults to the project '
'root.',
mustExist: true),
DartdocOptionArgFile<List<String>>('exclude', [], resourceProvider,
help: 'Names of libraries to exclude from documentation.',
splitCommas: true),
Expand Down
1 change: 0 additions & 1 deletion lib/src/generator/templates.runtime_renderers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16097,7 +16097,6 @@ const _invisibleGetters = {
'categories',
'categoryOrder',
'context',
'examplePathPrefix',
'exclude',
'excludeFooterVersion',
'flutterRoot',
Expand Down
104 changes: 0 additions & 104 deletions lib/src/model/documentation_comment.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ final _htmlPattern =
final _basicToolPattern =
RegExp(r'[ ]*{@tool\s+([^\s}][^}]*)}\n?([^]+?)\n?{@end-tool}[ ]*\n?');

final _examplePattern = RegExp(r'{@example\s+([^\s}][^}]*)}');

final _macroRegExp = RegExp(r'{@macro\s+([^\s}][^}]*)}');

final _htmlInjectRegExp = RegExp(r'<dartdoc-html>([a-f0-9]+)</dartdoc-html>');
Expand Down Expand Up @@ -97,7 +95,6 @@ mixin DocumentationComment
String _processCommentWithoutTools(String documentationComment) {
var docs = stripComments(documentationComment);
if (docs.contains('{@')) {
docs = _injectExamples(docs);
docs = _injectYouTube(docs);
docs = _injectAnimations(docs);
// TODO(srawlins): Processing templates here causes #2281. But leaving
Expand Down Expand Up @@ -126,7 +123,6 @@ mixin DocumentationComment
return docs;
}
_checkForUnknownDirectives(docs);
docs = _injectExamples(docs);
docs = _injectYouTube(docs);
docs = _injectAnimations(docs);
docs = _stripMacroTemplatesAndAddToIndex(docs);
Expand All @@ -147,7 +143,6 @@ mixin DocumentationComment
'end-inject-html',
'end-tool',
'endtemplate',
'example',
'macro',
'inject-html',
'template',
Expand Down Expand Up @@ -284,105 +279,6 @@ mixin DocumentationComment
.cast<String, String>();
}

/// Replace &#123;@example ...&#125; in API comments with the content of named file.
///
/// Syntax:
///
/// &#123;@example PATH [region=NAME] [lang=NAME]&#125;
///
/// If PATH is `dir/file.ext` and region is `r` then we'll look for the file
/// named `dir/file-r.ext.md`, relative to the project root directory of the
/// project for which the docs are being generated.
///
/// Examples: (escaped in this comment to show literal values in dartdoc's
/// dartdoc)
///
/// &#123;@example examples/angular/quickstart/web/main.dart&#125;
/// &#123;@example abc/def/xyz_component.dart region=template lang=html&#125;
///
String _injectExamples(String rawdocs) {
final dirPath = package.packageMeta.dir.path;
return rawdocs.replaceAllMapped(_examplePattern, (match) {
var args = _getExampleArgs(match[1]!);
if (args == null) {
// Already warned about an invalid parameter if this happens.
return '';
}
warn(
PackageWarning.deprecated,
message:
"The '@example' directive is deprecated, and will soon no longer "
'be supported.',
);
var lang = args['lang'] ??
pathContext.extension(args['src']!).replaceFirst('.', '');

var replacement = match[0]!; // default to fully matched string.

var fragmentFile = packageGraph.resourceProvider.getFile(
pathContext.canonicalize(pathContext.join(dirPath, args['file'])));

if (fragmentFile.exists) {
replacement = fragmentFile.readAsStringSync();
if (lang.isNotEmpty) {
replacement = replacement.replaceFirst('```', '```$lang');
}
} else {
var filePath = element.source!.fullName.substring(dirPath.length + 1);

// TODO(srawlins): If a file exists at the location without the
// appended 'md' extension, note this.
warn(PackageWarning.missingExampleFile,
message: '${fragmentFile.path}; path listed at $filePath');
}
return replacement;
});
}

/// An argument parser used in [_getExampleArgs] to parse an `{@example}`
/// directive.
static final ArgParser _exampleArgParser = ArgParser()
..addOption('lang')
..addOption('region');

/// Helper for [_injectExamples] used to process `@example` arguments.
///
/// Returns a map of arguments. The first unnamed argument will have key
/// 'src'. The computed file path, constructed from 'src' and 'region' will
/// have key 'file'.
Map<String, String?>? _getExampleArgs(String argsAsString) {
var results = _parseArgs(argsAsString, _exampleArgParser, 'example');
if (results == null) {
return null;
}

// Extract PATH and fix the path separators.
var src = results.rest.isEmpty
? ''
: results.rest.first.replaceAll('/', pathContext.separator);
var args = <String, String?>{
'src': src,
'lang': results['lang'],
'region': results['region'] ?? '',
};

// Compute 'file' from region and src.
final fragExtension = '.md';
var file = src + fragExtension;
var region = args['region'] ?? '';
if (region.isNotEmpty) {
var dir = pathContext.dirname(src);
var basename = pathContext.basenameWithoutExtension(src);
var ext = pathContext.extension(src);
file = pathContext.join(dir, '$basename-$region$ext$fragExtension');
}
var examplePathPrefix = config.examplePathPrefix;
args['file'] = examplePathPrefix == null
? file
: pathContext.join(examplePathPrefix, file);
return args;
}

/// Matches all youtube directives (even some invalid ones). This is so
/// we can give good error messages if the directive is malformed, instead of
/// just silently emitting it as-is.
Expand Down
1 change: 0 additions & 1 deletion lib/src/model/package_graph.dart
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,6 @@ class PackageGraph with CommentReferable, Nameable {
PackageWarning.invalidParameter ||
PackageWarning.toolError ||
PackageWarning.deprecated ||
PackageWarning.missingExampleFile ||
PackageWarning.missingCodeBlockLanguage =>
kind.messageFor([message])
};
Expand Down
7 changes: 0 additions & 7 deletions lib/src/warnings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -279,13 +279,6 @@ enum PackageWarning implements Comparable<PackageWarning> {
'deprecated dartdoc usage: {0}',
shortHelp: 'A dartdoc directive has a deprecated format.',
),
missingExampleFile(
'missing-example-file',
'example file not found: {0}',
shortHelp:
"A file which is indicated by an '{@example}' directive could not be "
'found',
),
missingCodeBlockLanguage(
'missing-code-block-language',
'missing code block language: {0}',
Expand Down
Loading