pin and auto-install chrome version (flutter/engine#12228)

pin and auto-install chrome version
This commit is contained in:
Yegor
2019-09-12 10:25:37 -07:00
committed by GitHub
parent c9f16e2b1a
commit eb965c8465
5 changed files with 269 additions and 10 deletions

View File

@@ -0,0 +1 @@
695653

View File

@@ -0,0 +1,215 @@
// Copyright 2013 The Flutter 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:io' as io;
import 'package:http/http.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
import 'environment.dart';
void main(List<String> args) async {
Environment.commandLineArguments = args;
try {
await getOrInstallChrome();
} on ChromeInstallerException catch (error) {
io.stderr.writeln(error.toString());
}
}
/// Returns the installation of Chrome, installing it if necessary.
///
/// If [requestedVersion] is null, uses the version specified on the
/// command-line. If not specified on the command-line, uses the version
/// specified in the "chrome.lock" file.
///
/// If [requestedVersion] is not null, installs that version. The value
/// may be "latest" (the latest available build of Chrome), "system"
/// (manually installed Chrome on the current operating system), or an
/// exact build nuber, such as 695653. Build numbers can be found here:
///
/// https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Linux_x64/
Future<ChromeInstallation> getOrInstallChrome({String requestedVersion, StringSink infoLog}) async {
requestedVersion ??= environment.chromeVersion;
infoLog ??= io.stdout;
if (requestedVersion == 'system') {
return ChromeInstallation(
version: 'system',
executable: await _findSystemChromeExecutable(),
);
}
ChromeInstaller installer;
try {
installer = requestedVersion == 'latest'
? await ChromeInstaller.latest()
: ChromeInstaller(version: requestedVersion);
if (installer.isInstalled) {
infoLog.writeln('Installation was skipped because Chrome version ${installer.version} is already installed.');
} else {
infoLog.writeln('Installing Chrome version: ${installer.version}');
await installer.install();
final ChromeInstallation installation = installer.getInstallation();
infoLog.writeln('Installations complete. To launch it run ${installation.executable}');
}
return installer.getInstallation();
} finally {
installer?.close();
}
}
Future<String> _findSystemChromeExecutable() async {
final io.ProcessResult which = await io.Process.run('which', <String>['google-chrome']);
if (which.exitCode != 0) {
throw ChromeInstallerException(
'Failed to locate system Chrome installation.'
);
}
return which.stdout;
}
class ChromeInstallation {
const ChromeInstallation({
@required this.version,
@required this.executable,
});
/// Chrome version.
final String version;
/// Path the the Chrome executable.
final String executable;
}
/// Manages the installation of a particular [version] of Chrome.
class ChromeInstaller {
factory ChromeInstaller({
@required String version,
}) {
if (version == 'system') {
throw ChromeInstallerException(
'Cannot install system version of Chrome. System Chrome must be installed manually.'
);
}
if (version == 'latest') {
throw ChromeInstallerException(
'Expected a concrete Chromer version, but got $version. Maybe use ChromeInstaller.latest()?'
);
}
final io.Directory chromeInstallationDir = io.Directory(
path.join(environment.webUiDartToolDir.path, 'chrome'),
);
final io.Directory versionDir = io.Directory(
path.join(chromeInstallationDir.path, version),
);
return ChromeInstaller._(
version: version,
chromeInstallationDir: chromeInstallationDir,
versionDir: versionDir,
);
}
static Future<ChromeInstaller> latest() async {
final String latestVersion = await fetchLatestChromeVersion();
return ChromeInstaller(version: latestVersion);
}
ChromeInstaller._({
@required this.version,
@required this.chromeInstallationDir,
@required this.versionDir,
});
/// Chrome version managed by this installer.
final String version;
/// HTTP client used to download Chrome.
final Client client = Client();
/// Root directory that contains Chrome versions.
final io.Directory chromeInstallationDir;
/// Installation directory for Chrome of the requested [version].
final io.Directory versionDir;
bool get isInstalled {
return versionDir.existsSync();
}
ChromeInstallation getInstallation() {
if (!isInstalled) {
return null;
}
return ChromeInstallation(
version: version,
executable: path.join(versionDir.path, 'chrome-linux', 'chrome'),
);
}
Future<void> install() async {
if (versionDir.existsSync()) {
versionDir.deleteSync(recursive: true);
}
versionDir.createSync(recursive: true);
final String url = 'https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Linux_x64%2F$version%2Fchrome-linux.zip?alt=media';
final StreamedResponse download = await client.send(Request(
'GET',
Uri.parse(url),
));
final io.File downloadedFile = io.File(path.join(versionDir.path, 'chrome.zip'));
await download.stream.pipe(downloadedFile.openWrite());
final io.ProcessResult unzipResult = await io.Process.run('unzip', <String>[
downloadedFile.path,
'-d',
versionDir.path,
]);
if (unzipResult.exitCode != 0) {
throw ChromeInstallerException(
'Failed to unzip the downloaded Chrome archive ${downloadedFile.path}.\n'
'The unzip process exited with code ${unzipResult.exitCode}.'
);
}
downloadedFile.deleteSync();
}
void close() {
client.close();
}
}
class ChromeInstallerException implements Exception {
ChromeInstallerException(this.message);
final String message;
@override
String toString() => message;
}
/// Fetches the latest available Chrome build version.
Future<String> fetchLatestChromeVersion() async {
final Client client = Client();
try {
final Response response = await client.get('https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Linux_x64%2FLAST_CHANGE?alt=media');
if (response.statusCode != 200) {
throw ChromeInstallerException(
'Failed to fetch latest Chrome version. Server returned status code ${response.statusCode}'
);
}
return response.body;
} finally {
client.close();
}
}

View File

@@ -30,6 +30,15 @@ args.ArgParser get _argParser {
help: 'Pauses the browser before running a test, giving you an '
'opportunity to add breakpoints or inspect loaded code before '
'running the code.',
)
..addOption(
'chrome-version',
help: 'The Chrome version to use while running tests. If the requested '
'version has not been installed, it will be downloaded and installed '
'automatically. A specific Chrome build version number, such as 695653 '
'this use that version of Chrome. Value "latest" will use the latest '
'available build of Chrome, installing it if necessary. Value "system" '
'will use the manually installed version of Chrome on this computer.',
);
}
@@ -63,6 +72,9 @@ class Environment {
}
}
final String pinnedChromeVersion = io.File(pathlib.join(webUiRootDir.path, 'dev', 'chrome.lock')).readAsStringSync().trim();
final String chromeVersion = options['chrome-version'] ?? pinnedChromeVersion;
return Environment._(
self: self,
webUiRootDir: webUiRootDir,
@@ -73,6 +85,7 @@ class Environment {
requestedShards: shards,
isDebug: isDebug,
targets: targets,
chromeVersion: chromeVersion,
);
}
@@ -86,6 +99,7 @@ class Environment {
this.requestedShards,
this.isDebug,
this.targets,
this.chromeVersion,
});
/// The Dart script that's currently running.
@@ -120,6 +134,21 @@ class Environment {
/// Paths to targets to run, e.g. a single test.
final List<String> targets;
/// The Chrome version used for testing.
///
/// The value must be one of:
///
/// - "system", which indicates the Chrome installed on the local machine.
/// - "latest", which indicates the latest available Chrome build specified by:
/// https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Linux_x64%2FLAST_CHANGE?alt=media
/// - A build number pointing at a pre-built version of Chrome available at:
/// https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Linux_x64/
///
/// The "system" Chrome is assumed to be already properly installed and will be invoked directly.
///
/// The "latest" or a specific build number will be downloaded and cached in [webUiDartToolDir].
final String chromeVersion;
/// The "dart" executable file.
String get dartExecutable => pathlib.join(dartSdkDir.path, 'bin', 'dart');
@@ -156,12 +185,3 @@ class Environment {
'.dart_tool',
));
}
String _which(String executable) {
final io.ProcessResult result = io.Process.runSync('which', <String>[executable]);
if (result.exitCode != 0) {
io.stderr.writeln(result.stderr);
io.exit(result.exitCode);
}
return result.stdout;
}

View File

@@ -40,6 +40,7 @@ import 'package:test_core/src/runner/load_exception.dart'; // ignore: implementa
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'
as wip;
import 'chrome_installer.dart';
import 'environment.dart' as env;
/// The port number Chrome exposes for debugging.
@@ -854,6 +855,8 @@ class Chrome extends Browser {
factory Chrome(Uri url, {bool debug = false}) {
var remoteDebuggerCompleter = Completer<Uri>.sync();
return Chrome._(() async {
final ChromeInstallation installation = await getOrInstallChrome(infoLog: _DevNull());
final bool isChromeNoSandbox = Platform.environment['CHROME_NO_SANDBOX'] == 'true';
var dir = createTempDir();
var args = [
@@ -871,7 +874,7 @@ class Chrome extends Browser {
'--remote-debugging-port=$_kChromeDevtoolsPort',
];
var process = await Process.start('google-chrome', args);
final Process process = await Process.start(installation.executable, args);
remoteDebuggerCompleter.complete(getRemoteDebuggerUrl(
Uri.parse('http://localhost:$_kChromeDevtoolsPort')));
@@ -886,3 +889,22 @@ class Chrome extends Browser {
Chrome._(Future<Process> startBrowser(), this.remoteDebuggerUrl)
: super(startBrowser);
}
/// A string sink that swallows all input.
class _DevNull implements StringSink {
@override
void write(Object obj) {
}
@override
void writeAll(Iterable objects, [String separator = ""]) {
}
@override
void writeCharCode(int charCode) {
}
@override
void writeln([Object obj = ""]) {
}
}

View File

@@ -8,6 +8,7 @@ dependencies:
meta: 1.1.7
dev_dependencies:
http: 0.12.0+2
path: 1.6.4
test: 1.6.5
quiver: 2.0.5