Make Pub an interface in the flutter tool (#42257)

This commit is contained in:
Jonah Williams
2019-10-08 14:53:28 -07:00
committed by GitHub
parent fc62666161
commit fde267516b
28 changed files with 433 additions and 223 deletions

View File

@@ -102,7 +102,7 @@ class BuildRunner extends CodeGenerator {
stringBuffer.writeln(' build_daemon: $kSupportedBuildDaemonVersion');
syntheticPubspec.writeAsStringSync(stringBuffer.toString());
await pubGet(
await pub.get(
context: PubContext.pubGet,
directory: generatedDirectory.path,
upgrade: false,

View File

@@ -179,7 +179,7 @@ class WebFs {
// Workaround for https://github.com/flutter/flutter/issues/41681.
final String toolPath = fs.path.join(Cache.flutterRoot, 'packages', 'flutter_tools');
if (!fs.isFileSync(fs.path.join(toolPath, '.packages'))) {
await pubGet(
await pub.get(
context: PubContext.pubGet,
directory: toolPath,
offline: true,

View File

@@ -498,7 +498,7 @@ To edit platform code in an IDE see https://flutter.dev/developing-packages/#edi
templateContext['description'] = description;
generatedCount += _renderTemplate(fs.path.join('module', 'common'), directory, templateContext, overwrite: overwrite);
if (argResults['pub']) {
await pubGet(
await pub.get(
context: PubContext.create,
directory: directory.path,
offline: argResults['offline'],
@@ -517,7 +517,7 @@ To edit platform code in an IDE see https://flutter.dev/developing-packages/#edi
templateContext['description'] = description;
generatedCount += _renderTemplate('package', directory, templateContext, overwrite: overwrite);
if (argResults['pub']) {
await pubGet(
await pub.get(
context: PubContext.createPackage,
directory: directory.path,
offline: argResults['offline'],
@@ -534,7 +534,7 @@ To edit platform code in an IDE see https://flutter.dev/developing-packages/#edi
templateContext['description'] = description;
generatedCount += _renderTemplate('plugin', directory, templateContext, overwrite: overwrite);
if (argResults['pub']) {
await pubGet(
await pub.get(
context: PubContext.createPlugin,
directory: directory.path,
offline: argResults['offline'],
@@ -570,7 +570,7 @@ To edit platform code in an IDE see https://flutter.dev/developing-packages/#edi
}
if (argResults['pub']) {
await pubGet(context: PubContext.create, directory: directory.path, offline: argResults['offline']);
await pub.get(context: PubContext.create, directory: directory.path, offline: argResults['offline']);
await project.ensureReadyForPlatformSpecificTooling(checkProjects: false);
}

View File

@@ -93,7 +93,7 @@ class PackagesGetCommand extends FlutterCommand {
Future<void> _runPubGet(String directory) async {
final Stopwatch pubGetTimer = Stopwatch()..start();
try {
await pubGet(context: PubContext.pubGet,
await pub.get(context: PubContext.pubGet,
directory: directory,
upgrade: upgrade ,
offline: argResults['offline'],
@@ -164,7 +164,7 @@ class PackagesTestCommand extends FlutterCommand {
@override
Future<FlutterCommandResult> runCommand() async {
Cache.releaseLockEarly();
await pub(<String>['run', 'test', ...argResults.rest], context: PubContext.runTest, retry: false);
await pub.batch(<String>['run', 'test', ...argResults.rest], context: PubContext.runTest, retry: false);
return null;
}
}
@@ -205,7 +205,7 @@ class PackagesPublishCommand extends FlutterCommand {
if (argResults['force']) '--force',
];
Cache.releaseLockEarly();
await pubInteractively(<String>['publish', ...args]);
await pub.interactively(<String>['publish', ...args]);
return null;
}
}
@@ -236,7 +236,7 @@ class PackagesForwardCommand extends FlutterCommand {
@override
Future<FlutterCommandResult> runCommand() async {
Cache.releaseLockEarly();
await pubInteractively(<String>[_commandName, ...argResults.rest]);
await pub.interactively(<String>[_commandName, ...argResults.rest]);
return null;
}
@@ -264,7 +264,7 @@ class PackagesPassthroughCommand extends FlutterCommand {
@override
Future<FlutterCommandResult> runCommand() async {
Cache.releaseLockEarly();
await pubInteractively(argResults.rest);
await pub.interactively(argResults.rest);
return null;
}
}

View File

@@ -131,7 +131,7 @@ class TestCommand extends FastFlutterCommand {
'directory (or one of its subdirectories).');
}
if (shouldRunPub) {
await pubGet(context: PubContext.getVerifyContext(name), skipPubspecYamlCheck: true);
await pub.get(context: PubContext.getVerifyContext(name), skipPubspecYamlCheck: true);
}
final bool buildTestAssets = argResults['test-assets'];
final List<String> names = argResults['name'];

View File

@@ -253,7 +253,7 @@ class UpdatePackagesCommand extends FlutterCommand {
fakePackage.createSync();
fakePackage.writeAsStringSync(_generateFakePubspec(dependencies.values));
// First we run "pub upgrade" on this generated package:
await pubGet(
await pub.get(
context: PubContext.updatePackages,
directory: tempDir.path,
upgrade: true,
@@ -264,7 +264,7 @@ class UpdatePackagesCommand extends FlutterCommand {
// of all the dependencies so that we can figure out the transitive
// dependencies later. It also remembers which version was selected for
// each package.
await pub(
await pub.batch(
<String>['deps', '--style=compact'],
context: PubContext.updatePackages,
directory: tempDir.path,
@@ -324,7 +324,7 @@ class UpdatePackagesCommand extends FlutterCommand {
int count = 0;
for (Directory dir in packages) {
await pubGet(context: PubContext.updatePackages, directory: dir.path, checkLastModified: false);
await pub.get(context: PubContext.updatePackages, directory: dir.path, checkLastModified: false);
count += 1;
}

View File

@@ -264,7 +264,7 @@ class UpgradeCommandRunner {
final String projectRoot = findProjectRoot();
if (projectRoot != null) {
printStatus('');
await pubGet(context: PubContext.pubUpgrade, directory: projectRoot, upgrade: true, checkLastModified: false);
await pub.get(context: PubContext.pubUpgrade, directory: projectRoot, upgrade: true, checkLastModified: false);
}
}

View File

@@ -119,7 +119,7 @@ class VersionCommand extends FlutterCommand {
final String projectRoot = findProjectRoot();
if (projectRoot != null) {
printStatus('');
await pubGet(
await pub.get(
context: PubContext.pubUpgrade,
directory: projectRoot,
upgrade: true,

View File

@@ -27,6 +27,7 @@ import 'base/utils.dart';
import 'build_system/build_system.dart';
import 'cache.dart';
import 'compile.dart';
import 'dart/pub.dart';
import 'devfs.dart';
import 'device.dart';
import 'doctor.dart';
@@ -105,6 +106,7 @@ Future<T> runInContext<T>(
MacOSWorkflow: () => const MacOSWorkflow(),
MDnsObservatoryDiscovery: () => MDnsObservatoryDiscovery(),
OperatingSystemUtils: () => OperatingSystemUtils(),
Pub: () => const Pub(),
ProcessInfo: () => ProcessInfo(),
ProcessUtils: () => ProcessUtils(),
Signals: () => Signals(),

View File

@@ -7,6 +7,7 @@ import 'dart:async';
import 'package:meta/meta.dart';
import '../base/common.dart';
import '../base/context.dart';
import '../base/file_system.dart';
import '../base/io.dart' as io;
import '../base/logger.dart';
@@ -19,6 +20,9 @@ import '../reporting/reporting.dart';
import '../runner/flutter_command.dart';
import 'sdk.dart';
/// The [Pub] instance.
Pub get pub => context.get<Pub>();
/// 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.
@@ -77,179 +81,225 @@ bool _shouldRunPubGet({ File pubSpecYaml, File dotPackages }) {
return false;
}
/// [context] provides extra information to package server requests to
/// understand usage.
Future<void> pubGet({
@required PubContext context,
String directory,
bool skipIfAbsent = false,
bool upgrade = false,
bool offline = false,
bool checkLastModified = true,
bool skipPubspecYamlCheck = false,
}) async {
directory ??= fs.currentDirectory.path;
/// A handle for interacting with the pub tool.
abstract class Pub {
/// Create a default [Pub] instance.
const factory Pub() = _DefaultPub;
final File pubSpecYaml = fs.file(fs.path.join(directory, 'pubspec.yaml'));
final File dotPackages = fs.file(fs.path.join(directory, '.packages'));
/// Runs `pub get`.
///
/// [context] provides extra information to package server requests to
/// understand usage.
Future<void> get({
@required PubContext context,
String directory,
bool skipIfAbsent = false,
bool upgrade = false,
bool offline = false,
bool checkLastModified = true,
bool skipPubspecYamlCheck = false,
});
if (!skipPubspecYamlCheck && !pubSpecYaml.existsSync()) {
if (!skipIfAbsent) {
throwToolExit('$directory: no pubspec.yaml found');
/// Runs pub in 'batch' mode.
///
/// forwarding complete lines written by pub to its stdout/stderr streams to
/// the corresponding stream of this process, optionally applying filtering.
/// The pub process will not receive anything on its stdin stream.
///
/// The `--trace` argument is passed to `pub` (by mutating the provided
/// `arguments` list) when `showTraceForErrors` is true, and when `showTraceForErrors`
/// is null/unset, and `isRunningOnBot` is true.
///
/// [context] provides extra information to package server requests to
/// understand usage.
Future<void> batch(
List<String> arguments, {
@required PubContext context,
String directory,
MessageFilter filter,
String failureMessage = 'pub failed',
@required bool retry,
bool showTraceForErrors,
});
/// Runs pub in 'interactive' mode.
///
/// directly piping the stdin stream of this process to that of pub, and the
/// stdout/stderr stream of pub to the corresponding streams of this process.
Future<void> interactively(
List<String> arguments, {
String directory,
});
}
class _DefaultPub implements Pub {
const _DefaultPub();
@override
Future<void> get({
@required PubContext context,
String directory,
bool skipIfAbsent = false,
bool upgrade = false,
bool offline = false,
bool checkLastModified = true,
bool skipPubspecYamlCheck = false,
}) async {
directory ??= fs.currentDirectory.path;
final File pubSpecYaml = fs.file(fs.path.join(directory, 'pubspec.yaml'));
final File dotPackages = fs.file(fs.path.join(directory, '.packages'));
if (!skipPubspecYamlCheck && !pubSpecYaml.existsSync()) {
if (!skipIfAbsent) {
throwToolExit('$directory: no pubspec.yaml found');
}
return;
}
return;
}
if (!checkLastModified || _shouldRunPubGet(pubSpecYaml: pubSpecYaml, dotPackages: dotPackages)) {
final String command = upgrade ? 'upgrade' : 'get';
final Status status = logger.startProgress(
'Running "flutter pub $command" in ${fs.path.basename(directory)}...',
timeout: timeoutConfiguration.slowOperation,
);
final bool verbose = FlutterCommand.current != null && FlutterCommand.current.globalResults['verbose'];
final List<String> args = <String>[
if (verbose) '--verbose' else '--verbosity=warning',
...<String>[command, '--no-precompile'],
if (offline) '--offline',
];
try {
await pub(
args,
context: context,
directory: directory,
filter: _filterOverrideWarnings,
failureMessage: 'pub $command failed',
retry: true,
if (!checkLastModified || _shouldRunPubGet(pubSpecYaml: pubSpecYaml, dotPackages: dotPackages)) {
final String command = upgrade ? 'upgrade' : 'get';
final Status status = logger.startProgress(
'Running "flutter pub $command" in ${fs.path.basename(directory)}...',
timeout: timeoutConfiguration.slowOperation,
);
status.stop();
} catch (exception) {
status.cancel();
rethrow;
final bool verbose = FlutterCommand.current != null && FlutterCommand.current.globalResults['verbose'];
final List<String> args = <String>[
if (verbose) '--verbose' else '--verbosity=warning',
...<String>[command, '--no-precompile'],
if (offline) '--offline',
];
try {
await batch(
args,
context: context,
directory: directory,
filter: _filterOverrideWarnings,
failureMessage: 'pub $command failed',
retry: true,
);
status.stop();
} catch (exception) {
status.cancel();
rethrow;
}
}
if (!dotPackages.existsSync()) {
throwToolExit('$directory: pub did not create .packages file.');
}
if (dotPackages.lastModifiedSync().isBefore(pubSpecYaml.lastModifiedSync())) {
throwToolExit('$directory: pub did not update .packages file '
'(pubspec.yaml timestamp: ${pubSpecYaml.lastModifiedSync()}; '
'.packages timestamp: ${dotPackages.lastModifiedSync()}).');
}
}
if (!dotPackages.existsSync()) {
throwToolExit('$directory: pub did not create .packages file.');
@override
Future<void> batch(
List<String> arguments, {
@required PubContext context,
String directory,
MessageFilter filter,
String failureMessage = 'pub failed',
@required bool retry,
bool showTraceForErrors,
}) async {
showTraceForErrors ??= isRunningOnBot;
bool versionSolvingFailed = false;
String filterWrapper(String line) {
if (line.contains('version solving failed')) {
versionSolvingFailed = true;
}
if (filter == null) {
return line;
}
return filter(line);
}
if (showTraceForErrors) {
arguments.insert(0, '--trace');
}
int attempts = 0;
int duration = 1;
int code;
while (true) {
attempts += 1;
code = await processUtils.stream(
_pubCommand(arguments),
workingDirectory: directory,
mapFunction: filterWrapper,
environment: _createPubEnvironment(context),
);
if (code != 69) { // UNAVAILABLE in https://github.com/dart-lang/pub/blob/master/lib/src/exit_codes.dart
break;
}
versionSolvingFailed = false;
printStatus('$failureMessage ($code) -- attempting retry $attempts in $duration second${ duration == 1 ? "" : "s"}...');
await Future<void>.delayed(Duration(seconds: duration));
if (duration < 64) {
duration *= 2;
}
}
assert(code != null);
String result = 'success';
if (versionSolvingFailed) {
result = 'version-solving-failed';
} else if (code != 0) {
result = 'failure';
}
PubResultEvent(
context: context.toAnalyticsString(),
result: result,
).send();
if (code != 0) {
throwToolExit('$failureMessage ($code)', exitCode: code);
}
}
if (dotPackages.lastModifiedSync().isBefore(pubSpecYaml.lastModifiedSync())) {
throwToolExit('$directory: pub did not update .packages file '
'(pubspec.yaml timestamp: ${pubSpecYaml.lastModifiedSync()}; '
'.packages timestamp: ${dotPackages.lastModifiedSync()}).');
@override
Future<void> interactively(
List<String> arguments, {
String directory,
}) async {
Cache.releaseLockEarly();
final io.Process process = await processUtils.start(
_pubCommand(arguments),
workingDirectory: directory,
environment: _createPubEnvironment(PubContext.interactive),
);
// Pipe the Flutter tool stdin to the pub stdin.
unawaited(process.stdin.addStream(io.stdin));
// Pipe the put stdout and stderr to the tool stdout and stderr.
await Future.wait<dynamic>(<Future<dynamic>>[
io.stdout.addStream(process.stdout),
io.stderr.addStream(process.stderr),
]);
// Wait for pub to exit.
final int code = await process.exitCode;
if (code != 0) {
throwToolExit('pub finished with exit code $code', exitCode: code);
}
}
/// The command used for running pub.
List<String> _pubCommand(List<String> arguments) {
return <String>[sdkBinaryName('pub'), ...arguments];
}
}
typedef MessageFilter = String Function(String message);
/// Runs pub in 'batch' mode, forwarding complete lines written by pub to its
/// stdout/stderr streams to the corresponding stream of this process, optionally
/// applying filtering. The pub process will not receive anything on its stdin stream.
///
/// The `--trace` argument is passed to `pub` (by mutating the provided
/// `arguments` list) when `showTraceForErrors` is true, and when `showTraceForErrors`
/// is null/unset, and `isRunningOnBot` is true.
///
/// [context] provides extra information to package server requests to
/// understand usage.
Future<void> pub(
List<String> arguments, {
@required PubContext context,
String directory,
MessageFilter filter,
String failureMessage = 'pub failed',
@required bool retry,
bool showTraceForErrors,
}) async {
showTraceForErrors ??= isRunningOnBot;
bool versionSolvingFailed = false;
String filterWrapper(String line) {
if (line.contains('version solving failed')) {
versionSolvingFailed = true;
}
if (filter == null) {
return line;
}
return filter(line);
}
if (showTraceForErrors) {
arguments.insert(0, '--trace');
}
int attempts = 0;
int duration = 1;
int code;
while (true) {
attempts += 1;
code = await processUtils.stream(
_pubCommand(arguments),
workingDirectory: directory,
mapFunction: filterWrapper,
environment: _createPubEnvironment(context),
);
if (code != 69) { // UNAVAILABLE in https://github.com/dart-lang/pub/blob/master/lib/src/exit_codes.dart
break;
}
versionSolvingFailed = false;
printStatus('$failureMessage ($code) -- attempting retry $attempts in $duration second${ duration == 1 ? "" : "s"}...');
await Future<void>.delayed(Duration(seconds: duration));
if (duration < 64) {
duration *= 2;
}
}
assert(code != null);
String result = 'success';
if (versionSolvingFailed) {
result = 'version-solving-failed';
} else if (code != 0) {
result = 'failure';
}
PubResultEvent(
context: context.toAnalyticsString(),
result: result,
).send();
if (code != 0) {
throwToolExit('$failureMessage ($code)', exitCode: code);
}
}
/// Runs pub in 'interactive' mode, directly piping the stdin stream of this
/// process to that of pub, and the stdout/stderr stream of pub to the corresponding
/// streams of this process.
Future<void> pubInteractively(
List<String> arguments, {
String directory,
}) async {
Cache.releaseLockEarly();
final io.Process process = await processUtils.start(
_pubCommand(arguments),
workingDirectory: directory,
environment: _createPubEnvironment(PubContext.interactive),
);
// Pipe the Flutter tool stdin to the pub stdin.
unawaited(process.stdin.addStream(io.stdin));
// Pipe the put stdout and stderr to the tool stdout and stderr.
await Future.wait<dynamic>(<Future<dynamic>>[
io.stdout.addStream(process.stdout),
io.stderr.addStream(process.stderr),
]);
// Wait for pub to exit.
final int code = await process.exitCode;
if (code != 0) {
throwToolExit('pub finished with exit code $code', exitCode: code);
}
}
/// The command used for running pub.
List<String> _pubCommand(List<String> arguments) {
return <String>[sdkBinaryName('pub'), ...arguments];
}
/// The full environment used when running pub.
///
/// [context] provides extra information to package server requests to

View File

@@ -538,7 +538,7 @@ abstract class FlutterCommand extends Command<void> {
}
if (shouldRunPub) {
await pubGet(context: PubContext.getVerifyContext(name));
await pub.get(context: PubContext.getVerifyContext(name));
final FlutterProject project = FlutterProject.current();
await project.ensureReadyForPlatformSpecificTooling(checkProjects: true);
}