From 13a6d40f90836ecb877dd8ae816d8696524dab1e Mon Sep 17 00:00:00 2001 From: Kevin Moore Date: Wed, 6 Dec 2017 08:10:56 -0800 Subject: [PATCH] flutter_tools: ensure the context value passed to pub is consistent (#13366) Adds a class `PubContext` with a fixed set of allowed values Make it clear these values should not be changed casually Fixed one inconsistency already: update_packages vs update_pkgs Provide more information for verify calls Eliminate `ctx_` prefix. --- .../lib/src/commands/create.dart | 6 +- .../lib/src/commands/packages.dart | 4 +- .../lib/src/commands/update_packages.dart | 6 +- .../lib/src/commands/upgrade.dart | 2 +- packages/flutter_tools/lib/src/dart/pub.dart | 65 ++++++++++++++----- .../lib/src/runner/flutter_command.dart | 2 +- .../commands/analyze_continuously_test.dart | 4 +- .../flutter_tools/test/dart/pub_get_test.dart | 8 +-- 8 files changed, 65 insertions(+), 32 deletions(-) diff --git a/packages/flutter_tools/lib/src/commands/create.dart b/packages/flutter_tools/lib/src/commands/create.dart index 0c32adfd3b..76b10edf09 100644 --- a/packages/flutter_tools/lib/src/commands/create.dart +++ b/packages/flutter_tools/lib/src/commands/create.dart @@ -162,7 +162,7 @@ class CreateCommand extends FlutterCommand { generatedCount += _renderTemplate('package', dirPath, templateContext); if (argResults['pub']) - await pubGet(context: 'create_pkg', directory: dirPath); + await pubGet(context: PubContext.createPackage, directory: dirPath); final String relativePath = fs.path.relative(dirPath); printStatus('Wrote $generatedCount files.'); @@ -180,7 +180,7 @@ class CreateCommand extends FlutterCommand { generatedCount += _renderTemplate('plugin', dirPath, templateContext); if (argResults['pub']) - await pubGet(context: 'create_plugin', directory: dirPath); + await pubGet(context: PubContext.createPlugin, directory: dirPath); if (android_sdk.androidSdk != null) gradle.updateLocalProperties(projectPath: dirPath); @@ -218,7 +218,7 @@ class CreateCommand extends FlutterCommand { ); if (argResults['pub']) { - await pubGet(context: 'create', directory: appPath); + await pubGet(context: PubContext.create, directory: appPath); injectPlugins(directory: appPath); } diff --git a/packages/flutter_tools/lib/src/commands/packages.dart b/packages/flutter_tools/lib/src/commands/packages.dart index 262db72cea..42302a77c7 100644 --- a/packages/flutter_tools/lib/src/commands/packages.dart +++ b/packages/flutter_tools/lib/src/commands/packages.dart @@ -69,7 +69,7 @@ class PackagesGetCommand extends FlutterCommand { ); } - await pubGet(context: 'get', + await pubGet(context: PubContext.pubGet, directory: target, upgrade: upgrade, offline: argResults['offline'], @@ -102,7 +102,7 @@ class PackagesTestCommand extends FlutterCommand { } @override - Future runCommand() => pub(['run', 'test']..addAll(argResults.rest), context: 'run_test', retry: false); + Future runCommand() => pub(['run', 'test']..addAll(argResults.rest), context: PubContext.runTest, retry: false); } class PackagesPassthroughCommand extends FlutterCommand { diff --git a/packages/flutter_tools/lib/src/commands/update_packages.dart b/packages/flutter_tools/lib/src/commands/update_packages.dart index 7cf7502c07..b3caa8d30b 100644 --- a/packages/flutter_tools/lib/src/commands/update_packages.dart +++ b/packages/flutter_tools/lib/src/commands/update_packages.dart @@ -146,7 +146,7 @@ class UpdatePackagesCommand extends FlutterCommand { fakePackage.createSync(); fakePackage.writeAsStringSync(_generateFakePubspec(dependencies.values)); // First we run "pub upgrade" on this generated package: - await pubGet(context: 'update_packages', directory: temporaryDirectory.path, upgrade: true, checkLastModified: false); + await pubGet(context: PubContext.updatePackages, directory: temporaryDirectory.path, upgrade: true, checkLastModified: false); // Then we run "pub deps --style=compact" on the result. We pipe all the // output to tree.fill(), which parses it so that it can create a graph // of all the dependencies so that we can figure out the transitive @@ -154,7 +154,7 @@ class UpdatePackagesCommand extends FlutterCommand { // each package. await pub( ['deps', '--style=compact'], - context: 'update_pkgs', + context: PubContext.updatePackages, directory: temporaryDirectory.path, filter: tree.fill, retry: false, // errors here are usually fatal since we're not hitting the network @@ -211,7 +211,7 @@ class UpdatePackagesCommand extends FlutterCommand { int count = 0; for (Directory dir in packages) { - await pubGet(context: 'update_packages', directory: dir.path, checkLastModified: false); + await pubGet(context: PubContext.updatePackages, directory: dir.path, checkLastModified: false); count += 1; } diff --git a/packages/flutter_tools/lib/src/commands/upgrade.dart b/packages/flutter_tools/lib/src/commands/upgrade.dart index b78bda97ab..77ac728494 100644 --- a/packages/flutter_tools/lib/src/commands/upgrade.dart +++ b/packages/flutter_tools/lib/src/commands/upgrade.dart @@ -68,7 +68,7 @@ class UpgradeCommand extends FlutterCommand { final String projRoot = findProjectRoot(); if (projRoot != null) { printStatus(''); - await pubGet(context: 'upgrade', directory: projRoot, upgrade: true, checkLastModified: false); + await pubGet(context: PubContext.pubUpgrade, directory: projRoot, upgrade: true, checkLastModified: false); } // Run a doctor check in case system requirements have changed. diff --git a/packages/flutter_tools/lib/src/dart/pub.dart b/packages/flutter_tools/lib/src/dart/pub.dart index 2ec4dc3f3f..10dd247f27 100644 --- a/packages/flutter_tools/lib/src/dart/pub.dart +++ b/packages/flutter_tools/lib/src/dart/pub.dart @@ -16,6 +16,43 @@ import '../cache.dart'; import '../globals.dart'; import 'sdk.dart'; +/// Represents Flutter-specific data that is added to the `PUB_ENVIRONMENT` +/// environment variable and allows understanding the type of requests made to +/// the package site on Flutter's behalf. +// DO NOT update without contacting kevmoo. +// We have server-side tooling that assumes the values are consistent. +class PubContext { + static final RegExp _validContext = new RegExp('[a-z][a-z_]*[a-z]'); + + static final PubContext create = new PubContext._(['create']); + static final PubContext createPackage = new PubContext._(['create_pkg']); + static final PubContext createPlugin = new PubContext._(['create_plugin']); + static final PubContext interactive = new PubContext._(['interactive']); + static final PubContext pubGet = new PubContext._(['get']); + static final PubContext pubUpgrade = new PubContext._(['upgrade']); + static final PubContext runTest = new PubContext._(['run_test']); + + static final PubContext flutterTests = new PubContext._(['flutter_tests']); + static final PubContext updatePackages = new PubContext._(['update_packages']); + + final List _values; + + PubContext._(this._values) { + for (String item in _values) { + if (!_validContext.hasMatch(item)) { + throw new ArgumentError.value( + _values, 'value', 'Must match RegExp ${_validContext.pattern}'); + } + } + } + + static PubContext getVerifyContext(String commandName) => + new PubContext._(['verify', commandName.replaceAll('-', '_')]); + + @override + String toString() => 'PubContext: ${_values.join(':')}'; +} + bool _shouldRunPubGet({ File pubSpecYaml, File dotPackages }) { if (!dotPackages.existsSync()) return true; @@ -30,9 +67,9 @@ bool _shouldRunPubGet({ File pubSpecYaml, File dotPackages }) { } /// [context] provides extra information to package server requests to -/// understand usage. It must match the regular expression `[a-z][a-z_]*[a-z]`. +/// understand usage. Future pubGet({ - @required String context, + @required PubContext context, String directory, bool skipIfAbsent: false, bool upgrade: false, @@ -90,9 +127,9 @@ typedef String MessageFilter(String message); /// `arguments` list) unless `showTraceForErrors` is false. /// /// [context] provides extra information to package server requests to -/// understand usage. It must match the regular expression `[a-z][a-z_]*[a-z]`. +/// understand usage. Future pub(List arguments, { - @required String context, + @required PubContext context, String directory, MessageFilter filter, String failureMessage: 'pub failed', @@ -133,7 +170,7 @@ Future pubInteractively(List arguments, { final int code = await runInteractively( _pubCommand(arguments), workingDirectory: directory, - environment: _createPubEnvironment('interactive'), + environment: _createPubEnvironment(PubContext.interactive), ); if (code != 0) throwToolExit('pub finished with exit code $code', exitCode: code); @@ -147,8 +184,8 @@ List _pubCommand(List arguments) { /// The full environment used when running pub. /// /// [context] provides extra information to package server requests to -/// understand usage. It must match the regular expression `[a-z][a-z_]*[a-z]`. -Map _createPubEnvironment(String context) { +/// understand usage. +Map _createPubEnvironment(PubContext context) { final Map environment = { 'FLUTTER_ROOT': Cache.flutterRoot, _pubEnvironmentKey: _getPubEnvironmentValue(context), @@ -168,15 +205,15 @@ const String _pubEnvironmentKey = 'PUB_ENVIRONMENT'; /// The console environment key used by the pub tool to find the cache directory. const String _pubCacheEnvironmentKey = 'PUB_CACHE'; -final RegExp _validContext = new RegExp('[a-z][a-z_]*[a-z]'); - /// Returns the environment value that should be used when running pub. /// /// Includes any existing environment variable, if one exists. /// /// [context] provides extra information to package server requests to -/// understand usage. It must match the regular expression `[a-z][a-z_]*[a-z]`. -String _getPubEnvironmentValue(String pubContext) { +/// understand usage. +String _getPubEnvironmentValue(PubContext pubContext) { + // DO NOT update this function without contacting kevmoo. + // We have server-side tooling that assumes the values are consistent. final List values = []; final String existing = platform.environment[_pubEnvironmentKey]; @@ -190,11 +227,7 @@ String _getPubEnvironmentValue(String pubContext) { } values.add('flutter_cli'); - - if (!_validContext.hasMatch(pubContext)) { - throw new ArgumentError.value(pubContext, 'pubContext', 'Must match RegExp ${_validContext.pattern}'); - } - values.add('ctx_$pubContext'); + values.addAll(pubContext._values); return values.join(':'); } diff --git a/packages/flutter_tools/lib/src/runner/flutter_command.dart b/packages/flutter_tools/lib/src/runner/flutter_command.dart index 82aa9b4553..5d673b61c4 100644 --- a/packages/flutter_tools/lib/src/runner/flutter_command.dart +++ b/packages/flutter_tools/lib/src/runner/flutter_command.dart @@ -242,7 +242,7 @@ abstract class FlutterCommand extends Command { await cache.updateAll(); if (shouldRunPub) - await pubGet(context: 'verify'); + await pubGet(context: PubContext.getVerifyContext(name)); setupApplicationPackages(); diff --git a/packages/flutter_tools/test/commands/analyze_continuously_test.dart b/packages/flutter_tools/test/commands/analyze_continuously_test.dart index b36ab2eb51..5655d336d8 100644 --- a/packages/flutter_tools/test/commands/analyze_continuously_test.dart +++ b/packages/flutter_tools/test/commands/analyze_continuously_test.dart @@ -32,7 +32,7 @@ void main() { testUsingContext('AnalysisServer success', () async { _createSampleProject(tempDir); - await pubGet(context: 'flutter_tests', directory: tempDir.path); + await pubGet(context: PubContext.flutterTests, directory: tempDir.path); server = new AnalysisServer(dartSdkPath, [tempDir.path]); @@ -52,7 +52,7 @@ void main() { testUsingContext('AnalysisServer errors', () async { _createSampleProject(tempDir, brokenCode: true); - await pubGet(context: 'flutter_tests', directory: tempDir.path); + await pubGet(context: PubContext.flutterTests, directory: tempDir.path); server = new AnalysisServer(dartSdkPath, [tempDir.path]); diff --git a/packages/flutter_tools/test/dart/pub_get_test.dart b/packages/flutter_tools/test/dart/pub_get_test.dart index 82e489b938..355983cef1 100644 --- a/packages/flutter_tools/test/dart/pub_get_test.dart +++ b/packages/flutter_tools/test/dart/pub_get_test.dart @@ -26,7 +26,7 @@ void main() { new FakeAsync().run((FakeAsync time) { expect(processMock.lastPubEnvironmment, isNull); - pubGet(context: 'flutter_tests', checkLastModified: false).then((Null value) { + pubGet(context: PubContext.flutterTests, checkLastModified: false).then((Null value) { error = 'test completed unexpectedly'; }, onError: (dynamic thrownError) { error = 'test failed unexpectedly: $thrownError'; @@ -37,7 +37,7 @@ void main() { 'Running "flutter packages get" in /...\n' 'pub get failed (69) -- attempting retry 1 in 1 second...\n' ); - expect(processMock.lastPubEnvironmment, contains('flutter_cli:ctx_flutter_tests')); + expect(processMock.lastPubEnvironmment, contains('flutter_cli:flutter_tests')); expect(processMock.lastPubCache, isNull); time.elapse(const Duration(milliseconds: 500)); expect(testLogger.statusText, @@ -96,7 +96,7 @@ void main() { MockDirectory.findCache = true; expect(processMock.lastPubEnvironmment, isNull); expect(processMock.lastPubCache, isNull); - pubGet(context: 'flutter_tests', checkLastModified: false).then((Null value) { + pubGet(context: PubContext.flutterTests, checkLastModified: false).then((Null value) { error = 'test completed unexpectedly'; }, onError: (dynamic thrownError) { error = 'test failed unexpectedly: $thrownError'; @@ -122,7 +122,7 @@ void main() { MockDirectory.findCache = false; expect(processMock.lastPubEnvironmment, isNull); expect(processMock.lastPubCache, isNull); - pubGet(context: 'flutter_tests', checkLastModified: false).then((Null value) { + pubGet(context: PubContext.flutterTests, checkLastModified: false).then((Null value) { error = 'test completed unexpectedly'; }, onError: (dynamic thrownError) { error = 'test failed unexpectedly: $thrownError';