Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(384)

Side by Side Diff: pkg/docgen/lib/docgen.dart

Issue 18438003: Removed ArgResult in lib/docgen.dart and removed top level variables. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 7 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« pkg/docgen/bin/docgen.dart ('K') | « pkg/docgen/bin/docgen.dart ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a 2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file. 3 // BSD-style license that can be found in the LICENSE file.
4 4
5 /** 5 /**
6 * **docgen** is a tool for creating machine readable representations of Dart 6 * **docgen** is a tool for creating machine readable representations of Dart
7 * code metadata, including: classes, members, comments and annotations. 7 * code metadata, including: classes, members, comments and annotations.
8 * 8 *
9 * docgen is run on a `.dart` file or a directory containing `.dart` files. 9 * docgen is run on a `.dart` file or a directory containing `.dart` files.
10 * 10 *
11 * $ dart docgen.dart [OPTIONS] [FILE/DIR] 11 * $ dart docgen.dart [OPTIONS] [FILE/DIR]
12 * 12 *
13 * This creates files called `docs/<library_name>.yaml` in your current 13 * This creates files called `docs/<library_name>.yaml` in your current
14 * working directory. 14 * working directory.
15 */ 15 */
16 library docgen; 16 library docgen;
17 17
18 import 'dart:io'; 18 import 'dart:io';
19 import 'dart:json'; 19 import 'dart:json';
20 import 'dart:async'; 20 import 'dart:async';
21 21
22 import 'package:args/args.dart';
23 import 'package:logging/logging.dart'; 22 import 'package:logging/logging.dart';
24 import 'package:markdown/markdown.dart' as markdown; 23 import 'package:markdown/markdown.dart' as markdown;
25 import 'package:pathos/path.dart' as path; 24 import 'package:pathos/path.dart' as path;
26 25
27 import 'dart2yaml.dart'; 26 import 'dart2yaml.dart';
28 import 'src/io.dart'; 27 import 'src/io.dart';
29 import '../../../sdk/lib/_internal/compiler/compiler.dart' as api; 28 import '../../../sdk/lib/_internal/compiler/compiler.dart' as api;
30 import '../../../sdk/lib/_internal/compiler/implementation/filenames.dart'; 29 import '../../../sdk/lib/_internal/compiler/implementation/filenames.dart';
31 import '../../../sdk/lib/_internal/compiler/implementation/mirrors/dart2js_mirro r.dart' 30 import '../../../sdk/lib/_internal/compiler/implementation/mirrors/dart2js_mirro r.dart'
32 as dart2js; 31 as dart2js;
(...skipping 11 matching lines...) Expand all
44 43
45 /// Current class being documented to be used for comment links. 44 /// Current class being documented to be used for comment links.
46 ClassMirror _currentClass; 45 ClassMirror _currentClass;
47 46
48 /// Current member being documented to be used for comment links. 47 /// Current member being documented to be used for comment links.
49 MemberMirror _currentMember; 48 MemberMirror _currentMember;
50 49
51 /// Resolves reference links in doc comments. 50 /// Resolves reference links in doc comments.
52 markdown.Resolver linkResolver; 51 markdown.Resolver linkResolver;
53 52
54 /// Package directory of directory being analyzed. 53 /// Package directory of directory being analyzed.
55 String packageDir; 54 String _packageDir;
56
57 bool outputToYaml;
58 bool outputToJson;
59 bool includePrivate;
60 /// State for whether imported SDK libraries should also be outputted.
61 bool includeSdk;
62 /// State for whether all SDK libraries should be outputted.
63 bool parseSdk;
64 55
65 /** 56 /**
66 * Docgen constructor initializes the link resolver for markdown parsing. 57 * Docgen constructor initializes the link resolver for markdown parsing.
67 * Also initializes the command line arguments. 58 * Also initializes the command line arguments.
59 *
60 * [includeSdk] Whether imported SDK libraries should also be outputted.
Emily Fortuna 2013/07/02 00:53:57 nit -1 space here and below after the *
Andrei Mouravski 2013/07/02 00:58:29 This is not the dartdoc way of talking about param
janicejl 2013/07/02 01:21:31 Done.
janicejl 2013/07/02 01:21:31 Done.
61 * [parseSdk] Whether all SDK libraries should be outputted.
68 */ 62 */
69 void docgen(ArgResults argResults) { 63 void docgen(List<String> files, {String packageDir,
70 _setCommandLineArguments(argResults); 64 bool outputToYaml: true, bool outputToJson: false,
Andrei Mouravski 2013/07/02 00:58:29 You only need one of outputToYaml or outputToJson
janicejl 2013/07/02 01:21:31 Done.
65 bool includePrivate: false, bool includeSdk: false, bool parseSdk: false}) {
66 if (packageDir != null) {
67 logger.info('Package Root: ${packageDir}');
68 _packageDir = packageDir;
69 }
71 70
72 linkResolver = (name) => 71 linkResolver = (name) =>
73 fixReference(name, _currentLibrary, _currentClass, _currentMember); 72 fixReference(name, _currentLibrary, _currentClass, _currentMember);
74 73
75 getMirrorSystem(argResults.rest).then((MirrorSystem mirrorSystem) { 74 getMirrorSystem(files, parseSdk: parseSdk)
76 if (mirrorSystem.libraries.values.isEmpty) { 75 .then((MirrorSystem mirrorSystem) {
77 throw new StateError('No Library Mirrors.'); 76 if (mirrorSystem.libraries.values.isEmpty) {
78 } 77 throw new StateError('No Library Mirrors.');
79 _documentLibraries(mirrorSystem.libraries.values); 78 }
80 }); 79 _documentLibraries(mirrorSystem.libraries.values,
81 } 80 includeSdk: includeSdk, includePrivate: includePrivate,
82 81 outputToYaml: outputToYaml, outputToJson: outputToJson);
83 void _setCommandLineArguments(ArgResults argResults) { 82 });
84 outputToYaml = argResults['yaml'] || argResults['output-format'] == 'yaml';
85 outputToJson = argResults['json'] || argResults['output-format'] == 'json';
86 if (outputToYaml && outputToJson) {
87 throw new ArgumentError('Cannot have contradictory output flags.');
88 }
89 outputToYaml = outputToYaml || !outputToJson;
90 includePrivate = argResults['include-private'];
91 parseSdk = argResults['parse-sdk'];
92 includeSdk = parseSdk || argResults['include-sdk'];
93 packageDir = argResults['package-root'];
94 if (packageDir != null) logger.info('Package Root: ${packageDir}');
95 } 83 }
96 84
97 List<String> _listLibraries(List<String> args) { 85 List<String> _listLibraries(List<String> args) {
98 // TODO(janicejl): At the moment, only have support to have either one file, 86 // TODO(janicejl): At the moment, only have support to have either one file,
99 // or one directory. This is because there can only be one package directory 87 // or one directory. This is because there can only be one package directory
100 // since only one docgen is created per run. 88 // since only one docgen is created per run.
101 if (args.length != 1) throw new UnsupportedError(USAGE); 89 if (args.length != 1) throw new UnsupportedError(USAGE);
102 var libraries = new List<String>(); 90 var libraries = new List<String>();
103 var type = FileSystemEntity.typeSync(args[0]); 91 var type = FileSystemEntity.typeSync(args[0]);
104 92
105 if (type == FileSystemEntityType.FILE) { 93 if (type == FileSystemEntityType.FILE) {
106 libraries.add(path.absolute(args[0])); 94 libraries.add(path.absolute(args[0]));
107 logger.info('Added to libraries: ${libraries.last}'); 95 logger.info('Added to libraries: ${libraries.last}');
108 } else { 96 } else {
109 libraries.addAll(_listDartFromDir(args[0])); 97 libraries.addAll(_listDartFromDir(args[0]));
110 } 98 }
111 return libraries; 99 return libraries;
112 } 100 }
113 101
114 List<String> _listDartFromDir(String args) { 102 List<String> _listDartFromDir(String args) {
115 var files = listDir(args, recursive: true); 103 var files = listDir(args, recursive: true);
116 if (packageDir == null) { 104 if (_packageDir == null) {
117 packageDir = files.firstWhere((f) => 105 _packageDir = files.firstWhere((f) =>
118 f.endsWith('/pubspec.yaml'), orElse: () => ''); 106 f.endsWith('/pubspec.yaml'), orElse: () => '');
119 if (packageDir != '') packageDir = path.dirname(packageDir) + '/packages'; 107 if (_packageDir != '') {
120 logger.info('Package Directory: $packageDir'); 108 _packageDir = path.dirname(_packageDir) + '/packages';
109 }
110 logger.info('Package Directory: $_packageDir');
121 } 111 }
122 // To avoid anaylzing package files twice, only files with paths not 112 // To avoid anaylzing package files twice, only files with paths not
123 // containing '/packages' will be added. The only exception is if the file to 113 // containing '/packages' will be added. The only exception is if the file to
124 // analyze already has a '/package' in its path. 114 // analyze already has a '/package' in its path.
125 return files.where((f) => f.endsWith('.dart') && 115 return files.where((f) => f.endsWith('.dart') &&
126 (!f.contains('/packages') || args.contains('/packages'))).toList() 116 (!f.contains('/packages') || args.contains('/packages'))).toList()
127 ..forEach((lib) => logger.info('Added to libraries: $lib')); 117 ..forEach((lib) => logger.info('Added to libraries: $lib'));
128 } 118 }
129 119
130 List<String> _listSdk() { 120 List<String> _listSdk() {
131 var sdk = new List<String>(); 121 var sdk = new List<String>();
132 LIBRARIES.forEach((String name, LibraryInfo info) { 122 LIBRARIES.forEach((String name, LibraryInfo info) {
133 if (info.documented) { 123 if (info.documented) {
134 sdk.add('dart:$name'); 124 sdk.add('dart:$name');
135 logger.info('Add to SDK: ${sdk.last}'); 125 logger.info('Add to SDK: ${sdk.last}');
136 } 126 }
137 }); 127 });
138 return sdk; 128 return sdk;
139 } 129 }
140 130
141 /** 131 /**
142 * Analyzes set of libraries by getting a mirror system and triggers the 132 * Analyzes set of libraries by getting a mirror system and triggers the
143 * documentation of the libraries. 133 * documentation of the libraries.
144 */ 134 */
145 Future<MirrorSystem> getMirrorSystem(List<String> args) { 135 Future<MirrorSystem> getMirrorSystem(List<String> args, {bool parseSdk:false}) {
146 var libraries = !parseSdk ? _listLibraries(args) : _listSdk(); 136 var libraries = !parseSdk ? _listLibraries(args) : _listSdk();
147 if (libraries.isEmpty) throw new StateError('No Libraries.'); 137 if (libraries.isEmpty) throw new StateError('No Libraries.');
148 // DART_SDK should be set to the root of the SDK library. 138 // DART_SDK should be set to the root of the SDK library.
149 var sdkRoot = Platform.environment['DART_SDK']; 139 var sdkRoot = Platform.environment['DART_SDK'];
150 if (sdkRoot != null) { 140 if (sdkRoot != null) {
151 logger.info('Using DART_SDK to find SDK at $sdkRoot'); 141 logger.info('Using DART_SDK to find SDK at $sdkRoot');
152 } else { 142 } else {
153 // If DART_SDK is not defined in the environment, 143 // If DART_SDK is not defined in the environment,
154 // assuming the dart executable is from the Dart SDK folder inside bin. 144 // assuming the dart executable is from the Dart SDK folder inside bin.
155 sdkRoot = path.dirname(path.dirname(new Options().executable)); 145 sdkRoot = path.dirname(path.dirname(new Options().executable));
156 logger.info('SDK Root: ${sdkRoot}'); 146 logger.info('SDK Root: ${sdkRoot}');
157 } 147 }
158 148
159 return _getMirrorSystemHelper(libraries, sdkRoot, packageRoot: packageDir); 149 return _getMirrorSystemHelper(libraries, sdkRoot, packageRoot: _packageDir);
160 } 150 }
161 151
162 // TODO(janicejl): Should make docgen fail gracefully, or output a friendly 152 // TODO(janicejl): Should make docgen fail gracefully, or output a friendly
163 // error message letting them know why it is failing to create a mirror system. 153 // error message letting them know why it is failing to create a mirror system.
164 // If there is conflicting library names, should modify it with a hash at the 154 // If there is conflicting library names, should modify it with a hash at the
165 // end of it's library name. 155 // end of it's library name.
166 /** 156 /**
167 * Analyzes set of libraries and provides a mirror system which can be used 157 * Analyzes set of libraries and provides a mirror system which can be used
168 * for static inspection of the source code. 158 * for static inspection of the source code.
169 */ 159 */
(...skipping 20 matching lines...) Expand all
190 // Currently, a string is thrown when it fails to create a mirror 180 // Currently, a string is thrown when it fails to create a mirror
191 // system, and it is not possible to use the stack trace. BUG(#11622) 181 // system, and it is not possible to use the stack trace. BUG(#11622)
192 // To avoid printing the stack trace. 182 // To avoid printing the stack trace.
193 exit(1); 183 exit(1);
194 }); 184 });
195 } 185 }
196 186
197 /** 187 /**
198 * Creates documentation for filtered libraries. 188 * Creates documentation for filtered libraries.
199 */ 189 */
200 void _documentLibraries(List<LibraryMirror> libraries) { 190 void _documentLibraries(List<LibraryMirror> libraries,
191 {bool includeSdk:false, bool includePrivate:false,
192 bool outputToYaml:true, bool outputToJson:false}) {
201 libraries.forEach((lib) { 193 libraries.forEach((lib) {
202 // Files belonging to the SDK have a uri that begins with 'dart:'. 194 // Files belonging to the SDK have a uri that begins with 'dart:'.
203 if (includeSdk || !lib.uri.toString().startsWith('dart:')) { 195 if (includeSdk || !lib.uri.toString().startsWith('dart:')) {
204 var library = generateLibrary(lib); 196 var library = generateLibrary(lib, includePrivate: includePrivate);
205 _outputLibrary(library); 197 _outputLibrary(library, outputToYaml, outputToJson);
206 } 198 }
207 }); 199 });
208 // Outputs a text file with a list of files available after creating all 200 // Outputs a text file with a list of files available after creating all
209 // the libraries. This will help the viewer know what files are available 201 // the libraries. This will help the viewer know what files are available
210 // to read in. 202 // to read in.
211 _writeToFile(listDir("docs").join('\n'), 'library_list.txt'); 203 _writeToFile(listDir("docs").join('\n'), 'library_list.txt');
212 } 204 }
213 205
214 Library generateLibrary(dart2js.Dart2JsLibraryMirror library) { 206 Library generateLibrary(dart2js.Dart2JsLibraryMirror library,
207 {bool includePrivate:false}) {
215 _currentLibrary = library; 208 _currentLibrary = library;
216 var result = new Library(library.qualifiedName, _getComment(library), 209 var result = new Library(library.qualifiedName, _getComment(library),
217 _getVariables(library.variables), _getMethods(library.functions), 210 _getVariables(library.variables, includePrivate),
218 _getClasses(library.classes)); 211 _getMethods(library.functions, includePrivate),
212 _getClasses(library.classes, includePrivate));
219 logger.fine('Generated library for ${result.name}'); 213 logger.fine('Generated library for ${result.name}');
220 return result; 214 return result;
221 } 215 }
222 216
223 void _outputLibrary(Library result) { 217 void _outputLibrary(Library result, bool outputToYaml, bool outputToJson) {
218 if (outputToYaml && outputToJson) {
219 throw new ArgumentError('Cannot have contradictory output flags.');
Emily Fortuna 2013/07/02 00:53:57 this doesn't seem like an error. I thought the poi
Andrei Mouravski 2013/07/02 00:58:29 I think you should also check this in the argParse
Andrei Mouravski 2013/07/02 00:58:29 Actually, you should only take one parameter here,
janicejl 2013/07/02 01:21:31 Done.
220 }
221 outputToYaml = outputToYaml || !outputToJson;
222
224 if (outputToJson) { 223 if (outputToJson) {
225 _writeToFile(stringify(result.toMap()), '${result.name}.json'); 224 _writeToFile(stringify(result.toMap()), '${result.name}.json');
226 } 225 }
227 if (outputToYaml) { 226 if (outputToYaml) {
228 _writeToFile(getYamlString(result.toMap()), '${result.name}.yaml'); 227 _writeToFile(getYamlString(result.toMap()), '${result.name}.yaml');
229 } 228 }
230 } 229 }
231 230
232 /** 231 /**
233 * Returns a list of meta annotations assocated with a mirror. 232 * Returns a list of meta annotations assocated with a mirror.
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
268 // TODO(tmandel): Create proper links for [_] style markdown based 267 // TODO(tmandel): Create proper links for [_] style markdown based
269 // on scope once layout of viewer is finished. 268 // on scope once layout of viewer is finished.
270 markdown.Node fixReference(String name, LibraryMirror currentLibrary, 269 markdown.Node fixReference(String name, LibraryMirror currentLibrary,
271 ClassMirror currentClass, MemberMirror currentMember) { 270 ClassMirror currentClass, MemberMirror currentMember) {
272 return new markdown.Element.text('code', name); 271 return new markdown.Element.text('code', name);
273 } 272 }
274 273
275 /** 274 /**
276 * Returns a map of [Variable] objects constructed from inputted mirrors. 275 * Returns a map of [Variable] objects constructed from inputted mirrors.
277 */ 276 */
278 Map<String, Variable> _getVariables(Map<String, VariableMirror> mirrorMap) { 277 Map<String, Variable> _getVariables(Map<String, VariableMirror> mirrorMap,
278 bool includePrivate) {
279 var data = {}; 279 var data = {};
280 mirrorMap.forEach((String mirrorName, VariableMirror mirror) { 280 mirrorMap.forEach((String mirrorName, VariableMirror mirror) {
281 if (includePrivate || !mirror.isPrivate) { 281 if (includePrivate || !mirror.isPrivate) {
282 _currentMember = mirror; 282 _currentMember = mirror;
283 data[mirrorName] = new Variable(mirrorName, mirror.qualifiedName, 283 data[mirrorName] = new Variable(mirrorName, mirror.qualifiedName,
284 mirror.isFinal, mirror.isStatic, mirror.type.qualifiedName, 284 mirror.isFinal, mirror.isStatic, mirror.type.qualifiedName,
285 _getComment(mirror), _getAnnotations(mirror)); 285 _getComment(mirror), _getAnnotations(mirror));
286 } 286 }
287 }); 287 });
288 return data; 288 return data;
289 } 289 }
290 290
291 /** 291 /**
292 * Returns a map of [Method] objects constructed from inputted mirrors. 292 * Returns a map of [Method] objects constructed from inputted mirrors.
293 */ 293 */
294 Map<String, Method> _getMethods(Map<String, MethodMirror> mirrorMap) { 294 Map<String, Method> _getMethods(Map<String, MethodMirror> mirrorMap,
295 bool includePrivate) {
295 var data = {}; 296 var data = {};
296 mirrorMap.forEach((String mirrorName, MethodMirror mirror) { 297 mirrorMap.forEach((String mirrorName, MethodMirror mirror) {
297 if (includePrivate || !mirror.isPrivate) { 298 if (includePrivate || !mirror.isPrivate) {
298 _currentMember = mirror; 299 _currentMember = mirror;
299 data[mirrorName] = new Method(mirrorName, mirror.qualifiedName, 300 data[mirrorName] = new Method(mirrorName, mirror.qualifiedName,
300 mirror.isSetter, mirror.isGetter, mirror.isConstructor, 301 mirror.isSetter, mirror.isGetter, mirror.isConstructor,
301 mirror.isOperator, mirror.isStatic, mirror.returnType.qualifiedName, 302 mirror.isOperator, mirror.isStatic, mirror.returnType.qualifiedName,
302 _getComment(mirror), _getParameters(mirror.parameters), 303 _getComment(mirror), _getParameters(mirror.parameters),
303 _getAnnotations(mirror)); 304 _getAnnotations(mirror));
304 } 305 }
305 }); 306 });
306 return data; 307 return data;
307 } 308 }
308 309
309 /** 310 /**
310 * Returns a map of [Class] objects constructed from inputted mirrors. 311 * Returns a map of [Class] objects constructed from inputted mirrors.
311 */ 312 */
312 Map<String, Class> _getClasses(Map<String, ClassMirror> mirrorMap) { 313 Map<String, Class> _getClasses(Map<String, ClassMirror> mirrorMap,
314 bool includePrivate) {
313 var data = {}; 315 var data = {};
314 mirrorMap.forEach((String mirrorName, ClassMirror mirror) { 316 mirrorMap.forEach((String mirrorName, ClassMirror mirror) {
315 if (includePrivate || !mirror.isPrivate) { 317 if (includePrivate || !mirror.isPrivate) {
316 _currentClass = mirror; 318 _currentClass = mirror;
317 var superclass = (mirror.superclass != null) ? 319 var superclass = (mirror.superclass != null) ?
318 mirror.superclass.qualifiedName : ''; 320 mirror.superclass.qualifiedName : '';
319 var interfaces = 321 var interfaces =
320 mirror.superinterfaces.map((interface) => interface.qualifiedName); 322 mirror.superinterfaces.map((interface) => interface.qualifiedName);
321 data[mirrorName] = new Class(mirrorName, mirror.qualifiedName, 323 data[mirrorName] = new Class(mirrorName, mirror.qualifiedName,
322 superclass, mirror.isAbstract, mirror.isTypedef, 324 superclass, mirror.isAbstract, mirror.isTypedef,
323 _getComment(mirror), interfaces.toList(), 325 _getComment(mirror), interfaces.toList(),
324 _getVariables(mirror.variables), _getMethods(mirror.methods), 326 _getVariables(mirror.variables, includePrivate),
327 _getMethods(mirror.methods, includePrivate),
325 _getAnnotations(mirror)); 328 _getAnnotations(mirror));
326 } 329 }
327 }); 330 });
328 return data; 331 return data;
329 } 332 }
330 333
331 /** 334 /**
332 * Returns a map of [Parameter] objects constructed from inputted mirrors. 335 * Returns a map of [Parameter] objects constructed from inputted mirrors.
333 */ 336 */
334 Map<String, Parameter> _getParameters(List<ParameterMirror> mirrorList) { 337 Map<String, Parameter> _getParameters(List<ParameterMirror> mirrorList) {
(...skipping 220 matching lines...) Expand 10 before | Expand all | Expand 10 after
555 parameterMap['qualifiedname'] = qualifiedName; 558 parameterMap['qualifiedname'] = qualifiedName;
556 parameterMap['optional'] = isOptional.toString(); 559 parameterMap['optional'] = isOptional.toString();
557 parameterMap['named'] = isNamed.toString(); 560 parameterMap['named'] = isNamed.toString();
558 parameterMap['default'] = hasDefaultValue.toString(); 561 parameterMap['default'] = hasDefaultValue.toString();
559 parameterMap['type'] = type; 562 parameterMap['type'] = type;
560 parameterMap['value'] = defaultValue; 563 parameterMap['value'] = defaultValue;
561 parameterMap['annotations'] = new List.from(annotations); 564 parameterMap['annotations'] = new List.from(annotations);
562 return parameterMap; 565 return parameterMap;
563 } 566 }
564 } 567 }
OLDNEW
« pkg/docgen/bin/docgen.dart ('K') | « pkg/docgen/bin/docgen.dart ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698