create.dart 7.71 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
  @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
  bool get requiresProjectRoot => false;

47
  @override
48 49
  String get invocation => "${runner.executableName} $name <output directory>";

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

58 59 60 61 62
    if (argResults.rest.length > 1) {
      printStatus('Multiple output directories specified.');
      return 2;
    }

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

69 70
    await Cache.instance.updateAll();

71
    String flutterRoot = path.absolute(Cache.flutterRoot);
72

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

80 81 82 83 84 85
    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;
    }

86
    Directory projectDir = new Directory(argResults.rest.first);
87 88 89
    String dirPath = path.normalize(projectDir.absolute.path);
    String projectName = _normalizeProjectName(path.basename(dirPath));

90 91 92 93
    if (_validateProjectDir(dirPath) != null) {
      printError(_validateProjectDir(dirPath));
      return 1;
    }
94 95 96 97 98
    if (_validateProjectName(projectName) != null) {
      printError(_validateProjectName(projectName));
      return 1;
    }

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

107 108
    printStatus('');

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

115
    printStatus('');
116 117 118 119 120 121 122 123 124

    // 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:

125
  \$ cd $dirPath
126 127 128 129 130 131 132 133 134 135 136 137
  \$ 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.");
138
      printStatus("When complete, type 'flutter run' from the '$dirPath' "
139 140 141
        "directory in order to launch your app.");
    }

Hixie's avatar
Hixie committed
142 143
    return 0;
  }
144

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

Devon Carew's avatar
Devon Carew committed
149 150
    flutterPackagesDirectory = path.normalize(flutterPackagesDirectory);
    flutterPackagesDirectory = _relativePath(from: dirPath, to: flutterPackagesDirectory);
151

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

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

163
    if (renderDriverTest)
164
      templateContext['withDriverTest?'] = <String, dynamic>{};
165

166 167 168
    Template createTemplate = new Template.fromName('create');
    createTemplate.render(new Directory(dirPath), templateContext,
        overwriteExisting: false);
169

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

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

186 187 188 189 190
String _createAndroidIdentifier(String name) {
  return 'com.yourcompany.${camelCase(name)}';
}

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

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 "
223
      "package dependencies.";
224
  }
225 226
  return null;
}
227

228 229 230 231
/// 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);
232

233 234 235 236 237 238 239 240 241 242
  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.";
    }
  }
243

244 245
  return null;
}
Devon Carew's avatar
Devon Carew committed
246 247 248 249 250 251 252 253

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;
}