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

5 6
import 'package:args/args.dart';

7
import '../base/common.dart';
8
import '../base/os.dart';
9 10 11 12
import '../build_info.dart';
import '../build_system/build_system.dart';
import '../cache.dart';
import '../dart/generate_synthetic_packages.dart';
13
import '../dart/pub.dart';
14
import '../flutter_plugins.dart';
15
import '../globals.dart' as globals;
16
import '../plugins.dart';
17
import '../project.dart';
18
import '../reporting/reporting.dart';
19 20 21 22
import '../runner/flutter_command.dart';

class PackagesCommand extends FlutterCommand {
  PackagesCommand() {
23 24 25 26
    addSubcommand(PackagesGetCommand('get', "Get the current package's dependencies.", PubContext.pubGet));
    addSubcommand(PackagesGetCommand('upgrade', "Upgrade the current package's dependencies to latest versions.", PubContext.pubUpgrade));
    addSubcommand(PackagesGetCommand('add', 'Add a dependency to pubspec.yaml.', PubContext.pubAdd));
    addSubcommand(PackagesGetCommand('remove', 'Removes a dependency from the current package.', PubContext.pubRemove));
27
    addSubcommand(PackagesTestCommand());
28 29 30 31 32 33 34
    addSubcommand(PackagesForwardCommand('publish', 'Publish the current package to pub.dartlang.org.', requiresPubspec: true));
    addSubcommand(PackagesForwardCommand('downgrade', 'Downgrade packages in a Flutter project.', requiresPubspec: true));
    addSubcommand(PackagesForwardCommand('deps', 'Print package dependencies.')); // path to package can be specified with --directory argument
    addSubcommand(PackagesForwardCommand('run', 'Run an executable from a package.', requiresPubspec: true));
    addSubcommand(PackagesForwardCommand('cache', 'Work with the Pub system cache.'));
    addSubcommand(PackagesForwardCommand('version', 'Print Pub version.'));
    addSubcommand(PackagesForwardCommand('uploader', 'Manage uploaders for a package on pub.dev.'));
35 36
    addSubcommand(PackagesForwardCommand('login', 'Log into pub.dev.'));
    addSubcommand(PackagesForwardCommand('logout', 'Log out of pub.dev.'));
37 38
    addSubcommand(PackagesForwardCommand('global', 'Work with Pub global packages.'));
    addSubcommand(PackagesForwardCommand('outdated', 'Analyze dependencies to find which ones can be upgraded.', requiresPubspec: true));
39
    addSubcommand(PackagesForwardCommand('token', 'Manage authentication tokens for hosted pub repositories.'));
40
    addSubcommand(PackagesPassthroughCommand());
41 42 43
  }

  @override
44
  final String name = 'pub';
45 46

  @override
47
  List<String> get aliases => const <String>['packages'];
48 49 50 51

  @override
  final String description = 'Commands for managing Flutter packages.';

52 53 54
  @override
  String get category => FlutterCommandCategory.project;

55
  @override
56
  Future<FlutterCommandResult> runCommand() async => FlutterCommandResult.fail();
57 58
}

59
class PackagesTestCommand extends FlutterCommand {
60 61 62 63
  PackagesTestCommand() {
    requiresPubspecYaml();
  }

64 65 66 67 68 69
  @override
  String get name => 'test';

  @override
  String get description {
    return 'Run the "test" package.\n'
70 71 72 73
           'This is similar to "flutter test", but instead of hosting the tests in the '
           'flutter environment it hosts the tests in a pure Dart environment. The main '
           'differences are that the "dart:ui" library is not available and that tests '
           'run faster. This is helpful for testing libraries that do not depend on any '
74 75 76 77 78
           'packages from the Flutter SDK. It is equivalent to "pub run test".';
  }

  @override
  String get invocation {
79
    return '${runner!.executableName} pub test [<tests...>]';
80 81 82
  }

  @override
83
  Future<FlutterCommandResult> runCommand() async {
84
    await pub.batch(<String>['run', 'test', ...argResults!.rest], context: PubContext.runTest);
85
    return FlutterCommandResult.success();
86
  }
87 88
}

89 90 91 92 93 94
class PackagesForwardCommand extends FlutterCommand {
  PackagesForwardCommand(this._commandName, this._description, {bool requiresPubspec = false}) {
    if (requiresPubspec) {
      requiresPubspecYaml();
    }
  }
95

96 97
  PubContext context = PubContext.pubForward;

98 99 100
  @override
  ArgParser argParser = ArgParser.allowAnything();

101 102 103 104 105 106 107 108
  final String _commandName;
  final String _description;

  @override
  String get name => _commandName;

  @override
  String get description {
109
    return '$_description\n'
110 111 112 113 114
           'This runs the "pub" tool in a Flutter context.';
  }

  @override
  String get invocation {
115
    return '${runner!.executableName} pub $_commandName [<arguments...>]';
116 117 118 119
  }

  @override
  Future<FlutterCommandResult> runCommand() async {
120
    final List<String> subArgs = argResults!.rest.toList()
121
      ..removeWhere((String arg) => arg == '--');
122 123 124 125 126
    await pub.interactively(
      <String>[ _commandName, ...subArgs],
      context: context,
      command: _commandName,
    );
127
    return FlutterCommandResult.success();
128 129 130
  }
}

131
class PackagesPassthroughCommand extends FlutterCommand {
132 133
  @override
  ArgParser argParser = ArgParser.allowAnything();
134 135 136 137 138 139 140 141 142 143 144 145

  @override
  String get name => 'pub';

  @override
  String get description {
    return 'Pass the remaining arguments to Dart\'s "pub" tool.\n'
           'This runs the "pub" tool in a Flutter context.';
  }

  @override
  String get invocation {
146
    return '${runner!.executableName} packages pub [<arguments...>]';
147 148
  }

149 150
  static final PubContext _context = PubContext.pubPassThrough;

151
  @override
152
  Future<FlutterCommandResult> runCommand() async {
153 154 155 156 157
    await pub.interactively(
      command: 'pub',
      argResults!.rest,
      context: _context,
    );
158
    return FlutterCommandResult.success();
159
  }
160
}
161

162 163 164
/// Represents the pub sub-commands that makes package-resolutions.
class PackagesGetCommand extends FlutterCommand {
  PackagesGetCommand(this._commandName, this._description, this._context);
165 166 167 168 169 170

  @override
  ArgParser argParser = ArgParser.allowAnything();

  final String _commandName;
  final String _description;
171 172 173
  final PubContext _context;

  FlutterProject? _rootProject;
174 175 176 177 178 179

  @override
  String get name => _commandName;

  @override
  String get description {
180
    return '$_description\n'
181 182 183 184 185
           'This runs the "pub" tool in a Flutter context.';
  }

  @override
  String get invocation {
186
    return '${runner!.executableName} pub $_commandName [<arguments...>]';
187 188
  }

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
  /// An [ArgParser] that accepts all options and flags that the
  ///
  /// `pub get`
  /// `pub upgrade`
  /// `pub downgrade`
  /// `pub add`
  /// `pub remove`
  ///
  /// commands accept.
  ArgParser get _permissiveArgParser {
    final ArgParser argParser = ArgParser();
    argParser.addOption('directory', abbr: 'C');
    argParser.addFlag('offline');
    argParser.addFlag('dry-run', abbr: 'n');
    argParser.addFlag('help', abbr: 'h');
    argParser.addFlag('enforce-lockfile');
    argParser.addFlag('precompile');
    argParser.addFlag('major-versions');
    argParser.addFlag('null-safety');
    argParser.addFlag('example', defaultsTo: true);
    argParser.addOption('sdk');
    argParser.addOption('path');
    argParser.addOption('hosted-url');
    argParser.addOption('git-url');
    argParser.addOption('git-ref');
    argParser.addOption('git-path');
    argParser.addFlag('dev');
216
    argParser.addFlag('verbose', abbr: 'v');
217 218 219
    return argParser;
  }

220 221
  @override
  Future<FlutterCommandResult> runCommand() async {
222
    List<String> rest = argResults!.rest;
223 224 225 226 227 228 229 230 231 232 233 234 235 236
    bool isHelp = false;
    bool example = true;
    bool exampleWasParsed = false;
    String? directoryOption;
    bool dryRun = false;
    try {
      final ArgResults results = _permissiveArgParser.parse(rest);
      isHelp = results['help'] as bool;
      directoryOption = results['directory'] as String?;
      example = results['example'] as bool;
      exampleWasParsed = results.wasParsed('example');
      dryRun = results['dry-run'] as bool;
    } on ArgParserException {
      // Let pub give the error message.
237
    }
238 239
    String? target;
    FlutterProject? rootProject;
240

241
    if (!isHelp) {
242 243 244 245 246
      if (directoryOption == null &&
          rest.length == 1 &&
          // Anything that looks like an argument should not be interpreted as
          // a directory.
          !rest.single.startsWith('-') &&
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
          ((rest.single.contains('/') || rest.single.contains(r'\')) ||
            name == 'get')) {
        // For historical reasons, if there is one argument to the command and it contains
        // a multiple-component path (i.e. contains a slash) then we use that to determine
        // to which project we're applying the command.
        target = findProjectRoot(globals.fs, rest.single);

        globals.printWarning('''
  Using a naked argument for directory is deprecated and will stop working in a future Flutter release.

  Use --directory instead.''');
        if (target == null) {
          throwToolExit('Expected to find project root in ${rest.single}.');
        }
        rest = <String>[];
      } else {
        target = findProjectRoot(globals.fs, directoryOption);
        if (target == null) {
          if (directoryOption == null) {
            throwToolExit('Expected to find project root in current working directory.');
          } else {
            throwToolExit('Expected to find project root in $directoryOption.');
          }
        }
271 272
      }

273 274 275 276
      rootProject = FlutterProject.fromDirectory(globals.fs.directory(target));
      _rootProject = rootProject;

      if (rootProject.manifest.generateSyntheticPackage) {
277
        final Environment environment = Environment(
278
          artifacts: globals.artifacts!,
279 280 281 282 283 284 285 286
          logger: globals.logger,
          cacheDir: globals.cache.getRoot(),
          engineVersion: globals.flutterVersion.engineRevision,
          fileSystem: globals.fs,
          flutterRootDir: globals.fs.directory(Cache.flutterRoot),
          outputDir: globals.fs.directory(getBuildDirectory()),
          processManager: globals.processManager,
          platform: globals.platform,
287
          usage: globals.flutterUsage,
288
          projectDir: rootProject.directory,
289
          generateDartPluginRegistry: true,
290 291 292 293 294 295 296
        );

        await generateLocalizationsSyntheticPackage(
          environment: environment,
          buildSystem: globals.buildSystem,
        );
      }
297
    }
298
    final String? relativeTarget = target == null ? null : globals.fs.path.relative(target);
299

300
    final List<String> subArgs = rest.toList()..removeWhere((String arg) => arg == '--');
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
    final Stopwatch timer = Stopwatch()..start();
    try {
      await pub.interactively(
        <String>[
          name,
          ...subArgs,
          // `dart pub get` and friends defaults to `--no-example`.
          if(!exampleWasParsed && target != null) '--example',
          if(directoryOption == null && relativeTarget != null) ...<String>['--directory', relativeTarget],
        ],
        project: rootProject,
        context: _context,
        command: name,
        touchesPackageConfig: !(isHelp || dryRun),
      );
      globals.flutterUsage.sendTiming('pub', 'get', timer.elapsed, label: 'success');
    // Not limiting to catching Exception because the exception is rethrown.
    } catch (_) { // ignore: avoid_catches_without_on_clauses
      globals.flutterUsage.sendTiming('pub', 'get', timer.elapsed, label: 'failure');
      rethrow;
    }

    if (rootProject != null) {
      // We need to regenerate the platform specific tooling for both the project
      // itself and example(if present).
      await rootProject.regeneratePlatformSpecificTooling();
      if (example && rootProject.hasExampleApp && rootProject.example.pubspecFile.existsSync()) {
        final FlutterProject exampleProject = rootProject.example;
        await exampleProject.regeneratePlatformSpecificTooling();
      }
    }
332 333 334

    return FlutterCommandResult.success();
  }
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

  /// The pub packages usage values are incorrect since these are calculated/sent
  /// before pub get completes. This needs to be performed after dependency resolution.
  @override
  Future<CustomDimensions> get usageValues async {
    final FlutterProject? rootProject = _rootProject;
    if (rootProject == null) {
      return const CustomDimensions();
    }

    int numberPlugins;
    // Do not send plugin analytics if pub has not run before.
    final bool hasPlugins = rootProject.flutterPluginsDependenciesFile.existsSync()
      && rootProject.packageConfigFile.existsSync();
    if (hasPlugins) {
      // Do not fail pub get if package config files are invalid before pub has
      // had a chance to run.
      final List<Plugin> plugins = await findPlugins(rootProject, throwOnError: false);
      numberPlugins = plugins.length;
    } else {
      numberPlugins = 0;
    }

    return CustomDimensions(
      commandPackagesNumberPlugins: numberPlugins,
      commandPackagesProjectModule: rootProject.isModule,
      commandPackagesAndroidEmbeddingVersion: rootProject.android.getEmbeddingVersion().toString().split('.').last,
    );
  }
364
}