create.dart 7.78 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2015 The Chromium Authors. All rights reserved.
// 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:io';

8
import 'package:path/path.dart' as path;
9

10
import '../android/android.dart' as android;
11
import '../base/utils.dart';
12
import '../cache.dart';
13
import '../dart/pub.dart';
14
import '../globals.dart';
15
import '../runner/flutter_command.dart';
16
import '../template.dart';
Hixie's avatar
Hixie committed
17

18
class CreateCommand extends FlutterCommand {
19
  CreateCommand() {
20
    argParser.addFlag('pub',
21 22 23
      defaultsTo: true,
      help: 'Whether to run "pub get" after the project has been created.'
    );
24 25 26 27
    argParser.addFlag(
      'with-driver-test',
      negatable: true,
      defaultsTo: false,
28
      help: 'Also add a flutter_driver dependency and generate a sample \'flutter drive\' test.'
29
    );
30 31 32 33 34
    argParser.addOption(
      'description',
      defaultsTo: 'A new flutter project.',
      help: 'The description to use for your new flutter project. This string ends up in the pubspec.yaml file.'
    );
35 36
  }

37 38 39 40 41 42 43 44 45 46 47 48 49
  @override
  final String name = 'create';

  @override
  final String description = 'Create a new Flutter project.\n\n'
    'If run on a project that already exists, this will repair the project, recreating any files that are missing.';

  @override
  final List<String> aliases = <String>['init'];

  @override
  bool get requiresProjectRoot => false;

50
  @override
51 52
  String get invocation => "${runner.executableName} $name <output directory>";

53
  @override
54
  Future<int> runInProject() async {
55
    if (argResults.rest.isEmpty) {
56
      printStatus('No option specified for the output directory.');
57
      printStatus(usage);
58
      return 2;
59 60
    }

61 62 63 64 65
    if (argResults.rest.length > 1) {
      printStatus('Multiple output directories specified.');
      return 2;
    }

66
    if (Cache.flutterRoot == null) {
67 68
      printError('Neither the --flutter-root command line flag nor the FLUTTER_ROOT environment\n'
        'variable was specified. Unable to find package:flutter.');
69 70
      return 2;
    }
71

72 73
    await Cache.instance.updateAll();

74
    String flutterRoot = path.absolute(Cache.flutterRoot);
75

76 77
    String flutterPackagesDirectory = path.join(flutterRoot, 'packages');
    String flutterPackagePath = path.join(flutterPackagesDirectory, 'flutter');
78
    if (!FileSystemEntity.isFileSync(path.join(flutterPackagePath, 'pubspec.yaml'))) {
79
      printError('Unable to find package:flutter in $flutterPackagePath');
80 81 82
      return 2;
    }

83 84 85 86 87 88
    String flutterDriverPackagePath = path.join(flutterRoot, 'packages', 'flutter_driver');
    if (!FileSystemEntity.isFileSync(path.join(flutterDriverPackagePath, 'pubspec.yaml'))) {
      printError('Unable to find package:flutter_driver in $flutterDriverPackagePath');
      return 2;
    }

89
    Directory projectDir = new Directory(argResults.rest.first);
90 91 92
    String dirPath = path.normalize(projectDir.absolute.path);
    String projectName = _normalizeProjectName(path.basename(dirPath));

93 94 95 96
    if (_validateProjectDir(dirPath) != null) {
      printError(_validateProjectDir(dirPath));
      return 1;
    }
97 98 99 100 101
    if (_validateProjectName(projectName) != null) {
      printError(_validateProjectName(projectName));
      return 1;
    }

102 103 104 105 106 107 108
    _renderTemplates(
      projectName,
      argResults['description'],
      dirPath,
      flutterPackagesDirectory,
      renderDriverTest: argResults['with-driver-test']
    );
109

110 111
    printStatus('');

112
    if (argResults['pub']) {
113
      int code = await pubGet(directory: dirPath);
Hixie's avatar
Hixie committed
114 115 116 117
      if (code != 0)
        return code;
    }

118
    printStatus('');
119 120 121 122 123 124 125 126 127

    // Run doctor; tell the user the next steps.
    if (doctor.canLaunchAnything) {
      // Let them know a summary of the state of their tooling.
      doctor.summary();

      printStatus('''
All done! In order to run your application, type:

128
  \$ cd $dirPath
129 130 131 132 133 134 135 136 137 138 139 140
  \$ flutter run
''');
    } else {
      printStatus("You'll need to install additional components before you can run "
        "your Flutter app:");
      printStatus('');

      // Give the user more detailed analysis.
      doctor.diagnose();
      printStatus('');
      printStatus("After installing components, run 'flutter doctor' in order to "
        "re-validate your setup.");
141
      printStatus("When complete, type 'flutter run' from the '$dirPath' "
142 143 144
        "directory in order to launch your app.");
    }

Hixie's avatar
Hixie committed
145 146
    return 0;
  }
147

148
  void _renderTemplates(String projectName, String projectDescription, String dirPath,
149
      String flutterPackagesDirectory, { bool renderDriverTest: false }) {
Devon Carew's avatar
Devon Carew committed
150
    new Directory(dirPath).createSync(recursive: true);
151

Devon Carew's avatar
Devon Carew committed
152 153
    flutterPackagesDirectory = path.normalize(flutterPackagesDirectory);
    flutterPackagesDirectory = _relativePath(from: dirPath, to: flutterPackagesDirectory);
154

Devon Carew's avatar
Devon Carew committed
155
    printStatus('Creating project ${path.basename(projectName)}:');
156

Ian Hickson's avatar
Ian Hickson committed
157
    Map<String, dynamic> templateContext = <String, dynamic>{
158
      'projectName': projectName,
159 160
      'androidIdentifier': _createAndroidIdentifier(projectName),
      'iosIdentifier': _createUTIIdentifier(projectName),
161
      'description': projectDescription,
Devon Carew's avatar
Devon Carew committed
162
      'flutterPackagesDirectory': flutterPackagesDirectory,
163
      'androidMinApiLevel': android.minApiLevel
164
    };
165

166
    if (renderDriverTest)
167
      templateContext['withDriverTest?'] = <String, dynamic>{};
168

169 170 171
    Template createTemplate = new Template.fromName('create');
    createTemplate.render(new Directory(dirPath), templateContext,
        overwriteExisting: false);
172

173 174 175 176 177
    if (renderDriverTest) {
      Template driverTemplate = new Template.fromName('driver');
      driverTemplate.render(new Directory(path.join(dirPath, 'test_driver')),
          templateContext, overwriteExisting: false);
    }
178
  }
179 180 181 182 183
}

String _normalizeProjectName(String name) {
  name = name.replaceAll('-', '_').replaceAll(' ', '_');
  // Strip any extension (like .dart).
184
  if (name.contains('.'))
185 186 187 188
    name = name.substring(0, name.indexOf('.'));
  return name;
}

189 190 191 192 193
String _createAndroidIdentifier(String name) {
  return 'com.yourcompany.${camelCase(name)}';
}

String _createUTIIdentifier(String name) {
194
  // Create a UTI (https://en.wikipedia.org/wiki/Uniform_Type_Identifier) from a base name
195
  RegExp disallowed = new RegExp(r"[^a-zA-Z0-9\-\.\u0080-\uffff]+");
196 197
  name = camelCase(name).replaceAll(disallowed, '');
  name = name.isEmpty ? 'untitled' : name;
Chinmay Garde's avatar
Chinmay Garde committed
198
  return 'com.yourcompany.$name';
199
}
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225

final Set<String> _packageDependencies = new Set<String>.from(<String>[
  'args',
  'async',
  'collection',
  'convert',
  'flutter',
  'html',
  'intl',
  'logging',
  'matcher',
  'mime',
  'path',
  'plugin',
  'pool',
  'test',
  'utf',
  'watcher',
  'yaml'
]);

/// Return `null` if the project name is legal. Return a validation message if
/// we should disallow the project name.
String _validateProjectName(String projectName) {
  if (_packageDependencies.contains(projectName)) {
    return "Invalid project name: '$projectName' - this will conflict with Flutter "
226
      "package dependencies.";
227
  }
228 229
  return null;
}
230

231 232 233 234
/// Return `null` if the project directory is legal. Return a validation message
/// if we should disallow the directory name.
String _validateProjectDir(String projectName) {
  FileSystemEntityType type = FileSystemEntity.typeSync(projectName);
235

236 237 238 239 240 241 242 243 244 245
  if (type != FileSystemEntityType.NOT_FOUND) {
    switch(type) {
      case FileSystemEntityType.FILE:
        // Do not overwrite files.
        return "Invalid project name: '$projectName' - file exists.";
      case FileSystemEntityType.LINK:
        // Do not overwrite links.
        return "Invalid project name: '$projectName' - refers to a link.";
    }
  }
246

247 248
  return null;
}
Devon Carew's avatar
Devon Carew committed
249 250 251 252 253 254 255 256

String _relativePath({ String from, String to }) {
  String result = path.relative(to, from: from);
  // `path.relative()` doesn't always return a correct result: dart-lang/path#12.
  if (FileSystemEntity.isDirectorySync(path.join(from, result)))
    return result;
  return to;
}