utils.dart 20.1 KB
Newer Older
1 2 3 4 5 6 7
// Copyright (c) 2016 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:convert';
import 'dart:io';
8
import 'dart:math' as math;
9

10
import 'package:args/args.dart';
11 12
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
13
import 'package:process/process.dart';
14 15 16 17 18
import 'package:stack_trace/stack_trace.dart';

/// Virtual current working directory, which affect functions, such as [exec].
String cwd = Directory.current.path;

19 20 21 22 23 24 25
/// The local engine to use for [flutter] and [evalFlutter], if any.
String get localEngine => const String.fromEnvironment('localEngine');

/// The local engine source path to use if a local engine is used for [flutter]
/// and [evalFlutter].
String get localEngineSrcPath => const String.fromEnvironment('localEngineSrcPath');

26
List<ProcessInfo> _runningProcesses = <ProcessInfo>[];
27
ProcessManager _processManager = const LocalProcessManager();
28 29 30 31

class ProcessInfo {
  ProcessInfo(this.command, this.process);

32
  final DateTime startTime = DateTime.now();
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
  final String command;
  final Process process;

  @override
  String toString() {
    return '''
  command : $command
  started : $startTime
  pid     : ${process.pid}
'''
        .trim();
  }
}

/// Result of a health check for a specific parameter.
class HealthCheckResult {
  HealthCheckResult.success([this.details]) : succeeded = true;
  HealthCheckResult.failure(this.details) : succeeded = false;
  HealthCheckResult.error(dynamic error, dynamic stackTrace)
      : succeeded = false,
        details = 'ERROR: $error${'\n$stackTrace' ?? ''}';

  final bool succeeded;
  final String details;

  @override
  String toString() {
60
    final StringBuffer buf = StringBuffer(succeeded ? 'succeeded' : 'failed');
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    if (details != null && details.trim().isNotEmpty) {
      buf.writeln();
      // Indent details by 4 spaces
      for (String line in details.trim().split('\n')) {
        buf.writeln('    $line');
      }
    }
    return '$buf';
  }
}

class BuildFailedError extends Error {
  BuildFailedError(this.message);

  final String message;

  @override
  String toString() => message;
}

void fail(String message) {
82
  throw BuildFailedError(message);
83 84
}

85 86 87 88 89 90 91 92 93 94 95 96
// Remove the given file or directory.
void rm(FileSystemEntity entity, { bool recursive = false}) {
  if (entity.existsSync()) {
    // This should not be necessary, but it turns out that
    // on Windows it's common for deletions to fail due to
    // bogus (we think) "access denied" errors.
    try {
      entity.deleteSync(recursive: recursive);
    } on FileSystemException catch (error) {
      print('Failed to delete ${entity.path}: $error');
    }
  }
97 98 99 100
}

/// Remove recursively.
void rmTree(FileSystemEntity entity) {
101
  rm(entity, recursive: true);
102 103 104 105
}

List<FileSystemEntity> ls(Directory directory) => directory.listSync();

106
Directory dir(String path) => Directory(path);
107

108
File file(String path) => File(path);
109 110

void copy(File sourceFile, Directory targetDirectory, {String name}) {
111
  final File target = file(
112 113 114 115
      path.join(targetDirectory.path, name ?? path.basename(sourceFile.path)));
  target.writeAsBytesSync(sourceFile.readAsBytesSync());
}

116 117 118 119 120 121 122
void recursiveCopy(Directory source, Directory target) {
  if (!target.existsSync())
    target.createSync();

  for (FileSystemEntity entity in source.listSync(followLinks: false)) {
    final String name = path.basename(entity.path);
    if (entity is Directory)
123
      recursiveCopy(entity, Directory(path.join(target.path, name)));
124
    else if (entity is File) {
125
      final File dest = File(path.join(target.path, name));
126
      dest.writeAsBytesSync(entity.readAsBytesSync());
127 128 129 130 131
      // Preserve executable bit
      final String modes = entity.statSync().modeString();
      if (modes != null && modes.contains('x')) {
        makeExecutable(dest);
      }
132 133 134 135
    }
  }
}

136 137 138 139 140 141
FileSystemEntity move(FileSystemEntity whatToMove,
    {Directory to, String name}) {
  return whatToMove
      .renameSync(path.join(to.path, name ?? path.basename(whatToMove.path)));
}

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
/// Equivalent of `chmod a+x file`
void makeExecutable(File file) {
  // Windows files do not have an executable bit
  if (Platform.isWindows) {
    return;
  }
  final ProcessResult result = _processManager.runSync(<String>[
    'chmod',
    'a+x',
    file.path,
  ]);

  if (result.exitCode != 0) {
    throw FileSystemException(
      'Error making ${file.path} executable.\n'
      '${result.stderr}',
      file.path,
    );
  }
}

163 164 165 166 167 168 169 170 171 172 173 174 175
/// Equivalent of `mkdir directory`.
void mkdir(Directory directory) {
  directory.createSync();
}

/// Equivalent of `mkdir -p directory`.
void mkdirs(Directory directory) {
  directory.createSync(recursive: true);
}

bool exists(FileSystemEntity entity) => entity.existsSync();

void section(String title) {
176 177 178 179 180 181
  title = '╡ ••• $title ••• ╞';
  final String line = '═' * math.max((80 - title.length) ~/ 2, 2);
  String output = '$line$title$line';
  if (output.length == 79)
    output += '═';
  print('\n\n$output\n');
182 183 184 185
}

Future<String> getDartVersion() async {
  // The Dart VM returns the version text to stderr.
186
  final ProcessResult result = _processManager.runSync(<String>[dartBin, '--version']);
187 188 189 190 191 192
  String version = result.stderr.trim();

  // Convert:
  //   Dart VM version: 1.17.0-dev.2.0 (Tue May  3 12:14:52 2016) on "macos_x64"
  // to:
  //   1.17.0-dev.2.0
193
  if (version.contains('('))
194
    version = version.substring(0, version.indexOf('(')).trim();
195
  if (version.contains(':'))
196 197 198 199 200 201 202
    version = version.substring(version.indexOf(':') + 1).trim();

  return version.replaceAll('"', "'");
}

Future<String> getCurrentFlutterRepoCommit() {
  if (!dir('${flutterDirectory.path}/.git').existsSync()) {
203
    return Future<String>.value(null);
204 205
  }

206
  return inDirectory<String>(flutterDirectory, () {
207 208 209 210 211 212
    return eval('git', <String>['rev-parse', 'HEAD']);
  });
}

Future<DateTime> getFlutterRepoCommitTimestamp(String commit) {
  // git show -s --format=%at 4b546df7f0b3858aaaa56c4079e5be1ba91fbb65
213
  return inDirectory<DateTime>(flutterDirectory, () async {
214
    final String unixTimestamp = await eval('git', <String>[
215 216 217 218 219
      'show',
      '-s',
      '--format=%at',
      commit,
    ]);
220
    final int secondsSinceEpoch = int.parse(unixTimestamp);
221
    return DateTime.fromMillisecondsSinceEpoch(secondsSinceEpoch * 1000);
222 223 224
  });
}

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
/// Starts a subprocess.
///
/// The first argument is the full path to the executable to run.
///
/// The second argument is the list of arguments to provide on the command line.
/// This argument can be null, indicating no arguments (same as the empty list).
///
/// The `environment` argument can be provided to configure environment variables
/// that will be made available to the subprocess. The `BOT` environment variable
/// is always set and overrides any value provided in the `environment` argument.
/// The `isBot` argument controls the value of the `BOT` variable. It will either
/// be "true", if `isBot` is true (the default), or "false" if it is false.
///
/// The `BOT` variable is in particular used by the `flutter` tool to determine
/// how verbose to be and whether to enable analytics by default.
///
/// The working directory can be provided using the `workingDirectory` argument.
/// By default it will default to the current working directory (see [cwd]).
///
/// Information regarding the execution of the subprocess is printed to the
/// console.
///
/// The actual process executes asynchronously. A handle to the subprocess is
/// returned in the form of a [Future] that completes to a [Process] object.
249 250 251 252
Future<Process> startProcess(
  String executable,
  List<String> arguments, {
  Map<String, String> environment,
253
  bool isBot = true, // set to false to pretend not to be on a bot (e.g. to test user-facing outputs)
254 255
  String workingDirectory,
}) async {
256
  assert(isBot != null);
257
  final String command = '$executable ${arguments?.join(" ") ?? ""}';
258 259
  final String finalWorkingDirectory = workingDirectory ?? cwd;
  print('\nExecuting: $command in $finalWorkingDirectory');
260
  environment ??= <String, String>{};
261
  environment['BOT'] = isBot ? 'true' : 'false';
262
  final Process process = await _processManager.start(
263
    <String>[executable, ...arguments],
264
    environment: environment,
265
    workingDirectory: finalWorkingDirectory,
266
  );
267
  final ProcessInfo processInfo = ProcessInfo(command, process);
268 269
  _runningProcesses.add(processInfo);

270
  process.exitCode.then<void>((int exitCode) {
271
    print('"$executable" exit code: $exitCode');
272
    _runningProcesses.remove(processInfo);
273 274
  });

275
  return process;
276 277
}

278
Future<void> forceQuitRunningProcesses() async {
279 280 281 282
  if (_runningProcesses.isEmpty)
    return;

  // Give normally quitting processes a chance to report their exit code.
283
  await Future<void>.delayed(const Duration(seconds: 1));
284 285 286

  // Whatever's left, kill it.
  for (ProcessInfo p in _runningProcesses) {
287
    print('Force-quitting process:\n$p');
288 289 290 291 292 293 294 295
    if (!p.process.kill()) {
      print('Failed to force quit process');
    }
  }
  _runningProcesses.clear();
}

/// Executes a command and returns its exit code.
296 297 298 299
Future<int> exec(
  String executable,
  List<String> arguments, {
  Map<String, String> environment,
300
  bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
301
  String workingDirectory,
302
}) async {
303
  final Process process = await startProcess(executable, arguments, environment: environment, workingDirectory: workingDirectory);
304

305 306
  final Completer<void> stdoutDone = Completer<void>();
  final Completer<void> stderrDone = Completer<void>();
307
  process.stdout
308 309
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
310 311 312
      .listen((String line) {
        print('stdout: $line');
      }, onDone: () { stdoutDone.complete(); });
313
  process.stderr
314 315
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
316 317 318
      .listen((String line) {
        print('stderr: $line');
      }, onDone: () { stderrDone.complete(); });
319

320
  await Future.wait<void>(<Future<void>>[stdoutDone.future, stderrDone.future]);
321
  final int exitCode = await process.exitCode;
322 323

  if (exitCode != 0 && !canFail)
324
    fail('Executable "$executable" failed with exit code $exitCode.');
325 326 327 328 329 330

  return exitCode;
}

/// Executes a command and returns its standard output as a String.
///
331
/// For logging purposes, the command's output is also printed out by default.
332 333 334 335
Future<String> eval(
  String executable,
  List<String> arguments, {
  Map<String, String> environment,
336
  bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
337
  String workingDirectory,
338
  StringBuffer stderr, // if not null, the stderr will be written here
339 340
  bool printStdout = true,
  bool printStderr = true,
341
}) async {
342
  final Process process = await startProcess(executable, arguments, environment: environment, workingDirectory: workingDirectory);
343

344
  final StringBuffer output = StringBuffer();
345 346
  final Completer<void> stdoutDone = Completer<void>();
  final Completer<void> stderrDone = Completer<void>();
347
  process.stdout
348 349
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
350
      .listen((String line) {
351 352 353
        if (printStdout) {
          print('stdout: $line');
        }
354 355 356
        output.writeln(line);
      }, onDone: () { stdoutDone.complete(); });
  process.stderr
357 358
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
359
      .listen((String line) {
360 361 362
        if (printStderr) {
          print('stderr: $line');
        }
363
        stderr?.writeln(line);
364 365
      }, onDone: () { stderrDone.complete(); });

366
  await Future.wait<void>(<Future<void>>[stdoutDone.future, stderrDone.future]);
367
  final int exitCode = await process.exitCode;
368 369

  if (exitCode != 0 && !canFail)
370
    fail('Executable "$executable" failed with exit code $exitCode.');
371

372
  return output.toString().trimRight();
373 374
}

375 376
List<String> flutterCommandArgs(String command, List<String> options) {
  return <String>[
377 378 379 380 381
    command,
    if (localEngine != null) ...<String>['--local-engine', localEngine],
    if (localEngineSrcPath != null) ...<String>['--local-engine-src-path', localEngineSrcPath],
    ...options,
  ];
382 383 384 385 386 387 388 389
}

Future<int> flutter(String command, {
  List<String> options = const <String>[],
  bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
  Map<String, String> environment,
}) {
  final List<String> args = flutterCommandArgs(command, options);
390
  return exec(path.join(flutterDirectory.path, 'bin', 'flutter'), args,
391
      canFail: canFail, environment: environment);
392 393
}

394
/// Runs a `flutter` command and returns the standard output as a string.
395
Future<String> evalFlutter(String command, {
396
  List<String> options = const <String>[],
397
  bool canFail = false, // as in, whether failures are ok. False means that they are fatal.
398
  Map<String, String> environment,
399
  StringBuffer stderr, // if not null, the stderr will be written here.
400
}) {
401
  final List<String> args = flutterCommandArgs(command, options);
402
  return eval(path.join(flutterDirectory.path, 'bin', 'flutter'), args,
403
      canFail: canFail, environment: environment, stderr: stderr);
404 405
}

406 407 408 409 410
String get dartBin =>
    path.join(flutterDirectory.path, 'bin', 'cache', 'dart-sdk', 'bin', 'dart');

Future<int> dart(List<String> args) => exec(dartBin, args);

411 412 413 414 415 416 417 418 419 420 421 422 423 424
/// Returns a future that completes with a path suitable for JAVA_HOME
/// or with null, if Java cannot be found.
Future<String> findJavaHome() async {
  final Iterable<String> hits = grep(
    'Java binary at: ',
    from: await evalFlutter('doctor', options: <String>['-v']),
  );
  if (hits.isEmpty)
    return null;
  final String javaBinary = hits.first.split(': ').last;
  // javaBinary == /some/path/to/java/home/bin/java
  return path.dirname(path.dirname(javaBinary));
}

425
Future<T> inDirectory<T>(dynamic directory, Future<T> action()) async {
426
  final String previousCwd = cwd;
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
  try {
    cd(directory);
    return await action();
  } finally {
    cd(previousCwd);
  }
}

void cd(dynamic directory) {
  Directory d;
  if (directory is String) {
    cwd = directory;
    d = dir(directory);
  } else if (directory is Directory) {
    cwd = directory.path;
    d = directory;
  } else {
    throw 'Unsupported type ${directory.runtimeType} of $directory';
  }

  if (!d.existsSync())
    throw 'Cannot cd into directory that does not exist: $directory';
}

451
Directory get flutterDirectory => Directory.current.parent.parent;
452 453

String requireEnvVar(String name) {
454
  final String value = Platform.environment[name];
455

456 457
  if (value == null)
    fail('$name environment variable is missing. Quitting.');
458 459 460 461

  return value;
}

462
T requireConfigProperty<T>(Map<String, dynamic> map, String propertyName) {
463 464
  if (!map.containsKey(propertyName))
    fail('Configuration property not found: $propertyName');
465
  final T result = map[propertyName];
466
  return result;
467 468 469
}

String jsonEncode(dynamic data) {
470
  return const JsonEncoder.withIndent('  ').convert(data) + '\n';
471 472
}

473
Future<void> getFlutter(String revision) async {
474 475 476
  section('Get Flutter!');

  if (exists(flutterDirectory)) {
477
    flutterDirectory.deleteSync(recursive: true);
478 479
  }

480
  await inDirectory<void>(flutterDirectory.parent, () async {
481 482 483
    await exec('git', <String>['clone', 'https://github.com/flutter/flutter.git']);
  });

484
  await inDirectory<void>(flutterDirectory, () async {
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
    await exec('git', <String>['checkout', revision]);
  });

  await flutter('config', options: <String>['--no-analytics']);

  section('flutter doctor');
  await flutter('doctor');

  section('flutter update-packages');
  await flutter('update-packages');
}

void checkNotNull(Object o1,
    [Object o2 = 1,
    Object o3 = 1,
    Object o4 = 1,
    Object o5 = 1,
    Object o6 = 1,
    Object o7 = 1,
    Object o8 = 1,
    Object o9 = 1,
    Object o10 = 1]) {
  if (o1 == null)
    throw 'o1 is null';
  if (o2 == null)
    throw 'o2 is null';
  if (o3 == null)
    throw 'o3 is null';
  if (o4 == null)
    throw 'o4 is null';
  if (o5 == null)
    throw 'o5 is null';
  if (o6 == null)
    throw 'o6 is null';
  if (o7 == null)
    throw 'o7 is null';
  if (o8 == null)
    throw 'o8 is null';
  if (o9 == null)
    throw 'o9 is null';
  if (o10 == null)
    throw 'o10 is null';
}

/// Splits [from] into lines and selects those that contain [pattern].
Iterable<String> grep(Pattern pattern, {@required String from}) {
  return from.split('\n').where((String line) {
    return line.contains(pattern);
  });
}

/// Captures asynchronous stack traces thrown by [callback].
///
/// This is a convenience wrapper around [Chain] optimized for use with
/// `async`/`await`.
///
/// Example:
///
///     try {
///       await captureAsyncStacks(() { /* async things */ });
///     } catch (error, chain) {
///
///     }
548 549
Future<void> runAndCaptureAsyncStacks(Future<void> callback()) {
  final Completer<void> completer = Completer<void>();
550 551 552
  Chain.capture(() async {
    await callback();
    completer.complete();
553
  }, onError: completer.completeError);
554 555
  return completer.future;
}
556

557
bool canRun(String path) => _processManager.canRun(path);
558 559

String extractCloudAuthTokenArg(List<String> rawArgs) {
560
  final ArgParser argParser = ArgParser()..addOption('cloud-auth-token');
561 562 563
  ArgResults args;
  try {
    args = argParser.parse(rawArgs);
564
  } on FormatException catch (error) {
565 566 567 568 569 570 571 572 573 574 575 576 577
    stderr.writeln('${error.message}\n');
    stderr.writeln('Usage:\n');
    stderr.writeln(argParser.usage);
    return null;
  }

  final String token = args['cloud-auth-token'];
  if (token == null) {
    stderr.writeln('Required option --cloud-auth-token not found');
    return null;
  }
  return token;
}
578

579 580 581 582 583
final RegExp _obsRegExp =
  RegExp('An Observatory debugger .* is available at: ');
final RegExp _obsPortRegExp = RegExp('(\\S+:(\\d+)/\\S*)\$');
final RegExp _obsUriRegExp = RegExp('((http|\/\/)[a-zA-Z0-9:/=_\\-\.\\[\\]]+)');

584 585 586
/// Tries to extract a port from the string.
///
/// The `prefix`, if specified, is a regular expression pattern and must not contain groups.
587
/// `prefix` defaults to the RegExp: `An Observatory debugger .* is available at: `.
588
int parseServicePort(String line, {
589
  Pattern prefix,
590
}) {
591
  prefix ??= _obsRegExp;
592 593
  final Iterable<Match> matchesIter = prefix.allMatches(line);
  if (matchesIter.isEmpty) {
594 595
    return null;
  }
596
  final Match prefixMatch = matchesIter.first;
597 598 599 600 601 602 603 604 605 606 607 608 609
  final List<Match> matches =
    _obsPortRegExp.allMatches(line, prefixMatch.end).toList();
  return matches.isEmpty ? null : int.parse(matches[0].group(2));
}

/// Tries to extract a Uri from the string.
///
/// The `prefix`, if specified, is a regular expression pattern and must not contain groups.
/// `prefix` defaults to the RegExp: `An Observatory debugger .* is available at: `.
Uri parseServiceUri(String line, {
  Pattern prefix,
}) {
  prefix ??= _obsRegExp;
610 611
  final Iterable<Match> matchesIter = prefix.allMatches(line);
  if (matchesIter.isEmpty) {
612 613
    return null;
  }
614
  final Match prefixMatch = matchesIter.first;
615 616 617
  final List<Match> matches =
    _obsUriRegExp.allMatches(line, prefixMatch.end).toList();
  return matches.isEmpty ? null : Uri.parse(matches[0].group(0));
618
}
619

620 621 622 623 624 625
/// Checks that the file exists, otherwise throws a [FileSystemException].
void checkFileExists(String file) {
  if (!exists(File(file))) {
    throw FileSystemException('Expected file to exit.', file);
  }
}
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668

void _checkExitCode(int code) {
  if (code != 0) {
    throw Exception(
      'Unexpected exit code = $code!',
    );
  }
}

Future<void> _execAndCheck(String executable, List<String> args) async {
  _checkExitCode(await exec(executable, args));
}

// Measure the CPU/GPU percentage for [duration] while a Flutter app is running
// on an iOS device (e.g., right after a Flutter driver test has finished, which
// doesn't close the Flutter app, and the Flutter app has an indefinite
// animation). The return should have a format like the following json
// ```
// {"gpu_percentage":12.6,"cpu_percentage":18.15}
// ```
Future<Map<String, dynamic>> measureIosCpuGpu({
    Duration duration = const Duration(seconds: 10),
    String deviceId,
}) async {
  await _execAndCheck('pub', <String>[
    'global',
    'activate',
    'gauge',
    '0.1.4',
  ]);

  await _execAndCheck('pub', <String>[
    'global',
    'run',
    'gauge',
    'ioscpugpu',
    'new',
    if (deviceId != null) ...<String>['-w', deviceId],
    '-l',
    '${duration.inMilliseconds}',
  ]);
  return json.decode(file('$cwd/result.json').readAsStringSync());
}