main.dart 6.93 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
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:io' hide Platform;

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

import 'configuration.dart';
import 'snippets.dart';

14
const String _kSerialOption = 'serial';
15
const String _kElementOption = 'element';
16
const String _kHelpOption = 'help';
17 18
const String _kInputOption = 'input';
const String _kLibraryOption = 'library';
19
const String _kOutputOption = 'output';
20 21 22
const String _kPackageOption = 'package';
const String _kTemplateOption = 'template';
const String _kTypeOption = 'type';
23
const String _kShowDartPad = 'dartpad';
24

25 26 27 28 29 30 31 32 33 34
String getChannelName() {
  final RegExp gitBranchRegexp = RegExp(r'^## (.*)');
  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(
      (gitResult.stdout as String).trim().split('\n').first);
  return gitBranchMatch == null ? '<unknown>' : gitBranchMatch.group(1).split('...').first;
}

35 36 37 38 39 40 41 42 43 44
/// Generates snippet dartdoc output for a given input, and creates any sample
/// applications needed by the snippet.
void main(List<String> argList) {
  const Platform platform = LocalPlatform();
  final Map<String, String> environment = platform.environment;
  final ArgParser parser = ArgParser();
  final List<String> snippetTypes =
      SnippetType.values.map<String>((SnippetType type) => getEnumName(type)).toList();
  parser.addOption(
    _kTypeOption,
45
    defaultsTo: getEnumName(SnippetType.sample),
46 47 48
    allowed: snippetTypes,
    allowedHelp: <String, String>{
      getEnumName(SnippetType.sample):
49 50 51
          'Produce a code sample application complete with embedding the sample in an '
          'application template.',
      getEnumName(SnippetType.snippet):
52
          'Produce a nicely formatted piece of sample code. Does not embed the '
53
          'sample into an application template.',
54 55 56 57 58 59 60 61
    },
    help: 'The type of snippet to produce.',
  );
  parser.addOption(
    _kTemplateOption,
    defaultsTo: null,
    help: 'The name of the template to inject the code into.',
  );
62 63 64
  parser.addOption(
    _kOutputOption,
    defaultsTo: null,
65
    help: 'The output path for the generated sample application. Overrides '
66
        'the naming generated by the --package/--library/--element arguments. '
67
        'Metadata will be written alongside in a .json file. '
68 69
        'The basename of this argument is used as the ID',
  );
70 71 72
  parser.addOption(
    _kInputOption,
    defaultsTo: environment['INPUT'],
73
    help: 'The input file containing the sample code to inject.',
74 75 76 77
  );
  parser.addOption(
    _kPackageOption,
    defaultsTo: environment['PACKAGE_NAME'],
78
    help: 'The name of the package that this sample belongs to.',
79 80 81 82
  );
  parser.addOption(
    _kLibraryOption,
    defaultsTo: environment['LIBRARY_NAME'],
83
    help: 'The name of the library that this sample belongs to.',
84 85 86 87
  );
  parser.addOption(
    _kElementOption,
    defaultsTo: environment['ELEMENT_NAME'],
88
    help: 'The name of the element that this sample belongs to.',
89
  );
90 91 92 93 94
  parser.addOption(
    _kSerialOption,
    defaultsTo: environment['INVOCATION_INDEX'],
    help: 'A unique serial number for this snippet tool invocation.',
  );
95 96 97 98 99 100
  parser.addFlag(
    _kHelpOption,
    defaultsTo: false,
    negatable: false,
    help: 'Prints help documentation for this command',
  );
101 102 103 104
  parser.addFlag(
    _kShowDartPad,
    defaultsTo: false,
    negatable: false,
105
    help: "Indicates whether DartPad should be included in the sample's "
106
        'final HTML output. This flag only applies when the type parameter is '
107
        '"sample".',
108
  );
109 110 111

  final ArgResults args = parser.parse(argList);

112
  if (args[_kHelpOption] as bool) {
113 114 115 116
    stderr.writeln(parser.usage);
    exit(0);
  }

117 118 119 120
  final SnippetType snippetType = SnippetType.values
      .firstWhere((SnippetType type) => getEnumName(type) == args[_kTypeOption], orElse: () => null);
  assert(snippetType != null, "Unable to find '${args[_kTypeOption]}' in SnippetType enum.");

121
  if (args[_kShowDartPad] == true && snippetType != SnippetType.sample) {
122
    errorExit('${args[_kTypeOption]} was selected, but the --dartpad flag is only valid '
123
      'for application sample code.');
124 125
  }

126 127 128 129 130 131
  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.');
  }

132
  final File input = File(args['input'] as String);
133 134 135 136 137
  if (!input.existsSync()) {
    errorExit('The input file ${input.path} does not exist.');
  }

  String template;
138
  if (snippetType == SnippetType.sample) {
139 140
    final String templateArg = args[_kTemplateOption] as String;
    if (templateArg == null || templateArg.isEmpty) {
141 142
      stderr.writeln(parser.usage);
      errorExit('The --$_kTemplateOption option must be specified on the command '
143
          'line for application samples.');
144
    }
145
    template = templateArg.replaceAll(RegExp(r'.tmpl$'), '');
146 147
  }

148 149 150 151 152
  String emptyToNull(String value) => value?.isEmpty ?? true ? null : value;
  final String packageName = emptyToNull(args[_kPackageOption] as String);
  final String libraryName = emptyToNull(args[_kLibraryOption] as String);
  final String elementName = emptyToNull(args[_kElementOption] as String);
  final String serial = emptyToNull(args[_kSerialOption] as String);
153
  final List<String> id = <String>[];
154
  if (args[_kOutputOption] != null) {
155
    id.add(path.basename(path.basenameWithoutExtension(args[_kOutputOption] as String)));
156
  } else {
157 158
    if (packageName != null && packageName != 'flutter') {
      id.add(packageName);
159
    }
160 161
    if (libraryName != null) {
      id.add(libraryName);
162
    }
163 164
    if (elementName != null) {
      id.add(elementName);
165
    }
166 167 168
    if (serial != null) {
      id.add(serial);
    }
169 170
    if (id.isEmpty) {
      errorExit('Unable to determine ID. At least one of --$_kPackageOption, '
171 172
          '--$_kLibraryOption, --$_kElementOption, -$_kSerialOption, or the environment variables '
          'PACKAGE_NAME, LIBRARY_NAME, ELEMENT_NAME, or INVOCATION_INDEX must be non-empty.');
173
    }
174 175 176 177 178 179
  }

  final SnippetGenerator generator = SnippetGenerator();
  stdout.write(generator.generate(
    input,
    snippetType,
180
    showDartPad: args[_kShowDartPad] as bool,
181
    template: template,
182
    output: args[_kOutputOption] != null ? File(args[_kOutputOption] as String) : null,
183 184
    metadata: <String, Object>{
      'sourcePath': environment['SOURCE_PATH'],
185 186 187
      'sourceLine': environment['SOURCE_LINE'] != null
          ? int.tryParse(environment['SOURCE_LINE'])
          : null,
188
      'id': id.join('.'),
189
      'channel': getChannelName(),
190
      'serial': serial,
191 192 193 194
      'package': packageName,
      'library': libraryName,
      'element': elementName,
    },
195
  ));
196

197 198
  exit(0);
}