dartdoc.dart 17.3 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:convert';
import 'dart:io';

9
import 'package:args/args.dart';
10
import 'package:intl/intl.dart';
11
import 'package:path/path.dart' as path;
12
import 'package:process/process.dart';
13

14 15
const String kDocsRoot = 'dev/docs';
const String kPublishRoot = '$kDocsRoot/doc';
16
const String kSnippetsRoot = 'dev/snippets';
Seth Ladd's avatar
Seth Ladd committed
17

18 19 20
/// This script expects to run with the cwd as the root of the flutter repo. It
/// will generate documentation for the packages in `//packages/` and write the
/// documentation to `//dev/docs/doc/api/`.
21
///
Seth Ladd's avatar
Seth Ladd committed
22 23 24 25
/// This script also updates the index.html file so that it can be placed
/// at the root of docs.flutter.io. We are keeping the files inside of
/// docs.flutter.io/flutter for now, so we need to manipulate paths
/// a bit. See https://github.com/flutter/flutter/issues/3900 for more info.
26 27 28 29 30
///
/// This will only work on UNIX systems, not Windows. It requires that 'git' be
/// in your path. It requires that 'flutter' has been run previously. It uses
/// the version of Dart downloaded by the 'flutter' tool in this repository and
/// will crash if that is absent.
31
Future<void> main(List<String> arguments) async {
32 33
  final ArgParser argParser = _createArgsParser();
  final ArgResults args = argParser.parse(arguments);
34
  if (args['help'] as bool) {
35 36 37 38
    print ('Usage:');
    print (argParser.usage);
    exit(0);
  }
39 40 41 42
  // If we're run from the `tools` dir, set the cwd to the repo root.
  if (path.basename(Directory.current.path) == 'tools')
    Directory.current = Directory.current.parent.parent;

43
  final ProcessResult flutter = Process.runSync('flutter', <String>[]);
44
  final File versionFile = File('version');
45
  if (flutter.exitCode != 0 || !versionFile.existsSync())
46
    throw Exception('Failed to determine Flutter version.');
47
  final String version = versionFile.readAsStringSync();
48

49
  // Create the pubspec.yaml file.
50
  final StringBuffer buf = StringBuffer();
51
  buf.writeln('name: Flutter');
52
  buf.writeln('homepage: https://flutter.dev');
53
  // TODO(dnfield): Re-factor for proper versioning, https://github.com/flutter/flutter/issues/55409
54
  buf.writeln('version: 0.0.0');
55
  buf.writeln('dependencies:');
56
  for (final String package in findPackageNames()) {
57
    buf.writeln('  $package:');
58
    buf.writeln('    sdk: flutter');
59
  }
60 61 62 63
  buf.writeln('  platform_integration: 0.0.1');
  buf.writeln('dependency_overrides:');
  buf.writeln('  platform_integration:');
  buf.writeln('    path: platform_integration');
64
  File('$kDocsRoot/pubspec.yaml').writeAsStringSync(buf.toString());
65 66

  // Create the library file.
67
  final Directory libDir = Directory('$kDocsRoot/lib');
68 69
  libDir.createSync();

70
  final StringBuffer contents = StringBuffer('library temp_doc;\n\n');
71
  for (final String libraryRef in libraryRefs()) {
72
    contents.writeln("import 'package:$libraryRef';");
73
  }
74
  File('$kDocsRoot/lib/temp_doc.dart').writeAsStringSync(contents.toString());
75

76 77 78 79 80 81 82
  final String flutterRoot = Directory.current.path;
  final Map<String, String> pubEnvironment = <String, String>{
    'FLUTTER_ROOT': flutterRoot,
  };

  // If there's a .pub-cache dir in the flutter root, use that.
  final String pubCachePath = '$flutterRoot/.pub-cache';
83
  if (Directory(pubCachePath).existsSync()) {
84 85 86 87 88
    pubEnvironment['PUB_CACHE'] = pubCachePath;
  }

  final String pubExecutable = '$flutterRoot/bin/cache/dart-sdk/bin/pub';

89
  // Run pub.
90
  ProcessWrapper process = ProcessWrapper(await Process.start(
91
    pubExecutable,
92
    <String>['get'],
93
    workingDirectory: kDocsRoot,
94
    environment: pubEnvironment,
95
  ));
96 97
  printStream(process.stdout, prefix: 'pub:stdout: ');
  printStream(process.stderr, prefix: 'pub:stderr: ');
98
  final int code = await process.done;
99 100 101
  if (code != 0)
    exit(code);

102
  createFooter('$kDocsRoot/lib/', version);
103
  copyAssets();
104
  createSearchMetadata('$kDocsRoot/lib/opensearch.xml', '$kDocsRoot/doc/opensearch.xml');
105
  cleanOutSnippets();
106

107 108 109
  final List<String> dartdocBaseArgs = <String>[
    'global',
    'run',
110
    if (args['checked'] as bool) '-c',
111 112
    'dartdoc',
  ];
113

114
  // Verify which version of dartdoc we're using.
115
  final ProcessResult result = Process.runSync(
116
    pubExecutable,
117
    <String>[...dartdocBaseArgs, '--version'],
118
    workingDirectory: kDocsRoot,
119
    environment: pubEnvironment,
120
  );
121
  print('\n${result.stdout}flutter version: $version\n');
122

123
  // Generate the documentation.
124 125
  // We don't need to exclude flutter_tools in this list because it's not in the
  // recursive dependencies of the package defined at dev/docs/pubspec.yaml
126 127
  final List<String> dartdocArgs = <String>[
    ...dartdocBaseArgs,
128
    '--allow-tools',
129 130
    if (args['json'] as bool) '--json',
    if (args['validate-links'] as bool) '--validate-links' else '--no-validate-links',
131 132 133
    '--link-to-source-excludes', '../../bin/cache',
    '--link-to-source-root', '../..',
    '--link-to-source-uri-template', 'https://github.com/flutter/flutter/blob/master/%f%#L%l%',
134
    '--inject-html',
135
    '--use-base-href',
136 137
    '--header', 'styles.html',
    '--header', 'analytics.html',
138
    '--header', 'survey.html',
139
    '--header', 'snippets.html',
140
    '--header', 'opensearch.html',
141
    '--footer-text', 'lib/footer.html',
142 143
    '--allow-warnings-in-packages',
    <String>[
144 145 146 147 148 149 150
      'Flutter',
      'flutter',
      'platform_integration',
      'flutter_test',
      'flutter_driver',
      'flutter_localizations',
    ].join(','),
151
    '--exclude-packages',
152 153 154 155 156 157 158
    <String>[
      'analyzer',
      'args',
      'barback',
      'cli_util',
      'csslib',
      'flutter_goldens',
159
      'flutter_goldens_client',
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
      'front_end',
      'fuchsia_remote_debug_protocol',
      'glob',
      'html',
      'http_multi_server',
      'io',
      'isolate',
      'js',
      'kernel',
      'logging',
      'mime',
      'mockito',
      'node_preamble',
      'plugin',
      'shelf',
      'shelf_packages_handler',
      'shelf_static',
      'shelf_web_socket',
      'utf',
      'watcher',
      'yaml',
    ].join(','),
182
    '--exclude',
183 184 185 186 187 188 189 190 191 192
    <String>[
      'package:Flutter/temp_doc.dart',
      'package:http/browser_client.dart',
      'package:intl/intl_browser.dart',
      'package:matcher/mirror_matchers.dart',
      'package:quiver/io.dart',
      'package:quiver/mirrors.dart',
      'package:vm_service_client/vm_service_client.dart',
      'package:web_socket_channel/html.dart',
    ].join(','),
193
    '--favicon=favicon.ico',
194
    '--package-order', 'flutter,Dart,platform_integration,flutter_test,flutter_driver',
195
    '--auto-include-dependencies',
196
  ];
197

198
  String quote(String arg) => arg.contains(' ') ? "'$arg'" : arg;
199
  print('Executing: (cd $kDocsRoot ; $pubExecutable ${dartdocArgs.map<String>(quote).join(' ')})');
200

201
  process = ProcessWrapper(await Process.start(
202
    pubExecutable,
203
    dartdocArgs,
204
    workingDirectory: kDocsRoot,
205
    environment: pubEnvironment,
206
  ));
207 208
  printStream(process.stdout, prefix: args['json'] as bool ? '' : 'dartdoc:stdout: ',
    filter: args['verbose'] as bool ? const <Pattern>[] : <Pattern>[
209 210
      RegExp(r'^generating docs for library '), // unnecessary verbosity
      RegExp(r'^pars'), // unnecessary verbosity
211 212
    ],
  );
213 214
  printStream(process.stderr, prefix: args['json'] as bool ? '' : 'dartdoc:stderr: ',
    filter: args['verbose'] as bool ? const <Pattern>[] : <Pattern>[
215
      RegExp(r'^ warning: .+: \(.+/\.pub-cache/hosted/pub.dartlang.org/.+\)'), // packages outside our control
216 217
    ],
  );
218
  final int exitCode = await process.done;
Seth Ladd's avatar
Seth Ladd committed
219 220 221 222

  if (exitCode != 0)
    exit(exitCode);

223 224
  sanityCheckDocs();

Seth Ladd's avatar
Seth Ladd committed
225 226 227
  createIndexAndCleanup();
}

228
ArgParser _createArgsParser() {
229
  final ArgParser parser = ArgParser();
230 231 232 233 234 235 236 237 238 239
  parser.addFlag('help', abbr: 'h', negatable: false,
      help: 'Show command help.');
  parser.addFlag('verbose', negatable: true, defaultsTo: true,
      help: 'Whether to report all error messages (on) or attempt to '
          'filter out some known false positives (off).  Shut this off '
          'locally if you want to address Flutter-specific issues.');
  parser.addFlag('checked', abbr: 'c', negatable: true,
      help: 'Run dartdoc in checked mode.');
  parser.addFlag('json', negatable: true,
      help: 'Display json-formatted output from dartdoc and skip stdout/stderr prefixing.');
240 241
  parser.addFlag('validate-links', negatable: true,
      help: 'Display warnings for broken links generated by dartdoc (slow)');
242 243 244
  return parser;
}

245
final RegExp gitBranchRegexp = RegExp(r'^## (.*)');
246

247 248 249 250 251
String getBranchName() {
  final ProcessResult gitResult = Process.runSync('git', <String>['status', '-b', '--porcelain']);
  if (gitResult.exitCode != 0)
    throw 'git status exit with non-zero exit code: ${gitResult.exitCode}';
  final Match gitBranchMatch = gitBranchRegexp.firstMatch(
252
      (gitResult.stdout as String).trim().split('\n').first);
253 254 255
  return gitBranchMatch == null ? '' : gitBranchMatch.group(1).split('...').first;
}

256
String gitRevision() {
257 258
  const int kGitRevisionLength = 10;

259
  final ProcessResult gitResult = Process.runSync('git', <String>['rev-parse', 'HEAD']);
260
  if (gitResult.exitCode != 0)
261
    throw 'git rev-parse exit with non-zero exit code: ${gitResult.exitCode}';
262
  final String gitRevision = (gitResult.stdout as String).trim();
263

264 265
  return gitRevision.length > kGitRevisionLength ? gitRevision.substring(0, kGitRevisionLength) : gitRevision;
}
266

267
void createFooter(String footerPath, String version) {
268
  final String timestamp = DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now());
269
  final String gitBranch = getBranchName();
270 271 272 273
  final String gitBranchOut = gitBranch.isEmpty ? '' : '• $gitBranch';
  File('${footerPath}footer.html').writeAsStringSync('<script src="footer.js"></script>');
  File('$kPublishRoot/api/footer.js')
    ..createSync(recursive: true)
274 275
    ..writeAsStringSync('''
(function() {
Dan Field's avatar
Dan Field committed
276 277 278 279 280 281 282 283 284
  var span = document.querySelector('footer>span');
  if (span) {
    span.innerText = 'Flutter $version  $timestamp  ${gitRevision()} $gitBranchOut';
  }
  var sourceLink = document.querySelector('a.source-link');
  if (sourceLink) {
    sourceLink.href = sourceLink.href.replace('/master/', '/${gitRevision()}/');
  }
})();
285
''');
286 287
}

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
/// Generates an OpenSearch XML description that can be used to add a custom
/// search for Flutter API docs to the browser. Unfortunately, it has to know
/// the URL to which site to search, so we customize it here based upon the
/// branch name.
void createSearchMetadata(String templatePath, String metadataPath) {
  final String template = File(templatePath).readAsStringSync();
  final String branch = getBranchName();
  final String metadata = template.replaceAll(
    '{SITE_URL}',
    branch == 'stable' ? 'https://docs.flutter.io/' : 'https://master-docs.flutter.io/',
  );
  Directory(path.dirname(metadataPath)).create(recursive: true);
  File(metadataPath).writeAsStringSync(metadata);
}

303 304 305 306 307 308 309 310 311 312 313
/// Recursively copies `srcDir` to `destDir`, invoking [onFileCopied], if
/// specified, for each source/destination file pair.
///
/// Creates `destDir` if needed.
void copyDirectorySync(Directory srcDir, Directory destDir, [void onFileCopied(File srcFile, File destFile)]) {
  if (!srcDir.existsSync())
    throw Exception('Source directory "${srcDir.path}" does not exist, nothing to copy');

  if (!destDir.existsSync())
    destDir.createSync(recursive: true);

314
  for (final FileSystemEntity entity in srcDir.listSync()) {
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    final String newPath = path.join(destDir.path, path.basename(entity.path));
    if (entity is File) {
      final File newFile = File(newPath);
      entity.copySync(newPath);
      onFileCopied?.call(entity, newFile);
    } else if (entity is Directory) {
      copyDirectorySync(entity, Directory(newPath));
    } else {
      throw Exception('${entity.path} is neither File nor Directory');
    }
  }
}

void copyAssets() {
  final Directory assetsDir = Directory(path.join(kPublishRoot, 'assets'));
  if (assetsDir.existsSync()) {
    assetsDir.deleteSync(recursive: true);
  }
  copyDirectorySync(
      Directory(path.join(kDocsRoot, 'assets')),
      Directory(path.join(kPublishRoot, 'assets')),
          (File src, File dest) => print('Copied ${src.path} to ${dest.path}'));
}

339 340
/// Clean out any existing snippets so that we don't publish old files from
/// previous runs accidentally.
341 342 343 344 345 346 347 348 349
void cleanOutSnippets() {
  final Directory snippetsDir = Directory(path.join(kPublishRoot, 'snippets'));
  if (snippetsDir.existsSync()) {
    snippetsDir
      ..deleteSync(recursive: true)
      ..createSync(recursive: true);
  }
}

350
void sanityCheckDocs() {
351
  final List<String> canaries = <String>[
352 353 354 355 356 357 358 359 360
    '$kPublishRoot/assets/overrides.css',
    '$kPublishRoot/api/dart-io/File-class.html',
    '$kPublishRoot/api/dart-ui/Canvas-class.html',
    '$kPublishRoot/api/dart-ui/Canvas/drawRect.html',
    '$kPublishRoot/api/flutter_driver/FlutterDriver/FlutterDriver.connectedTo.html',
    '$kPublishRoot/api/flutter_test/WidgetTester/pumpWidget.html',
    '$kPublishRoot/api/material/Material-class.html',
    '$kPublishRoot/api/material/Tooltip-class.html',
    '$kPublishRoot/api/widgets/Widget-class.html',
361
  ];
362
  for (final String canary in canaries) {
363 364
    if (!File(canary).existsSync())
      throw Exception('Missing "$canary", which probably means the documentation failed to build correctly.');
365 366 367
  }
}

Seth Ladd's avatar
Seth Ladd committed
368 369 370
/// Creates a custom index.html because we try to maintain old
/// paths. Cleanup unused index.html files no longer needed.
void createIndexAndCleanup() {
371
  print('\nCreating a custom index.html in $kPublishRoot/index.html');
372
  removeOldFlutterDocsDir();
Seth Ladd's avatar
Seth Ladd committed
373 374 375
  renameApiDir();
  copyIndexToRootOfDocs();
  addHtmlBaseToIndex();
376
  changePackageToSdkInTitlebar();
Seth Ladd's avatar
Seth Ladd committed
377
  putRedirectInOldIndexLocation();
378
  writeSnippetsIndexFile();
Seth Ladd's avatar
Seth Ladd committed
379 380 381
  print('\nDocs ready to go!');
}

382 383
void removeOldFlutterDocsDir() {
  try {
384
    Directory('$kPublishRoot/flutter').deleteSync(recursive: true);
385
  } on FileSystemException {
386 387 388 389
    // If the directory does not exist, that's OK.
  }
}

Seth Ladd's avatar
Seth Ladd committed
390
void renameApiDir() {
391
  Directory('$kPublishRoot/api').renameSync('$kPublishRoot/flutter');
Seth Ladd's avatar
Seth Ladd committed
392 393
}

394
void copyIndexToRootOfDocs() {
395
  File('$kPublishRoot/flutter/index.html').copySync('$kPublishRoot/index.html');
Seth Ladd's avatar
Seth Ladd committed
396 397
}

398
void changePackageToSdkInTitlebar() {
399
  final File indexFile = File('$kPublishRoot/index.html');
400 401
  String indexContents = indexFile.readAsStringSync();
  indexContents = indexContents.replaceFirst(
402 403
    '<li><a href="https://flutter.dev">Flutter package</a></li>',
    '<li><a href="https://flutter.dev">Flutter SDK</a></li>',
404 405 406 407 408
  );

  indexFile.writeAsStringSync(indexContents);
}

Seth Ladd's avatar
Seth Ladd committed
409
void addHtmlBaseToIndex() {
410
  final File indexFile = File('$kPublishRoot/index.html');
Seth Ladd's avatar
Seth Ladd committed
411
  String indexContents = indexFile.readAsStringSync();
412 413 414 415
  indexContents = indexContents.replaceFirst(
    '</title>\n',
    '</title>\n  <base href="./flutter/">\n',
  );
416 417
  indexContents = indexContents.replaceAll(
    'href="Android/Android-library.html"',
418
    'href="/javadoc/"',
419
  );
420 421
  indexContents = indexContents.replaceAll(
      'href="iOS/iOS-library.html"',
422
      'href="/objcdoc/"',
423 424
  );

Seth Ladd's avatar
Seth Ladd committed
425 426 427 428
  indexFile.writeAsStringSync(indexContents);
}

void putRedirectInOldIndexLocation() {
429
  const String metaTag = '<meta http-equiv="refresh" content="0;URL=../index.html">';
430
  File('$kPublishRoot/flutter/index.html').writeAsStringSync(metaTag);
431 432
}

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

void writeSnippetsIndexFile() {
  final Directory snippetsDir = Directory(path.join(kPublishRoot, 'snippets'));
  if (snippetsDir.existsSync()) {
    const JsonEncoder jsonEncoder = JsonEncoder.withIndent('    ');
    final Iterable<File> files = snippetsDir
        .listSync()
        .whereType<File>()
        .where((File file) => path.extension(file.path) == '.json');
        // Combine all the metadata into a single JSON array.
    final Iterable<String> fileContents = files.map((File file) => file.readAsStringSync());
    final List<dynamic> metadataObjects = fileContents.map<dynamic>(json.decode).toList();
    final String jsonArray = jsonEncoder.convert(metadataObjects);
    File('$kPublishRoot/snippets/index.json').writeAsStringSync(jsonArray);
  }
}

Seth Ladd's avatar
Seth Ladd committed
450
List<String> findPackageNames() {
451
  return findPackages().map<String>((FileSystemEntity file) => path.basename(file.path)).toList();
452 453
}

454
/// Finds all packages in the Flutter SDK
455
List<Directory> findPackages() {
456
  return Directory('packages')
457
    .listSync()
458 459 460
    .where((FileSystemEntity entity) {
      if (entity is! Directory)
        return false;
461
      final File pubspec = File('${entity.path}/pubspec.yaml');
462 463
      // TODO(ianh): Use a real YAML parser here
      return !pubspec.readAsStringSync().contains('nodoc: true');
464
    })
465
    .cast<Directory>()
466 467 468
    .toList();
}

469
/// Returns import or on-disk paths for all libraries in the Flutter SDK.
470
Iterable<String> libraryRefs() sync* {
471
  for (final Directory dir in findPackages()) {
472
    final String dirName = path.basename(dir.path);
473
    for (final FileSystemEntity file in Directory('${dir.path}/lib').listSync()) {
474
      if (file is File && file.path.endsWith('.dart')) {
475 476
        yield '$dirName/${path.basename(file.path)}';
      }
477 478
    }
  }
479 480

  // Add a fake package for platform integration APIs.
481 482
  yield 'platform_integration/android.dart';
  yield 'platform_integration/ios.dart';
483 484
}

485
void printStream(Stream<List<int>> stream, { String prefix = '', List<Pattern> filter = const <Pattern>[] }) {
486 487
  assert(prefix != null);
  assert(filter != null);
488
  stream
489 490
    .transform<String>(utf8.decoder)
    .transform<String>(const LineSplitter())
491 492 493 494
    .listen((String line) {
      if (!filter.any((Pattern pattern) => line.contains(pattern)))
        print('$prefix$line'.trim());
    });
495
}