Migrate flutter conductor out of dev/tools and into its own directory (#83313)

* Migrate flutter conductor out of dev/tools and into its own directory

* flesh out documentation

* fix analysis options

* fix integration test
This commit is contained in:
Christopher Fujino
2021-05-25 16:12:53 -07:00
committed by GitHub
parent 36eea758ac
commit 62d00c6d5f
37 changed files with 210 additions and 55 deletions

View File

@@ -34,6 +34,7 @@ function follow_links() (
PROG_NAME="$(follow_links "${BASH_SOURCE[0]}")"
BIN_DIR="$(cd "${PROG_NAME%/*}" ; pwd -P)"
DART_BIN="$BIN_DIR/../../../bin/dart"
REPO_DIR="$BIN_DIR/../../.."
DART_BIN="$REPO_DIR/bin/dart"
"$DART_BIN" --enable-asserts "$BIN_DIR/conductor.dart" "$@"
"$DART_BIN" --enable-asserts "$REPO_DIR/dev/conductor/bin/conductor.dart" "$@"

View File

@@ -1,87 +0,0 @@
// Copyright 2014 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.
// @dart = 2.8
// See: https://github.com/flutter/flutter/wiki/Release-process
import 'dart:io' as io;
import 'package:args/command_runner.dart';
import 'package:dev_tools/candidates.dart';
import 'package:dev_tools/clean.dart';
import 'package:dev_tools/codesign.dart';
import 'package:dev_tools/globals.dart';
import 'package:dev_tools/repository.dart';
import 'package:dev_tools/roll_dev.dart';
import 'package:dev_tools/start.dart';
import 'package:dev_tools/status.dart';
import 'package:dev_tools/stdio.dart';
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:platform/platform.dart';
import 'package:process/process.dart';
Future<void> main(List<String> args) async {
const FileSystem fileSystem = LocalFileSystem();
const ProcessManager processManager = LocalProcessManager();
const Platform platform = LocalPlatform();
final Stdio stdio = VerboseStdio(
stdout: io.stdout,
stderr: io.stderr,
stdin: io.stdin,
);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: localFlutterRoot.parent,
platform: platform,
processManager: processManager,
stdio: stdio,
);
final CommandRunner<void> runner = CommandRunner<void>(
'conductor',
'A tool for coordinating Flutter releases.',
usageLineLength: 80,
);
<Command<void>>[
RollDevCommand(
checkouts: checkouts,
fileSystem: fileSystem,
platform: platform,
stdio: stdio,
),
CodesignCommand(
checkouts: checkouts,
flutterRoot: localFlutterRoot,
),
StatusCommand(
checkouts: checkouts,
),
StartCommand(
checkouts: checkouts,
flutterRoot: localFlutterRoot,
),
CleanCommand(
checkouts: checkouts,
),
CandidatesCommand(
checkouts: checkouts,
flutterRoot: localFlutterRoot,
),
].forEach(runner.addCommand);
if (!assertsEnabled()) {
stdio.printError('The conductor tool must be run with --enable-asserts.');
io.exit(1);
}
try {
await runner.run(args);
} on Exception catch (e, stacktrace) {
stdio.printError('$e\n\n$stacktrace');
io.exit(1);
}
}

View File

@@ -1,102 +0,0 @@
// Copyright 2014 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 'package:args/args.dart';
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import './git.dart';
import './globals.dart' show releaseCandidateBranchRegex;
import './repository.dart';
import './stdio.dart';
import './version.dart';
const String kRemote = 'remote';
class CandidatesCommand extends Command<void> {
CandidatesCommand({
required this.flutterRoot,
required this.checkouts,
}) : git = Git(checkouts.processManager), stdio = checkouts.stdio {
argParser.addOption(
kRemote,
help: 'Which remote name to query for branches.',
defaultsTo: 'upstream',
);
}
final Checkouts checkouts;
final Directory flutterRoot;
final Git git;
final Stdio stdio;
@override
String get name => 'candidates';
@override
String get description => 'List release candidates.';
@override
void run() {
final ArgResults results = argResults!;
git.run(
<String>['fetch', results[kRemote] as String],
'Fetch from remote ${results[kRemote]}',
workingDirectory: flutterRoot.path,
);
final FrameworkRepository framework = HostFrameworkRepository(
checkouts: checkouts,
name: 'framework-for-candidates',
upstreamPath: flutterRoot.path,
);
final Version currentVersion = framework.flutterVersion();
stdio.printStatus('currentVersion = $currentVersion');
final List<String> branches = git.getOutput(
<String>[
'branch',
'--no-color',
'--remotes',
'--list',
'${results[kRemote]}/*',
],
'List all remote branches',
workingDirectory: flutterRoot.path,
).split('\n');
// Pattern for extracting only the branch name via sub-group 1
final RegExp remotePattern = RegExp('${results[kRemote]}\\/(.*)');
for (final String branchName in branches) {
final RegExpMatch? candidateMatch = releaseCandidateBranchRegex.firstMatch(branchName);
if (candidateMatch == null) {
continue;
}
final int currentX = currentVersion.x;
final int currentY = currentVersion.y;
final int currentZ = currentVersion.z;
final int currentM = currentVersion.m ?? 0;
final int x = int.parse(candidateMatch.group(1)!);
final int y = int.parse(candidateMatch.group(2)!);
final int m = int.parse(candidateMatch.group(3)!);
final RegExpMatch? match = remotePattern.firstMatch(branchName);
// If this is not the correct remote
if (match == null) {
continue;
}
if (x < currentVersion.x) {
continue;
}
if (x == currentVersion.x && y < currentVersion.y) {
continue;
}
if (x == currentX && y == currentY && currentZ == 0 && m <= currentM) {
continue;
}
stdio.printStatus(match.group(1)!);
}
}
}

View File

@@ -1,77 +0,0 @@
// Copyright 2014 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.
// @dart = 2.8
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:meta/meta.dart';
import 'package:platform/platform.dart';
import './globals.dart';
import './repository.dart';
import './state.dart';
import './stdio.dart';
const String kYesFlag = 'yes';
const String kStateOption = 'state-file';
/// Command to clean up persistent state file.
///
/// If the release was not completed, this command will abort the release.
class CleanCommand extends Command<void> {
CleanCommand({
@required this.checkouts,
}) : platform = checkouts.platform,
fileSystem = checkouts.fileSystem,
stdio = checkouts.stdio {
final String defaultPath = defaultStateFilePath(platform);
argParser.addFlag(
kYesFlag,
help: 'Override confirmation checks.',
);
argParser.addOption(
kStateOption,
defaultsTo: defaultPath,
help: 'Path to persistent state file. Defaults to $defaultPath',
);
}
final Checkouts checkouts;
final FileSystem fileSystem;
final Platform platform;
final Stdio stdio;
@override
String get name => 'clean';
@override
String get description => 'Cleanup persistent state file. '
'This will abort a work in progress release.';
@override
void run() {
final File stateFile = checkouts.fileSystem.file(argResults[kStateOption]);
if (!stateFile.existsSync()) {
throw ConductorException(
'No persistent state file found at ${stateFile.path}!');
}
if (!(argResults[kYesFlag] as bool)) {
stdio.printStatus(
'Are you sure you want to clean up the persistent state file at\n'
'${stateFile.path} (y/n)?',
);
final String response = stdio.readLineSync();
// Only proceed if the first character of stdin is 'y' or 'Y'
if (response.isEmpty || response[0].toLowerCase() != 'y') {
stdio.printStatus('Aborting clean operation.');
return;
}
}
stdio.printStatus('Deleting persistent state file ${stateFile.path}...');
stateFile.deleteSync();
}
}

View File

@@ -1,394 +0,0 @@
// Copyright 2014 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:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:meta/meta.dart' show visibleForTesting;
import 'package:platform/platform.dart';
import 'package:process/process.dart';
import './globals.dart';
import './repository.dart';
import './stdio.dart';
const List<String> expectedEntitlements = <String>[
'com.apple.security.cs.allow-jit',
'com.apple.security.cs.allow-unsigned-executable-memory',
'com.apple.security.cs.allow-dyld-environment-variables',
'com.apple.security.network.client',
'com.apple.security.network.server',
'com.apple.security.cs.disable-library-validation',
];
const String kVerify = 'verify';
const String kSignatures = 'signatures';
const String kRevision = 'revision';
const String kUpstream = 'upstream';
/// Command to codesign and verify the signatures of cached binaries.
class CodesignCommand extends Command<void> {
CodesignCommand({
required this.checkouts,
required this.flutterRoot,
FrameworkRepository? framework,
}) : fileSystem = checkouts.fileSystem,
platform = checkouts.platform,
stdio = checkouts.stdio,
processManager = checkouts.processManager {
if (framework != null) {
_framework = framework;
}
argParser.addFlag(
kVerify,
help:
'Only verify expected binaries exist and are codesigned with entitlements.',
);
argParser.addFlag(
kSignatures,
defaultsTo: true,
help:
'When off, this command will only verify the existence of binaries, and not their\n'
'signatures or entitlements. Must be used with --verify flag.',
);
argParser.addOption(
kUpstream,
defaultsTo: FrameworkRepository.defaultUpstream,
help: "The git remote URL to use as the Flutter framework's upstream.",
);
argParser.addOption(
kRevision,
help: 'The Flutter framework revision to use.',
);
}
final Checkouts checkouts;
final FileSystem fileSystem;
final Platform platform;
final ProcessManager processManager;
final Stdio stdio;
/// Root directory of the Flutter repository.
final Directory flutterRoot;
FrameworkRepository? _framework;
FrameworkRepository get framework {
return _framework ??= FrameworkRepository.localRepoAsUpstream(
checkouts,
upstreamPath: flutterRoot.path,
);
}
@override
String get name => 'codesign';
@override
String get description =>
'For codesigning and verifying the signatures of engine binaries.';
@override
void run() {
if (!platform.isMacOS) {
throw ConductorException(
'Error! Expected operating system "macos", actual operating system is: '
'"${platform.operatingSystem}"');
}
if (argResults!['verify'] as bool != true) {
throw ConductorException(
'Sorry, but codesigning is not implemented yet. Please pass the '
'--$kVerify flag to verify signatures.');
}
String revision;
if (argResults!.wasParsed(kRevision)) {
stdio.printError(
'Warning! When providing an arbitrary revision, the contents of the cache may not');
stdio.printError(
'match the expected binaries in the conductor tool. It is preferred to check out');
stdio.printError(
'the desired revision and run that version of the conductor.\n');
revision = argResults![kRevision] as String;
} else {
revision = (processManager.runSync(
<String>['git', 'rev-parse', 'HEAD'],
workingDirectory: framework.checkoutDirectory.path,
).stdout as String)
.trim();
assert(revision.isNotEmpty);
}
framework.checkout(revision);
// Ensure artifacts present
framework.runFlutter(<String>['precache', '--android', '--ios', '--macos']);
verifyExist();
if (argResults![kSignatures] as bool) {
verifySignatures();
}
}
/// Binaries that are expected to be codesigned and have entitlements.
///
/// This list should be kept in sync with the actual contents of Flutter's
/// cache.
List<String> get binariesWithEntitlements {
return <String>[
'artifacts/engine/android-arm-profile/darwin-x64/gen_snapshot',
'artifacts/engine/android-arm-release/darwin-x64/gen_snapshot',
'artifacts/engine/android-arm64-profile/darwin-x64/gen_snapshot',
'artifacts/engine/android-arm64-release/darwin-x64/gen_snapshot',
'artifacts/engine/android-x64-profile/darwin-x64/gen_snapshot',
'artifacts/engine/android-x64-release/darwin-x64/gen_snapshot',
'artifacts/engine/darwin-x64-profile/gen_snapshot',
'artifacts/engine/darwin-x64-release/gen_snapshot',
'artifacts/engine/darwin-x64/flutter_tester',
'artifacts/engine/darwin-x64/gen_snapshot',
'artifacts/engine/ios-profile/gen_snapshot_arm64',
'artifacts/engine/ios-profile/gen_snapshot_armv7',
'artifacts/engine/ios-release/gen_snapshot_arm64',
'artifacts/engine/ios-release/gen_snapshot_armv7',
'artifacts/engine/ios/gen_snapshot_arm64',
'artifacts/engine/ios/gen_snapshot_armv7',
'artifacts/libimobiledevice/idevicescreenshot',
'artifacts/libimobiledevice/idevicesyslog',
'artifacts/libimobiledevice/libimobiledevice-1.0.6.dylib',
'artifacts/libplist/libplist-2.0.3.dylib',
'artifacts/openssl/libcrypto.1.1.dylib',
'artifacts/openssl/libssl.1.1.dylib',
'artifacts/usbmuxd/iproxy',
'artifacts/usbmuxd/libusbmuxd-2.0.6.dylib',
'dart-sdk/bin/dart',
'dart-sdk/bin/dartaotruntime',
'dart-sdk/bin/utils/gen_snapshot',
]
.map((String relativePath) =>
fileSystem.path.join(framework.cacheDirectory, relativePath))
.toList();
}
/// Binaries that are only expected to be codesigned.
///
/// This list should be kept in sync with the actual contents of Flutter's
/// cache.
List<String> get binariesWithoutEntitlements {
return <String>[
'artifacts/engine/darwin-x64-profile/FlutterMacOS.framework/Versions/A/FlutterMacOS',
'artifacts/engine/darwin-x64-release/FlutterMacOS.framework/Versions/A/FlutterMacOS',
'artifacts/engine/darwin-x64/FlutterMacOS.framework/Versions/A/FlutterMacOS',
'artifacts/engine/darwin-x64/font-subset',
'artifacts/engine/ios-profile/Flutter.xcframework/ios-armv7_arm64/Flutter.framework/Flutter',
'artifacts/engine/ios-profile/Flutter.xcframework/ios-x86_64-simulator/Flutter.framework/Flutter',
'artifacts/engine/ios-release/Flutter.xcframework/ios-armv7_arm64/Flutter.framework/Flutter',
'artifacts/engine/ios-release/Flutter.xcframework/ios-x86_64-simulator/Flutter.framework/Flutter',
'artifacts/engine/ios/Flutter.xcframework/ios-armv7_arm64/Flutter.framework/Flutter',
'artifacts/engine/ios/Flutter.xcframework/ios-x86_64-simulator/Flutter.framework/Flutter',
'artifacts/ios-deploy/ios-deploy',
]
.map((String relativePath) =>
fileSystem.path.join(framework.cacheDirectory, relativePath))
.toList();
}
/// Verify the existence of all expected binaries in cache.
///
/// This function ignores code signatures and entitlements, and is intended to
/// be run on every commit. It should throw if either new binaries are added
/// to the cache or expected binaries removed. In either case, this class'
/// [binariesWithEntitlements] or [binariesWithoutEntitlements] lists should
/// be updated accordingly.
@visibleForTesting
void verifyExist() {
final Set<String> foundFiles = <String>{};
for (final String binaryPath in findBinaryPaths(framework.cacheDirectory)) {
if (binariesWithEntitlements.contains(binaryPath)) {
foundFiles.add(binaryPath);
} else if (binariesWithoutEntitlements.contains(binaryPath)) {
foundFiles.add(binaryPath);
} else {
throw ConductorException(
'Found unexpected binary in cache: $binaryPath');
}
}
final List<String> allExpectedFiles =
binariesWithEntitlements + binariesWithoutEntitlements;
if (foundFiles.length < allExpectedFiles.length) {
final List<String> unfoundFiles = allExpectedFiles
.where(
(String file) => !foundFiles.contains(file),
)
.toList();
stdio.printError(
'Expected binaries not found in cache:\n\n${unfoundFiles.join('\n')}\n');
stdio.printError(
'If this commit is removing binaries from the cache, this test should be fixed by');
stdio.printError(
'removing the relevant entry from either the `binariesWithEntitlements` or');
stdio.printError(
'`binariesWithoutEntitlements` getters in dev/tools/lib/codesign.dart.');
throw ConductorException('Did not find all expected binaries!');
}
stdio.printStatus('All expected binaries present.');
}
/// Verify code signatures and entitlements of all binaries in the cache.
@visibleForTesting
void verifySignatures() {
final List<String> unsignedBinaries = <String>[];
final List<String> wrongEntitlementBinaries = <String>[];
final List<String> unexpectedBinaries = <String>[];
for (final String binaryPath in findBinaryPaths(framework.cacheDirectory)) {
bool verifySignature = false;
bool verifyEntitlements = false;
if (binariesWithEntitlements.contains(binaryPath)) {
verifySignature = true;
verifyEntitlements = true;
}
if (binariesWithoutEntitlements.contains(binaryPath)) {
verifySignature = true;
}
if (!verifySignature && !verifyEntitlements) {
unexpectedBinaries.add(binaryPath);
stdio.printError('Unexpected binary $binaryPath found in cache!');
continue;
}
stdio.printTrace('Verifying the code signature of $binaryPath');
final io.ProcessResult codeSignResult = processManager.runSync(
<String>[
'codesign',
'-vvv',
binaryPath,
],
);
if (codeSignResult.exitCode != 0) {
unsignedBinaries.add(binaryPath);
stdio.printError(
'File "$binaryPath" does not appear to be codesigned.\n'
'The `codesign` command failed with exit code ${codeSignResult.exitCode}:\n'
'${codeSignResult.stderr}\n');
continue;
}
if (verifyEntitlements) {
stdio.printTrace('Verifying entitlements of $binaryPath');
if (!hasExpectedEntitlements(binaryPath)) {
wrongEntitlementBinaries.add(binaryPath);
}
}
}
// First print all deviations from expectations
if (unsignedBinaries.isNotEmpty) {
stdio.printError('Found ${unsignedBinaries.length} unsigned binaries:');
unsignedBinaries.forEach(print);
}
if (wrongEntitlementBinaries.isNotEmpty) {
stdio.printError(
'Found ${wrongEntitlementBinaries.length} binaries with unexpected entitlements:');
wrongEntitlementBinaries.forEach(print);
}
if (unexpectedBinaries.isNotEmpty) {
stdio.printError(
'Found ${unexpectedBinaries.length} unexpected binaries in the cache:');
unexpectedBinaries.forEach(print);
}
// Finally, exit on any invalid state
if (unsignedBinaries.isNotEmpty) {
throw ConductorException(
'Test failed because unsigned binaries detected.');
}
if (wrongEntitlementBinaries.isNotEmpty) {
throw ConductorException(
'Test failed because files found with the wrong entitlements:\n'
'${wrongEntitlementBinaries.join('\n')}');
}
if (unexpectedBinaries.isNotEmpty) {
throw ConductorException(
'Test failed because unexpected binaries found in the cache.');
}
stdio.printStatus(
'Verified that binaries for commit ${argResults![kRevision] as String} are codesigned and have '
'expected entitlements.');
}
List<String>? _allBinaryPaths;
/// Find every binary file in the given [rootDirectory].
List<String> findBinaryPaths(String rootDirectory) {
if (_allBinaryPaths != null) {
return _allBinaryPaths!;
}
final io.ProcessResult result = processManager.runSync(
<String>[
'find',
rootDirectory,
'-type',
'f',
],
);
final List<String> allFiles = (result.stdout as String)
.split('\n')
.where((String s) => s.isNotEmpty)
.toList();
_allBinaryPaths = allFiles.where(isBinary).toList();
return _allBinaryPaths!;
}
/// Check mime-type of file at [filePath] to determine if it is binary.
bool isBinary(String filePath) {
final io.ProcessResult result = processManager.runSync(
<String>[
'file',
'--mime-type',
'-b', // is binary
filePath,
],
);
return (result.stdout as String).contains('application/x-mach-binary');
}
/// Check if the binary has the expected entitlements.
bool hasExpectedEntitlements(String binaryPath) {
final io.ProcessResult entitlementResult = processManager.runSync(
<String>[
'codesign',
'--display',
'--entitlements',
':-',
binaryPath,
],
);
if (entitlementResult.exitCode != 0) {
stdio.printError(
'The `codesign --entitlements` command failed with exit code ${entitlementResult.exitCode}:\n'
'${entitlementResult.stderr}\n');
return false;
}
bool passes = true;
final String output = entitlementResult.stdout as String;
for (final String entitlement in expectedEntitlements) {
final bool entitlementExpected =
binariesWithEntitlements.contains(binaryPath);
if (output.contains(entitlement) != entitlementExpected) {
stdio.printError(
'File "$binaryPath" ${entitlementExpected ? 'does not have expected' : 'has unexpected'} '
'entitlement $entitlement.');
passes = false;
}
}
return passes;
}
}

View File

@@ -1,81 +0,0 @@
// Copyright 2014 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';
import 'package:process/process.dart';
import './globals.dart';
/// A wrapper around git process calls that can be mocked for unit testing.
class Git {
Git(this.processManager) : assert(processManager != null);
final ProcessManager processManager;
String getOutput(
List<String> args,
String explanation, {
required String workingDirectory,
bool allowFailures = false,
}) {
final ProcessResult result = _run(args, workingDirectory);
if (result.exitCode == 0) {
return stdoutToString(result.stdout);
}
_reportFailureAndExit(args, workingDirectory, result, explanation);
}
int run(
List<String> args,
String explanation, {
bool allowNonZeroExitCode = false,
required String workingDirectory,
}) {
final ProcessResult result = _run(args, workingDirectory);
if (result.exitCode != 0 && !allowNonZeroExitCode) {
_reportFailureAndExit(args, workingDirectory, result, explanation);
}
return result.exitCode;
}
ProcessResult _run(List<String> args, String workingDirectory) {
return processManager.runSync(
<String>['git', ...args],
workingDirectory: workingDirectory,
environment: <String, String>{'GIT_TRACE': '1'},
);
}
Never _reportFailureAndExit(
List<String> args,
String workingDirectory,
ProcessResult result,
String explanation,
) {
final StringBuffer message = StringBuffer();
if (result.exitCode != 0) {
message.writeln(
'Command "git ${args.join(' ')}" failed in directory "$workingDirectory" to '
'$explanation. Git exited with error code ${result.exitCode}.',
);
} else {
message.writeln('Command "git ${args.join(' ')}" failed to $explanation.');
}
if ((result.stdout as String).isNotEmpty)
message.writeln('stdout from git:\n${result.stdout}\n');
if ((result.stderr as String).isNotEmpty)
message.writeln('stderr from git:\n${result.stderr}\n');
throw GitException(message.toString());
}
}
class GitException implements Exception {
GitException(this.message);
final String message;
@override
String toString() => 'Exception: $message';
}

View File

@@ -1,155 +0,0 @@
// Copyright 2014 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 'package:args/args.dart';
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:platform/platform.dart';
const String kUpstreamRemote = 'https://github.com/flutter/flutter.git';
const String gsutilBinary = 'gsutil.py';
const List<String> kReleaseChannels = <String>[
'stable',
'beta',
'dev',
'master',
];
const String kReleaseDocumentationUrl = 'https://github.com/flutter/flutter/wiki/Flutter-Cherrypick-Process';
final RegExp releaseCandidateBranchRegex = RegExp(
r'flutter-(\d+)\.(\d+)-candidate\.(\d+)',
);
/// Cast a dynamic to String and trim.
String stdoutToString(dynamic input) {
final String str = input as String;
return str.trim();
}
class ConductorException implements Exception {
ConductorException(this.message);
final String message;
@override
String toString() => 'Exception: $message';
}
Directory? _flutterRoot;
Directory get localFlutterRoot {
if (_flutterRoot != null) {
return _flutterRoot!;
}
String filePath;
const FileSystem fileSystem = LocalFileSystem();
const Platform platform = LocalPlatform();
// If a test
if (platform.script.scheme == 'data') {
final RegExp pattern = RegExp(
r'(file:\/\/[^"]*[/\\]dev\/tools[/\\][^"]+\.dart)',
multiLine: true,
);
final Match? match =
pattern.firstMatch(Uri.decodeFull(platform.script.path));
if (match == null) {
throw Exception(
'Cannot determine path of script!\n${platform.script.path}',
);
}
filePath = Uri.parse(match.group(1)!).path.replaceAll(r'%20', ' ');
} else {
filePath = platform.script.toFilePath();
}
final String checkoutsDirname = fileSystem.path.normalize(
fileSystem.path.join(
fileSystem.path.dirname(filePath),
'..', // flutter/dev/tools
'..', // flutter/dev
'..', // flutter
),
);
_flutterRoot = fileSystem.directory(checkoutsDirname);
return _flutterRoot!;
}
bool assertsEnabled() {
// Verify asserts enabled
bool assertsEnabled = false;
assert(() {
assertsEnabled = true;
return true;
}());
return assertsEnabled;
}
/// Either return the value from [env] or fall back to [argResults].
///
/// If the key does not exist in either the environment or CLI args, throws a
/// [ConductorException].
///
/// The environment is favored over CLI args since the latter can have a default
/// value, which the environment should be able to override.
String? getValueFromEnvOrArgs(
String name,
ArgResults argResults,
Map<String, String> env, {
bool allowNull = false,
}
) {
final String envName = fromArgToEnvName(name);
if (env[envName] != null ) {
return env[envName];
}
final String? argValue = argResults[name] as String?;
if (argValue != null) {
return argValue;
}
if (allowNull) {
return null;
}
throw ConductorException(
'Expected either the CLI arg --$name or the environment variable $envName '
'to be provided!');
}
/// Return multiple values from the environment or fall back to [argResults].
///
/// Values read from an environment variable are assumed to be comma-delimited.
///
/// If the key does not exist in either the CLI args or environment, throws a
/// [ConductorException].
///
/// The environment is favored over CLI args since the latter can have a default
/// value, which the environment should be able to override.
List<String> getValuesFromEnvOrArgs(
String name,
ArgResults argResults,
Map<String, String> env,
) {
final String envName = fromArgToEnvName(name);
if (env[envName] != null && env[envName] != '') {
return env[envName]!.split(',');
}
final List<String> argValues = argResults[name] as List<String>;
if (argValues != null) {
return argValues;
}
throw ConductorException(
'Expected either the CLI arg --$name or the environment variable $envName '
'to be provided!');
}
/// Translate CLI arg names to env variable names.
///
/// For example, 'state-file' -> 'STATE_FILE'.
String fromArgToEnvName(String argName) {
return argName.toUpperCase().replaceAll(r'-', r'_');
}

View File

@@ -1,8 +0,0 @@
## Flutter Conductor Protocol Buffers
This directory contains [conductor_state.proto](./conductor_state.proto), which
defines the persistent state file the conductor creates. After changes to this
file, you must run the [compile_proto.sh](./compile_proto.sh) script in this
directory, which will re-generate the rest of the Dart files in this directory,
format them, and prepend the license comment from
[license_header.txt](./license_header.txt).

View File

@@ -1,45 +0,0 @@
#!/usr/bin/env bash
# Copyright 2014 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.
# //flutter/dev/tools/lib/proto
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
DARTFMT="$DIR/../../../../bin/cache/dart-sdk/bin/dartfmt"
# Ensure dart-sdk is cached
"$DIR/../../../../bin/dart" --version
if ! type protoc >/dev/null 2>&1; then
PROTOC_LINK='https://grpc.io/docs/protoc-installation/'
echo "Error! \"protoc\" binary required on path."
echo "See $PROTOC_LINK for more information."
exit 1
fi
if ! type dart >/dev/null 2>&1; then
echo "Error! \"dart\" binary required on path."
exit 1
fi
# Pin protoc-gen-dart to pre-nullsafe version.
dart pub global activate protoc_plugin 19.3.1
protoc --dart_out="$DIR" --proto_path="$DIR" "$DIR/conductor_state.proto"
for SOURCE_FILE in $(ls "$DIR"/*.pb*.dart); do
# Format in place file
"$DARTFMT" --overwrite --line-length 120 "$SOURCE_FILE"
# Create temp copy with the license header prepended
cp license_header.txt "${SOURCE_FILE}.tmp"
# Add an extra newline required by analysis (analysis also prevents
# license_header.txt from having the trailing newline)
echo '' >> "${SOURCE_FILE}.tmp"
cat "$SOURCE_FILE" >> "${SOURCE_FILE}.tmp"
# Move temp version (with license) over the original
mv "${SOURCE_FILE}.tmp" "$SOURCE_FILE"
done

View File

@@ -1,556 +0,0 @@
// Copyright 2014 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.
///
// Generated code. Do not modify.
// source: conductor_state.proto
//
// @dart = 2.7
// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields
import 'dart:core' as $core;
import 'package:fixnum/fixnum.dart' as $fixnum;
import 'package:protobuf/protobuf.dart' as $pb;
import 'conductor_state.pbenum.dart';
export 'conductor_state.pbenum.dart';
class Remote extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(
const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'Remote',
package: const $pb.PackageName(
const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'conductor_state'),
createEmptyInstance: create)
..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'name')
..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'url')
..hasRequiredFields = false;
Remote._() : super();
factory Remote({
$core.String name,
$core.String url,
}) {
final _result = create();
if (name != null) {
_result.name = name;
}
if (url != null) {
_result.url = url;
}
return _result;
}
factory Remote.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromBuffer(i, r);
factory Remote.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(i, r);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
Remote clone() => Remote()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
Remote copyWith(void Function(Remote) updates) =>
super.copyWith((message) => updates(message as Remote)) as Remote; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static Remote create() => Remote._();
Remote createEmptyInstance() => create();
static $pb.PbList<Remote> createRepeated() => $pb.PbList<Remote>();
@$core.pragma('dart2js:noInline')
static Remote getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<Remote>(create);
static Remote _defaultInstance;
@$pb.TagNumber(1)
$core.String get name => $_getSZ(0);
@$pb.TagNumber(1)
set name($core.String v) {
$_setString(0, v);
}
@$pb.TagNumber(1)
$core.bool hasName() => $_has(0);
@$pb.TagNumber(1)
void clearName() => clearField(1);
@$pb.TagNumber(2)
$core.String get url => $_getSZ(1);
@$pb.TagNumber(2)
set url($core.String v) {
$_setString(1, v);
}
@$pb.TagNumber(2)
$core.bool hasUrl() => $_has(1);
@$pb.TagNumber(2)
void clearUrl() => clearField(2);
}
class Cherrypick extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(
const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'Cherrypick',
package: const $pb.PackageName(
const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'conductor_state'),
createEmptyInstance: create)
..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'trunkRevision',
protoName: 'trunkRevision')
..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'appliedRevision',
protoName: 'appliedRevision')
..e<CherrypickState>(
3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'state', $pb.PbFieldType.OE,
defaultOrMaker: CherrypickState.PENDING, valueOf: CherrypickState.valueOf, enumValues: CherrypickState.values)
..hasRequiredFields = false;
Cherrypick._() : super();
factory Cherrypick({
$core.String trunkRevision,
$core.String appliedRevision,
CherrypickState state,
}) {
final _result = create();
if (trunkRevision != null) {
_result.trunkRevision = trunkRevision;
}
if (appliedRevision != null) {
_result.appliedRevision = appliedRevision;
}
if (state != null) {
_result.state = state;
}
return _result;
}
factory Cherrypick.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromBuffer(i, r);
factory Cherrypick.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(i, r);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
Cherrypick clone() => Cherrypick()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
Cherrypick copyWith(void Function(Cherrypick) updates) =>
super.copyWith((message) => updates(message as Cherrypick)) as Cherrypick; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static Cherrypick create() => Cherrypick._();
Cherrypick createEmptyInstance() => create();
static $pb.PbList<Cherrypick> createRepeated() => $pb.PbList<Cherrypick>();
@$core.pragma('dart2js:noInline')
static Cherrypick getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<Cherrypick>(create);
static Cherrypick _defaultInstance;
@$pb.TagNumber(1)
$core.String get trunkRevision => $_getSZ(0);
@$pb.TagNumber(1)
set trunkRevision($core.String v) {
$_setString(0, v);
}
@$pb.TagNumber(1)
$core.bool hasTrunkRevision() => $_has(0);
@$pb.TagNumber(1)
void clearTrunkRevision() => clearField(1);
@$pb.TagNumber(2)
$core.String get appliedRevision => $_getSZ(1);
@$pb.TagNumber(2)
set appliedRevision($core.String v) {
$_setString(1, v);
}
@$pb.TagNumber(2)
$core.bool hasAppliedRevision() => $_has(1);
@$pb.TagNumber(2)
void clearAppliedRevision() => clearField(2);
@$pb.TagNumber(3)
CherrypickState get state => $_getN(2);
@$pb.TagNumber(3)
set state(CherrypickState v) {
setField(3, v);
}
@$pb.TagNumber(3)
$core.bool hasState() => $_has(2);
@$pb.TagNumber(3)
void clearState() => clearField(3);
}
class Repository extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(
const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'Repository',
package: const $pb.PackageName(
const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'conductor_state'),
createEmptyInstance: create)
..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'candidateBranch',
protoName: 'candidateBranch')
..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'startingGitHead',
protoName: 'startingGitHead')
..aOS(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'currentGitHead',
protoName: 'currentGitHead')
..aOS(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'checkoutPath',
protoName: 'checkoutPath')
..aOM<Remote>(5, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'upstream',
subBuilder: Remote.create)
..aOM<Remote>(6, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'mirror',
subBuilder: Remote.create)
..pc<Cherrypick>(
7, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'cherrypicks', $pb.PbFieldType.PM,
subBuilder: Cherrypick.create)
..aOS(8, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'dartRevision',
protoName: 'dartRevision')
..hasRequiredFields = false;
Repository._() : super();
factory Repository({
$core.String candidateBranch,
$core.String startingGitHead,
$core.String currentGitHead,
$core.String checkoutPath,
Remote upstream,
Remote mirror,
$core.Iterable<Cherrypick> cherrypicks,
$core.String dartRevision,
}) {
final _result = create();
if (candidateBranch != null) {
_result.candidateBranch = candidateBranch;
}
if (startingGitHead != null) {
_result.startingGitHead = startingGitHead;
}
if (currentGitHead != null) {
_result.currentGitHead = currentGitHead;
}
if (checkoutPath != null) {
_result.checkoutPath = checkoutPath;
}
if (upstream != null) {
_result.upstream = upstream;
}
if (mirror != null) {
_result.mirror = mirror;
}
if (cherrypicks != null) {
_result.cherrypicks.addAll(cherrypicks);
}
if (dartRevision != null) {
_result.dartRevision = dartRevision;
}
return _result;
}
factory Repository.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromBuffer(i, r);
factory Repository.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(i, r);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
Repository clone() => Repository()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
Repository copyWith(void Function(Repository) updates) =>
super.copyWith((message) => updates(message as Repository)) as Repository; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static Repository create() => Repository._();
Repository createEmptyInstance() => create();
static $pb.PbList<Repository> createRepeated() => $pb.PbList<Repository>();
@$core.pragma('dart2js:noInline')
static Repository getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<Repository>(create);
static Repository _defaultInstance;
@$pb.TagNumber(1)
$core.String get candidateBranch => $_getSZ(0);
@$pb.TagNumber(1)
set candidateBranch($core.String v) {
$_setString(0, v);
}
@$pb.TagNumber(1)
$core.bool hasCandidateBranch() => $_has(0);
@$pb.TagNumber(1)
void clearCandidateBranch() => clearField(1);
@$pb.TagNumber(2)
$core.String get startingGitHead => $_getSZ(1);
@$pb.TagNumber(2)
set startingGitHead($core.String v) {
$_setString(1, v);
}
@$pb.TagNumber(2)
$core.bool hasStartingGitHead() => $_has(1);
@$pb.TagNumber(2)
void clearStartingGitHead() => clearField(2);
@$pb.TagNumber(3)
$core.String get currentGitHead => $_getSZ(2);
@$pb.TagNumber(3)
set currentGitHead($core.String v) {
$_setString(2, v);
}
@$pb.TagNumber(3)
$core.bool hasCurrentGitHead() => $_has(2);
@$pb.TagNumber(3)
void clearCurrentGitHead() => clearField(3);
@$pb.TagNumber(4)
$core.String get checkoutPath => $_getSZ(3);
@$pb.TagNumber(4)
set checkoutPath($core.String v) {
$_setString(3, v);
}
@$pb.TagNumber(4)
$core.bool hasCheckoutPath() => $_has(3);
@$pb.TagNumber(4)
void clearCheckoutPath() => clearField(4);
@$pb.TagNumber(5)
Remote get upstream => $_getN(4);
@$pb.TagNumber(5)
set upstream(Remote v) {
setField(5, v);
}
@$pb.TagNumber(5)
$core.bool hasUpstream() => $_has(4);
@$pb.TagNumber(5)
void clearUpstream() => clearField(5);
@$pb.TagNumber(5)
Remote ensureUpstream() => $_ensure(4);
@$pb.TagNumber(6)
Remote get mirror => $_getN(5);
@$pb.TagNumber(6)
set mirror(Remote v) {
setField(6, v);
}
@$pb.TagNumber(6)
$core.bool hasMirror() => $_has(5);
@$pb.TagNumber(6)
void clearMirror() => clearField(6);
@$pb.TagNumber(6)
Remote ensureMirror() => $_ensure(5);
@$pb.TagNumber(7)
$core.List<Cherrypick> get cherrypicks => $_getList(6);
@$pb.TagNumber(8)
$core.String get dartRevision => $_getSZ(7);
@$pb.TagNumber(8)
set dartRevision($core.String v) {
$_setString(7, v);
}
@$pb.TagNumber(8)
$core.bool hasDartRevision() => $_has(7);
@$pb.TagNumber(8)
void clearDartRevision() => clearField(8);
}
class ConductorState extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(
const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'ConductorState',
package: const $pb.PackageName(
const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'conductor_state'),
createEmptyInstance: create)
..aOS(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'releaseChannel',
protoName: 'releaseChannel')
..aOS(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'releaseVersion',
protoName: 'releaseVersion')
..aOM<Repository>(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'engine',
subBuilder: Repository.create)
..aOM<Repository>(5, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'framework',
subBuilder: Repository.create)
..aInt64(6, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'createdDate',
protoName: 'createdDate')
..aInt64(7, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'lastUpdatedDate',
protoName: 'lastUpdatedDate')
..pPS(8, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'logs')
..e<ReleasePhase>(
9, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'lastPhase', $pb.PbFieldType.OE,
protoName: 'lastPhase',
defaultOrMaker: ReleasePhase.INITIALIZE,
valueOf: ReleasePhase.valueOf,
enumValues: ReleasePhase.values)
..aOS(10, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'conductorVersion')
..hasRequiredFields = false;
ConductorState._() : super();
factory ConductorState({
$core.String releaseChannel,
$core.String releaseVersion,
Repository engine,
Repository framework,
$fixnum.Int64 createdDate,
$fixnum.Int64 lastUpdatedDate,
$core.Iterable<$core.String> logs,
ReleasePhase lastPhase,
$core.String conductorVersion,
}) {
final _result = create();
if (releaseChannel != null) {
_result.releaseChannel = releaseChannel;
}
if (releaseVersion != null) {
_result.releaseVersion = releaseVersion;
}
if (engine != null) {
_result.engine = engine;
}
if (framework != null) {
_result.framework = framework;
}
if (createdDate != null) {
_result.createdDate = createdDate;
}
if (lastUpdatedDate != null) {
_result.lastUpdatedDate = lastUpdatedDate;
}
if (logs != null) {
_result.logs.addAll(logs);
}
if (lastPhase != null) {
_result.lastPhase = lastPhase;
}
if (conductorVersion != null) {
_result.conductorVersion = conductorVersion;
}
return _result;
}
factory ConductorState.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromBuffer(i, r);
factory ConductorState.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(i, r);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
ConductorState clone() => ConductorState()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
ConductorState copyWith(void Function(ConductorState) updates) =>
super.copyWith((message) => updates(message as ConductorState))
as ConductorState; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static ConductorState create() => ConductorState._();
ConductorState createEmptyInstance() => create();
static $pb.PbList<ConductorState> createRepeated() => $pb.PbList<ConductorState>();
@$core.pragma('dart2js:noInline')
static ConductorState getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<ConductorState>(create);
static ConductorState _defaultInstance;
@$pb.TagNumber(1)
$core.String get releaseChannel => $_getSZ(0);
@$pb.TagNumber(1)
set releaseChannel($core.String v) {
$_setString(0, v);
}
@$pb.TagNumber(1)
$core.bool hasReleaseChannel() => $_has(0);
@$pb.TagNumber(1)
void clearReleaseChannel() => clearField(1);
@$pb.TagNumber(2)
$core.String get releaseVersion => $_getSZ(1);
@$pb.TagNumber(2)
set releaseVersion($core.String v) {
$_setString(1, v);
}
@$pb.TagNumber(2)
$core.bool hasReleaseVersion() => $_has(1);
@$pb.TagNumber(2)
void clearReleaseVersion() => clearField(2);
@$pb.TagNumber(4)
Repository get engine => $_getN(2);
@$pb.TagNumber(4)
set engine(Repository v) {
setField(4, v);
}
@$pb.TagNumber(4)
$core.bool hasEngine() => $_has(2);
@$pb.TagNumber(4)
void clearEngine() => clearField(4);
@$pb.TagNumber(4)
Repository ensureEngine() => $_ensure(2);
@$pb.TagNumber(5)
Repository get framework => $_getN(3);
@$pb.TagNumber(5)
set framework(Repository v) {
setField(5, v);
}
@$pb.TagNumber(5)
$core.bool hasFramework() => $_has(3);
@$pb.TagNumber(5)
void clearFramework() => clearField(5);
@$pb.TagNumber(5)
Repository ensureFramework() => $_ensure(3);
@$pb.TagNumber(6)
$fixnum.Int64 get createdDate => $_getI64(4);
@$pb.TagNumber(6)
set createdDate($fixnum.Int64 v) {
$_setInt64(4, v);
}
@$pb.TagNumber(6)
$core.bool hasCreatedDate() => $_has(4);
@$pb.TagNumber(6)
void clearCreatedDate() => clearField(6);
@$pb.TagNumber(7)
$fixnum.Int64 get lastUpdatedDate => $_getI64(5);
@$pb.TagNumber(7)
set lastUpdatedDate($fixnum.Int64 v) {
$_setInt64(5, v);
}
@$pb.TagNumber(7)
$core.bool hasLastUpdatedDate() => $_has(5);
@$pb.TagNumber(7)
void clearLastUpdatedDate() => clearField(7);
@$pb.TagNumber(8)
$core.List<$core.String> get logs => $_getList(6);
@$pb.TagNumber(9)
ReleasePhase get lastPhase => $_getN(7);
@$pb.TagNumber(9)
set lastPhase(ReleasePhase v) {
setField(9, v);
}
@$pb.TagNumber(9)
$core.bool hasLastPhase() => $_has(7);
@$pb.TagNumber(9)
void clearLastPhase() => clearField(9);
@$pb.TagNumber(10)
$core.String get conductorVersion => $_getSZ(8);
@$pb.TagNumber(10)
set conductorVersion($core.String v) {
$_setString(8, v);
}
@$pb.TagNumber(10)
$core.bool hasConductorVersion() => $_has(8);
@$pb.TagNumber(10)
void clearConductorVersion() => clearField(10);
}

View File

@@ -1,69 +0,0 @@
// Copyright 2014 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.
///
// Generated code. Do not modify.
// source: conductor_state.proto
//
// @dart = 2.7
// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields
// ignore_for_file: UNDEFINED_SHOWN_NAME
import 'dart:core' as $core;
import 'package:protobuf/protobuf.dart' as $pb;
class ReleasePhase extends $pb.ProtobufEnum {
static const ReleasePhase INITIALIZE =
ReleasePhase._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'INITIALIZE');
static const ReleasePhase APPLY_ENGINE_CHERRYPICKS =
ReleasePhase._(1, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'APPLY_ENGINE_CHERRYPICKS');
static const ReleasePhase CODESIGN_ENGINE_BINARIES =
ReleasePhase._(2, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'CODESIGN_ENGINE_BINARIES');
static const ReleasePhase APPLY_FRAMEWORK_CHERRYPICKS = ReleasePhase._(
3, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'APPLY_FRAMEWORK_CHERRYPICKS');
static const ReleasePhase PUBLISH_VERSION =
ReleasePhase._(4, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PUBLISH_VERSION');
static const ReleasePhase PUBLISH_CHANNEL =
ReleasePhase._(5, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PUBLISH_CHANNEL');
static const ReleasePhase VERIFY_RELEASE =
ReleasePhase._(6, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'VERIFY_RELEASE');
static const $core.List<ReleasePhase> values = <ReleasePhase>[
INITIALIZE,
APPLY_ENGINE_CHERRYPICKS,
CODESIGN_ENGINE_BINARIES,
APPLY_FRAMEWORK_CHERRYPICKS,
PUBLISH_VERSION,
PUBLISH_CHANNEL,
VERIFY_RELEASE,
];
static final $core.Map<$core.int, ReleasePhase> _byValue = $pb.ProtobufEnum.initByValue(values);
static ReleasePhase valueOf($core.int value) => _byValue[value];
const ReleasePhase._($core.int v, $core.String n) : super(v, n);
}
class CherrypickState extends $pb.ProtobufEnum {
static const CherrypickState PENDING =
CherrypickState._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PENDING');
static const CherrypickState PENDING_WITH_CONFLICT =
CherrypickState._(1, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PENDING_WITH_CONFLICT');
static const CherrypickState COMPLETED =
CherrypickState._(2, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'COMPLETED');
static const CherrypickState ABANDONED =
CherrypickState._(3, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ABANDONED');
static const $core.List<CherrypickState> values = <CherrypickState>[
PENDING,
PENDING_WITH_CONFLICT,
COMPLETED,
ABANDONED,
];
static final $core.Map<$core.int, CherrypickState> _byValue = $pb.ProtobufEnum.initByValue(values);
static CherrypickState valueOf($core.int value) => _byValue[value];
const CherrypickState._($core.int v, $core.String n) : super(v, n);
}

View File

@@ -1,108 +0,0 @@
// Copyright 2014 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.
///
// Generated code. Do not modify.
// source: conductor_state.proto
//
// @dart = 2.7
// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package
import 'dart:core' as $core;
import 'dart:convert' as $convert;
import 'dart:typed_data' as $typed_data;
@$core.Deprecated('Use releasePhaseDescriptor instead')
const ReleasePhase$json = const {
'1': 'ReleasePhase',
'2': const [
const {'1': 'INITIALIZE', '2': 0},
const {'1': 'APPLY_ENGINE_CHERRYPICKS', '2': 1},
const {'1': 'CODESIGN_ENGINE_BINARIES', '2': 2},
const {'1': 'APPLY_FRAMEWORK_CHERRYPICKS', '2': 3},
const {'1': 'PUBLISH_VERSION', '2': 4},
const {'1': 'PUBLISH_CHANNEL', '2': 5},
const {'1': 'VERIFY_RELEASE', '2': 6},
],
};
/// Descriptor for `ReleasePhase`. Decode as a `google.protobuf.EnumDescriptorProto`.
final $typed_data.Uint8List releasePhaseDescriptor = $convert.base64Decode(
'CgxSZWxlYXNlUGhhc2USDgoKSU5JVElBTElaRRAAEhwKGEFQUExZX0VOR0lORV9DSEVSUllQSUNLUxABEhwKGENPREVTSUdOX0VOR0lORV9CSU5BUklFUxACEh8KG0FQUExZX0ZSQU1FV09SS19DSEVSUllQSUNLUxADEhMKD1BVQkxJU0hfVkVSU0lPThAEEhMKD1BVQkxJU0hfQ0hBTk5FTBAFEhIKDlZFUklGWV9SRUxFQVNFEAY=');
@$core.Deprecated('Use cherrypickStateDescriptor instead')
const CherrypickState$json = const {
'1': 'CherrypickState',
'2': const [
const {'1': 'PENDING', '2': 0},
const {'1': 'PENDING_WITH_CONFLICT', '2': 1},
const {'1': 'COMPLETED', '2': 2},
const {'1': 'ABANDONED', '2': 3},
],
};
/// Descriptor for `CherrypickState`. Decode as a `google.protobuf.EnumDescriptorProto`.
final $typed_data.Uint8List cherrypickStateDescriptor = $convert.base64Decode(
'Cg9DaGVycnlwaWNrU3RhdGUSCwoHUEVORElORxAAEhkKFVBFTkRJTkdfV0lUSF9DT05GTElDVBABEg0KCUNPTVBMRVRFRBACEg0KCUFCQU5ET05FRBAD');
@$core.Deprecated('Use remoteDescriptor instead')
const Remote$json = const {
'1': 'Remote',
'2': const [
const {'1': 'name', '3': 1, '4': 1, '5': 9, '10': 'name'},
const {'1': 'url', '3': 2, '4': 1, '5': 9, '10': 'url'},
],
};
/// Descriptor for `Remote`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List remoteDescriptor =
$convert.base64Decode('CgZSZW1vdGUSEgoEbmFtZRgBIAEoCVIEbmFtZRIQCgN1cmwYAiABKAlSA3VybA==');
@$core.Deprecated('Use cherrypickDescriptor instead')
const Cherrypick$json = const {
'1': 'Cherrypick',
'2': const [
const {'1': 'trunkRevision', '3': 1, '4': 1, '5': 9, '10': 'trunkRevision'},
const {'1': 'appliedRevision', '3': 2, '4': 1, '5': 9, '10': 'appliedRevision'},
const {'1': 'state', '3': 3, '4': 1, '5': 14, '6': '.conductor_state.CherrypickState', '10': 'state'},
],
};
/// Descriptor for `Cherrypick`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List cherrypickDescriptor = $convert.base64Decode(
'CgpDaGVycnlwaWNrEiQKDXRydW5rUmV2aXNpb24YASABKAlSDXRydW5rUmV2aXNpb24SKAoPYXBwbGllZFJldmlzaW9uGAIgASgJUg9hcHBsaWVkUmV2aXNpb24SNgoFc3RhdGUYAyABKA4yIC5jb25kdWN0b3Jfc3RhdGUuQ2hlcnJ5cGlja1N0YXRlUgVzdGF0ZQ==');
@$core.Deprecated('Use repositoryDescriptor instead')
const Repository$json = const {
'1': 'Repository',
'2': const [
const {'1': 'candidateBranch', '3': 1, '4': 1, '5': 9, '10': 'candidateBranch'},
const {'1': 'startingGitHead', '3': 2, '4': 1, '5': 9, '10': 'startingGitHead'},
const {'1': 'currentGitHead', '3': 3, '4': 1, '5': 9, '10': 'currentGitHead'},
const {'1': 'checkoutPath', '3': 4, '4': 1, '5': 9, '10': 'checkoutPath'},
const {'1': 'upstream', '3': 5, '4': 1, '5': 11, '6': '.conductor_state.Remote', '10': 'upstream'},
const {'1': 'mirror', '3': 6, '4': 1, '5': 11, '6': '.conductor_state.Remote', '10': 'mirror'},
const {'1': 'cherrypicks', '3': 7, '4': 3, '5': 11, '6': '.conductor_state.Cherrypick', '10': 'cherrypicks'},
const {'1': 'dartRevision', '3': 8, '4': 1, '5': 9, '10': 'dartRevision'},
],
};
/// Descriptor for `Repository`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List repositoryDescriptor = $convert.base64Decode(
'CgpSZXBvc2l0b3J5EigKD2NhbmRpZGF0ZUJyYW5jaBgBIAEoCVIPY2FuZGlkYXRlQnJhbmNoEigKD3N0YXJ0aW5nR2l0SGVhZBgCIAEoCVIPc3RhcnRpbmdHaXRIZWFkEiYKDmN1cnJlbnRHaXRIZWFkGAMgASgJUg5jdXJyZW50R2l0SGVhZBIiCgxjaGVja291dFBhdGgYBCABKAlSDGNoZWNrb3V0UGF0aBIzCgh1cHN0cmVhbRgFIAEoCzIXLmNvbmR1Y3Rvcl9zdGF0ZS5SZW1vdGVSCHVwc3RyZWFtEi8KBm1pcnJvchgGIAEoCzIXLmNvbmR1Y3Rvcl9zdGF0ZS5SZW1vdGVSBm1pcnJvchI9CgtjaGVycnlwaWNrcxgHIAMoCzIbLmNvbmR1Y3Rvcl9zdGF0ZS5DaGVycnlwaWNrUgtjaGVycnlwaWNrcxIiCgxkYXJ0UmV2aXNpb24YCCABKAlSDGRhcnRSZXZpc2lvbg==');
@$core.Deprecated('Use conductorStateDescriptor instead')
const ConductorState$json = const {
'1': 'ConductorState',
'2': const [
const {'1': 'releaseChannel', '3': 1, '4': 1, '5': 9, '10': 'releaseChannel'},
const {'1': 'releaseVersion', '3': 2, '4': 1, '5': 9, '10': 'releaseVersion'},
const {'1': 'engine', '3': 4, '4': 1, '5': 11, '6': '.conductor_state.Repository', '10': 'engine'},
const {'1': 'framework', '3': 5, '4': 1, '5': 11, '6': '.conductor_state.Repository', '10': 'framework'},
const {'1': 'createdDate', '3': 6, '4': 1, '5': 3, '10': 'createdDate'},
const {'1': 'lastUpdatedDate', '3': 7, '4': 1, '5': 3, '10': 'lastUpdatedDate'},
const {'1': 'logs', '3': 8, '4': 3, '5': 9, '10': 'logs'},
const {'1': 'lastPhase', '3': 9, '4': 1, '5': 14, '6': '.conductor_state.ReleasePhase', '10': 'lastPhase'},
const {'1': 'conductor_version', '3': 10, '4': 1, '5': 9, '10': 'conductorVersion'},
],
};
/// Descriptor for `ConductorState`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List conductorStateDescriptor = $convert.base64Decode(
'Cg5Db25kdWN0b3JTdGF0ZRImCg5yZWxlYXNlQ2hhbm5lbBgBIAEoCVIOcmVsZWFzZUNoYW5uZWwSJgoOcmVsZWFzZVZlcnNpb24YAiABKAlSDnJlbGVhc2VWZXJzaW9uEjMKBmVuZ2luZRgEIAEoCzIbLmNvbmR1Y3Rvcl9zdGF0ZS5SZXBvc2l0b3J5UgZlbmdpbmUSOQoJZnJhbWV3b3JrGAUgASgLMhsuY29uZHVjdG9yX3N0YXRlLlJlcG9zaXRvcnlSCWZyYW1ld29yaxIgCgtjcmVhdGVkRGF0ZRgGIAEoA1ILY3JlYXRlZERhdGUSKAoPbGFzdFVwZGF0ZWREYXRlGAcgASgDUg9sYXN0VXBkYXRlZERhdGUSEgoEbG9ncxgIIAMoCVIEbG9ncxI7CglsYXN0UGhhc2UYCSABKA4yHS5jb25kdWN0b3Jfc3RhdGUuUmVsZWFzZVBoYXNlUglsYXN0UGhhc2USKwoRY29uZHVjdG9yX3ZlcnNpb24YCiABKAlSEGNvbmR1Y3RvclZlcnNpb24=');

View File

@@ -1,12 +0,0 @@
// Copyright 2014 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.
///
// Generated code. Do not modify.
// source: conductor_state.proto
//
// @dart = 2.7
// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package
export 'conductor_state.pb.dart';

View File

@@ -1,106 +0,0 @@
syntax = "proto3";
package conductor_state;
// A git remote
message Remote {
string name = 1;
string url = 2;
}
enum ReleasePhase {
// Release was started with `conductor start` and repositories cloned.
INITIALIZE = 0;
APPLY_ENGINE_CHERRYPICKS = 1;
CODESIGN_ENGINE_BINARIES = 2;
APPLY_FRAMEWORK_CHERRYPICKS = 3;
// Git tag applied to framework RC branch HEAD and pushed upstream.
PUBLISH_VERSION = 4;
// RC branch HEAD pushed to upstream release branch.
//
// For example, flutter-1.2-candidate.3 -> upstream/beta
PUBLISH_CHANNEL = 5;
// Package artifacts verified to exist on cloud storage.
VERIFY_RELEASE = 6;
}
enum CherrypickState {
// The cherrypick has not yet been applied.
PENDING = 0;
// The cherrypick has not been applied and will require manual resolution.
PENDING_WITH_CONFLICT = 1;
// The cherrypick has been successfully applied to the local checkout.
//
// This state requires Cherrypick.appliedRevision to also be set.
COMPLETED = 2;
// The cherrypick will NOT be applied in this release.
ABANDONED = 3;
}
message Cherrypick {
// The revision on trunk to cherrypick.
string trunkRevision = 1;
// Once applied, the actual commit revision of the cherrypick.
string appliedRevision = 2;
CherrypickState state = 3;
}
message Repository {
// The development git branch the release is based on.
//
// Must be of the form /flutter-(\d+)\.(\d+)-candidate\.(\d+)/
string candidateBranch = 1;
// The commit hash at the tip of the branch before cherrypicks were applied.
string startingGitHead = 2;
// The difference in commits between this and [startingGitHead] is the number
// of cherrypicks that have been currently applied.
string currentGitHead = 3;
// Path to the git checkout on local disk.
string checkoutPath = 4;
// The remote commits will be fetched from.
Remote upstream = 5;
// The remote cherrypicks will be pushed to create a Pull Request.
//
// This should be a mirror owned by the user conducting the release.
Remote mirror = 6;
// Desired cherrypicks.
repeated Cherrypick cherrypicks = 7;
// Only for engine repositories.
string dartRevision = 8;
}
message ConductorState {
// One of 'stable', 'beta', or 'dev'
string releaseChannel = 1;
// The name of the release.
string releaseVersion = 2;
Repository engine = 4;
Repository framework = 5;
int64 createdDate = 6;
int64 lastUpdatedDate = 7;
repeated string logs = 8;
// The last [ReleasePhase] that was successfully completed.
ReleasePhase lastPhase = 9;
// Commit hash of the Conductor tool.
string conductor_version = 10;
}

View File

@@ -1,3 +0,0 @@
// Copyright 2014 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.

View File

@@ -1,704 +0,0 @@
// Copyright 2014 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:convert' show jsonDecode;
import 'dart:io' as io;
import 'package:file/file.dart';
import 'package:meta/meta.dart';
import 'package:platform/platform.dart';
import 'package:process/process.dart';
import './git.dart';
import './globals.dart';
import './stdio.dart';
import './version.dart';
/// Allowed git remote names.
enum RemoteName {
upstream,
mirror,
}
class Remote {
const Remote({
required RemoteName name,
required this.url,
}) : _name = name;
final RemoteName _name;
/// The name of the remote.
String get name {
switch (_name) {
case RemoteName.upstream:
return 'upstream';
case RemoteName.mirror:
return 'mirror';
}
}
/// The URL of the remote.
final String url;
}
/// A source code repository.
abstract class Repository {
Repository({
required this.name,
required this.fetchRemote,
required this.processManager,
required this.stdio,
required this.platform,
required this.fileSystem,
required this.parentDirectory,
this.initialRef,
this.localUpstream = false,
this.useExistingCheckout = false,
this.pushRemote,
}) : git = Git(processManager),
assert(localUpstream != null),
assert(useExistingCheckout != null);
final String name;
final Remote fetchRemote;
/// Remote to publish tags and commits to.
///
/// This value can be null, in which case attempting to publish will lead to
/// a [ConductorException].
final Remote? pushRemote;
/// The initial ref (branch or commit name) to check out.
final String? initialRef;
final Git git;
final ProcessManager processManager;
final Stdio stdio;
final Platform platform;
final FileSystem fileSystem;
final Directory parentDirectory;
final bool useExistingCheckout;
/// If the repository will be used as an upstream for a test repo.
final bool localUpstream;
Directory? _checkoutDirectory;
/// Directory for the repository checkout.
///
/// Since cloning a repository takes a long time, we do not ensure it is
/// cloned on the filesystem until this getter is accessed.
Directory get checkoutDirectory {
if (_checkoutDirectory != null) {
return _checkoutDirectory!;
}
_checkoutDirectory = parentDirectory.childDirectory(name);
lazilyInitialize(_checkoutDirectory!);
return _checkoutDirectory!;
}
/// Ensure the repository is cloned to disk and initialized with proper state.
void lazilyInitialize(Directory checkoutDirectory) {
if (!useExistingCheckout && checkoutDirectory.existsSync()) {
stdio.printTrace('Deleting $name from ${checkoutDirectory.path}...');
checkoutDirectory.deleteSync(recursive: true);
}
if (!checkoutDirectory.existsSync()) {
stdio.printTrace(
'Cloning $name from ${fetchRemote.url} to ${checkoutDirectory.path}...',
);
git.run(
<String>[
'clone',
'--origin',
fetchRemote.name,
'--',
fetchRemote.url,
checkoutDirectory.path
],
'Cloning $name repo',
workingDirectory: parentDirectory.path,
);
if (pushRemote != null) {
git.run(
<String>['remote', 'add', pushRemote!.name, pushRemote!.url],
'Adding remote ${pushRemote!.url} as ${pushRemote!.name}',
workingDirectory: checkoutDirectory.path,
);
git.run(
<String>['fetch', pushRemote!.name],
'Fetching git remote ${pushRemote!.name}',
workingDirectory: checkoutDirectory.path,
);
}
if (localUpstream) {
// These branches must exist locally for the repo that depends on it
// to fetch and push to.
for (final String channel in kReleaseChannels) {
git.run(
<String>['checkout', channel, '--'],
'check out branch $channel locally',
workingDirectory: checkoutDirectory.path,
);
}
}
}
if (initialRef != null) {
git.run(
<String>['checkout', '${fetchRemote.name}/$initialRef'],
'Checking out initialRef $initialRef',
workingDirectory: checkoutDirectory.path,
);
}
final String revision = reverseParse('HEAD');
stdio.printTrace(
'Repository $name is checked out at revision "$revision".',
);
}
/// The URL of the remote named [remoteName].
String remoteUrl(String remoteName) {
assert(remoteName != null);
return git.getOutput(
<String>['remote', 'get-url', remoteName],
'verify the URL of the $remoteName remote',
workingDirectory: checkoutDirectory.path,
);
}
/// Verify the repository's git checkout is clean.
bool gitCheckoutClean() {
final String output = git.getOutput(
<String>['status', '--porcelain'],
'check that the git checkout is clean',
workingDirectory: checkoutDirectory.path,
);
return output == '';
}
/// Return the revision for the branch point between two refs.
String branchPoint(String firstRef, String secondRef) {
return git.getOutput(
<String>['merge-base', firstRef, secondRef],
'determine the merge base between $firstRef and $secondRef',
workingDirectory: checkoutDirectory.path,
).trim();
}
/// Fetch all branches and associated commits and tags from [remoteName].
void fetch(String remoteName) {
git.run(
<String>['fetch', remoteName, '--tags'],
'fetch $remoteName --tags',
workingDirectory: checkoutDirectory.path,
);
}
/// Create (and checkout) a new branch based on the current HEAD.
///
/// Runs `git checkout -b $branchName`.
void newBranch(String branchName) {
git.run(
<String>['checkout', '-b', branchName],
'create & checkout new branch $branchName',
workingDirectory: checkoutDirectory.path,
);
}
/// Check out the given ref.
void checkout(String ref) {
git.run(
<String>['checkout', ref],
'checkout ref',
workingDirectory: checkoutDirectory.path,
);
}
/// Obtain the version tag of the previous dev release.
String getFullTag(String remoteName) {
const String glob = '*.*.*-*.*.pre';
// describe the latest dev release
final String ref = 'refs/remotes/$remoteName/dev';
return git.getOutput(
<String>['describe', '--match', glob, '--exact-match', '--tags', ref],
'obtain last released version number',
workingDirectory: checkoutDirectory.path,
);
}
/// List commits in reverse chronological order.
List<String> revList(List<String> args) {
return git
.getOutput(
<String>['rev-list', ...args],
'rev-list with args ${args.join(' ')}',
workingDirectory: checkoutDirectory.path,
)
.trim()
.split('\n');
}
/// Look up the commit for [ref].
String reverseParse(String ref) {
final String revisionHash = git.getOutput(
<String>['rev-parse', ref],
'look up the commit for the ref $ref',
workingDirectory: checkoutDirectory.path,
);
assert(revisionHash.isNotEmpty);
return revisionHash;
}
/// Determines if one ref is an ancestor for another.
bool isAncestor(String possibleAncestor, String possibleDescendant) {
final int exitcode = git.run(
<String>[
'merge-base',
'--is-ancestor',
possibleDescendant,
possibleAncestor
],
'verify $possibleAncestor is a direct ancestor of $possibleDescendant.',
allowNonZeroExitCode: true,
workingDirectory: checkoutDirectory.path,
);
return exitcode == 0;
}
/// Determines if a given commit has a tag.
bool isCommitTagged(String commit) {
final int exitcode = git.run(
<String>['describe', '--exact-match', '--tags', commit],
'verify $commit is already tagged',
allowNonZeroExitCode: true,
workingDirectory: checkoutDirectory.path,
);
return exitcode == 0;
}
/// Determines if a commit will cherry-pick to current HEAD without conflict.
bool canCherryPick(String commit) {
assert(
gitCheckoutClean(),
'cannot cherry-pick because git checkout ${checkoutDirectory.path} is not clean',
);
final int exitcode = git.run(
<String>['cherry-pick', '--no-commit', commit],
'attempt to cherry-pick $commit without committing',
allowNonZeroExitCode: true,
workingDirectory: checkoutDirectory.path,
);
final bool result = exitcode == 0;
if (result == false) {
stdio.printError(git.getOutput(
<String>['diff'],
'get diff of failed cherry-pick',
workingDirectory: checkoutDirectory.path,
));
}
reset('HEAD');
return result;
}
/// Cherry-pick a [commit] to the current HEAD.
///
/// This method will throw a [GitException] if the command fails.
void cherryPick(String commit) {
assert(
gitCheckoutClean(),
'cannot cherry-pick because git checkout ${checkoutDirectory.path} is not clean',
);
git.run(
<String>['cherry-pick', commit],
'cherry-pick $commit',
workingDirectory: checkoutDirectory.path,
);
}
/// Resets repository HEAD to [ref].
void reset(String ref) {
git.run(
<String>['reset', ref, '--hard'],
'reset to $ref',
workingDirectory: checkoutDirectory.path,
);
}
/// Tag [commit] and push the tag to the remote.
void tag(String commit, String tagName, String remote) {
git.run(
<String>['tag', tagName, commit],
'tag the commit with the version label',
workingDirectory: checkoutDirectory.path,
);
git.run(
<String>['push', remote, tagName],
'publish the tag to the repo',
workingDirectory: checkoutDirectory.path,
);
}
/// Push [commit] to the release channel [branch].
void updateChannel(
String commit,
String remote,
String branch, {
bool force = false,
}) {
git.run(
<String>[
'push',
if (force) '--force',
remote,
'$commit:$branch',
],
'update the release branch with the commit',
workingDirectory: checkoutDirectory.path,
);
}
String commit(
String message, {
bool addFirst = false,
}) {
assert(!message.contains("'"));
if (addFirst) {
git.run(
<String>['add', '--all'],
'add all changes to the index',
workingDirectory: checkoutDirectory.path,
);
}
git.run(
<String>['commit', "--message='$message'"],
'commit changes',
workingDirectory: checkoutDirectory.path,
);
return reverseParse('HEAD');
}
/// Create an empty commit and return the revision.
@visibleForTesting
String authorEmptyCommit([String message = 'An empty commit']) {
git.run(
<String>[
'-c',
'user.name=Conductor',
'-c',
'user.email=conductor@flutter.dev',
'commit',
'--allow-empty',
'-m',
"'$message'",
],
'create an empty commit',
workingDirectory: checkoutDirectory.path,
);
return reverseParse('HEAD');
}
/// Create a new clone of the current repository.
///
/// The returned repository will inherit all properties from this one, except
/// for the upstream, which will be the path to this repository on disk.
///
/// This method is for testing purposes.
@visibleForTesting
Repository cloneRepository(String cloneName);
}
class FrameworkRepository extends Repository {
FrameworkRepository(
this.checkouts, {
String name = 'framework',
Remote fetchRemote = const Remote(
name: RemoteName.upstream, url: FrameworkRepository.defaultUpstream),
bool localUpstream = false,
bool useExistingCheckout = false,
String? initialRef,
Remote? pushRemote,
}) : super(
name: name,
fetchRemote: fetchRemote,
pushRemote: pushRemote,
initialRef: initialRef,
fileSystem: checkouts.fileSystem,
localUpstream: localUpstream,
parentDirectory: checkouts.directory,
platform: checkouts.platform,
processManager: checkouts.processManager,
stdio: checkouts.stdio,
useExistingCheckout: useExistingCheckout,
);
/// A [FrameworkRepository] with the host conductor's repo set as upstream.
///
/// This is useful when testing a commit that has not been merged upstream
/// yet.
factory FrameworkRepository.localRepoAsUpstream(
Checkouts checkouts, {
String name = 'framework',
bool useExistingCheckout = false,
required String upstreamPath,
}) {
return FrameworkRepository(
checkouts,
name: name,
fetchRemote: Remote(
name: RemoteName.upstream,
url: 'file://$upstreamPath/',
),
localUpstream: false,
useExistingCheckout: useExistingCheckout,
);
}
final Checkouts checkouts;
static const String defaultUpstream =
'https://github.com/flutter/flutter.git';
static const String defaultBranch = 'master';
String get cacheDirectory => fileSystem.path.join(
checkoutDirectory.path,
'bin',
'cache',
);
@override
Repository cloneRepository(String? cloneName) {
assert(localUpstream);
cloneName ??= 'clone-of-$name';
return FrameworkRepository(
checkouts,
name: cloneName,
fetchRemote: Remote(
name: RemoteName.upstream, url: 'file://${checkoutDirectory.path}/'),
useExistingCheckout: useExistingCheckout,
);
}
void _ensureToolReady() {
final File toolsStamp =
fileSystem.directory(cacheDirectory).childFile('flutter_tools.stamp');
if (toolsStamp.existsSync()) {
final String toolsStampHash = toolsStamp.readAsStringSync().trim();
final String repoHeadHash = reverseParse('HEAD');
if (toolsStampHash == repoHeadHash) {
return;
}
}
stdio.printTrace('Building tool...');
// Build tool
processManager.runSync(<String>[
fileSystem.path.join(checkoutDirectory.path, 'bin', 'flutter'),
'help',
]);
}
io.ProcessResult runFlutter(List<String> args) {
_ensureToolReady();
return processManager.runSync(<String>[
fileSystem.path.join(checkoutDirectory.path, 'bin', 'flutter'),
...args,
]);
}
@override
void checkout(String ref) {
super.checkout(ref);
// The tool will overwrite old cached artifacts, but not delete unused
// artifacts from a previous version. Thus, delete the entire cache and
// re-populate.
final Directory cache = fileSystem.directory(cacheDirectory);
if (cache.existsSync()) {
stdio.printTrace('Deleting cache...');
cache.deleteSync(recursive: true);
}
_ensureToolReady();
}
Version flutterVersion() {
// Check version
final io.ProcessResult result =
runFlutter(<String>['--version', '--machine']);
final Map<String, dynamic> versionJson = jsonDecode(
stdoutToString(result.stdout),
) as Map<String, dynamic>;
return Version.fromString(versionJson['frameworkVersion'] as String);
}
}
/// A wrapper around the host repository that is executing the conductor.
///
/// [Repository] methods that mutate the underlying repository will throw a
/// [ConductorException].
class HostFrameworkRepository extends FrameworkRepository {
HostFrameworkRepository({
required Checkouts checkouts,
String name = 'host-framework',
bool useExistingCheckout = false,
required String upstreamPath,
}) : super(
checkouts,
name: name,
fetchRemote: Remote(
name: RemoteName.upstream,
url: 'file://$upstreamPath/',
),
localUpstream: false,
useExistingCheckout: useExistingCheckout,
) {
_checkoutDirectory = checkouts.fileSystem.directory(upstreamPath);
}
@override
Directory get checkoutDirectory => _checkoutDirectory!;
@override
void newBranch(String branchName) {
throw ConductorException('newBranch not implemented for the host repository');
}
@override
void checkout(String ref) {
throw ConductorException('checkout not implemented for the host repository');
}
@override
String cherryPick(String commit) {
throw ConductorException('cherryPick not implemented for the host repository');
}
@override
String reset(String ref) {
throw ConductorException('reset not implemented for the host repository');
}
@override
void tag(String commit, String tagName, String remote) {
throw ConductorException('tag not implemented for the host repository');
}
@override
void updateChannel(
String commit,
String remote,
String branch, {
bool force = false,
}) {
throw ConductorException('updateChannel not implemented for the host repository');
}
@override
String authorEmptyCommit([String message = 'An empty commit']) {
throw ConductorException(
'authorEmptyCommit not implemented for the host repository',
);
}
}
class EngineRepository extends Repository {
EngineRepository(
this.checkouts, {
String name = 'engine',
String initialRef = EngineRepository.defaultBranch,
Remote fetchRemote = const Remote(
name: RemoteName.upstream, url: EngineRepository.defaultUpstream),
bool localUpstream = false,
bool useExistingCheckout = false,
Remote? pushRemote,
}) : super(
name: name,
fetchRemote: fetchRemote,
pushRemote: pushRemote,
initialRef: initialRef,
fileSystem: checkouts.fileSystem,
localUpstream: localUpstream,
parentDirectory: checkouts.directory,
platform: checkouts.platform,
processManager: checkouts.processManager,
stdio: checkouts.stdio,
useExistingCheckout: useExistingCheckout,
);
final Checkouts checkouts;
static const String defaultUpstream = 'https://github.com/flutter/engine.git';
static const String defaultBranch = 'master';
/// Update the `dart_revision` entry in the DEPS file.
void updateDartRevision(
String newRevision, {
@visibleForTesting File? depsFile,
}) {
assert(newRevision.length == 40);
depsFile ??= checkoutDirectory.childFile('DEPS');
final String fileContent = depsFile.readAsStringSync();
final RegExp dartPattern = RegExp("[ ]+'dart_revision': '([a-z0-9]{40})',");
final Iterable<RegExpMatch> allMatches = dartPattern.allMatches(fileContent);
if (allMatches.length != 1) {
throw ConductorException(
'Unexpected content in the DEPS file at ${depsFile.path}\n'
'Expected to find pattern ${dartPattern.pattern} 1 times, but got '
'${allMatches.length}.'
);
}
final String updatedFileContent = fileContent.replaceFirst(
dartPattern,
" 'dart_revision': '$newRevision',",
);
depsFile.writeAsStringSync(updatedFileContent);
}
@override
Repository cloneRepository(String? cloneName) {
assert(localUpstream);
cloneName ??= 'clone-of-$name';
return EngineRepository(
checkouts,
name: cloneName,
fetchRemote: Remote(
name: RemoteName.upstream, url: 'file://${checkoutDirectory.path}/'),
useExistingCheckout: useExistingCheckout,
);
}
}
/// An enum of all the repositories that the Conductor supports.
enum RepositoryType {
framework,
engine,
}
class Checkouts {
Checkouts({
required this.fileSystem,
required this.platform,
required this.processManager,
required this.stdio,
required Directory parentDirectory,
String directoryName = 'flutter_conductor_checkouts',
}) : directory = parentDirectory.childDirectory(directoryName) {
if (!directory.existsSync()) {
directory.createSync(recursive: true);
}
}
final Directory directory;
final FileSystem fileSystem;
final Platform platform;
final ProcessManager processManager;
final Stdio stdio;
}

View File

@@ -1,204 +0,0 @@
// Copyright 2014 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 'package:args/args.dart';
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:meta/meta.dart';
import 'package:platform/platform.dart';
import './repository.dart';
import './stdio.dart';
import './version.dart';
const String kIncrement = 'increment';
const String kCommit = 'commit';
const String kRemoteName = 'remote';
const String kJustPrint = 'just-print';
const String kYes = 'yes';
const String kForce = 'force';
const String kSkipTagging = 'skip-tagging';
/// Create a new dev release without cherry picks.
class RollDevCommand extends Command<void> {
RollDevCommand({
required this.checkouts,
required this.fileSystem,
required this.platform,
required this.stdio,
}) {
argParser.addOption(
kIncrement,
help: 'Specifies which part of the x.y.z version number to increment. Required.',
valueHelp: 'level',
allowed: <String>['y', 'z', 'm'],
allowedHelp: <String, String>{
'y': 'Indicates the first dev release after a beta release.',
'z': 'Indicates a hotfix to a stable release.',
'm': 'Indicates a standard dev release.',
},
);
argParser.addOption(
kCommit,
help: 'Specifies which git commit to roll to the dev branch. Required.',
valueHelp: 'hash',
defaultsTo: null, // This option is required
);
argParser.addFlag(
kForce,
abbr: 'f',
help: 'Force push. Necessary when the previous release had cherry-picks.',
negatable: false,
);
argParser.addFlag(
kJustPrint,
negatable: false,
help:
"Don't actually roll the dev channel; "
'just print the would-be version and quit.',
);
argParser.addFlag(
kSkipTagging,
negatable: false,
help: 'Do not create tag and push to remote, only update release branch. '
'For recovering when the script fails trying to git push to the release branch.'
);
argParser.addFlag(
kYes,
negatable: false,
abbr: 'y',
help: 'Skip the confirmation prompt.',
);
argParser.addOption(
kRemoteName,
help: 'Specifies which git remote to fetch from.',
defaultsTo: 'upstream',
);
}
final Checkouts checkouts;
final FileSystem fileSystem;
final Platform platform;
final Stdio stdio;
@override
String get name => 'roll-dev';
@override
String get description =>
'For publishing a dev release without cherry picks.';
@override
void run() {
rollDev(
argResults: argResults!,
repository: FrameworkRepository(checkouts),
stdio: stdio,
usage: argParser.usage,
);
}
}
/// Main script execution.
///
/// Returns true if publishing was successful, else false.
@visibleForTesting
bool rollDev({
required String usage,
required ArgResults argResults,
required Stdio stdio,
required FrameworkRepository repository,
}) {
final String remoteName = argResults[kRemoteName] as String;
final String level = argResults[kIncrement] as String;
final String commit = argResults[kCommit] as String;
final bool justPrint = argResults[kJustPrint] as bool;
final bool autoApprove = argResults[kYes] as bool;
final bool force = argResults[kForce] as bool;
final bool skipTagging = argResults[kSkipTagging] as bool;
if (level == null || commit == null) {
stdio.printStatus(
'roll_dev.dart --increment=level --commit=hash • update the version tags '
'and roll a new dev build.\n$usage');
return false;
}
final String remoteUrl = repository.remoteUrl(remoteName);
if (!repository.gitCheckoutClean()) {
throw Exception(
'Your git repository is not clean. Try running "git clean -fd". Warning, '
'this will delete files! Run with -n to find out which ones.');
}
repository.fetch(remoteName);
// Verify [commit] is valid
repository.reverseParse(commit);
stdio.printStatus('remoteName is $remoteName');
final Version lastVersion =
Version.fromString(repository.getFullTag(remoteName));
final Version version =
skipTagging ? lastVersion : Version.increment(lastVersion, level);
final String tagName = version.toString();
if (repository.reverseParse(lastVersion.toString()).contains(commit.trim())) {
throw Exception(
'Commit $commit is already on the dev branch as $lastVersion.');
}
if (justPrint) {
stdio.printStatus(tagName);
return false;
}
if (skipTagging && !repository.isCommitTagged(commit)) {
throw Exception(
'The $kSkipTagging flag is only supported for tagged commits.');
}
if (!force && !repository.isAncestor(commit, lastVersion.toString())) {
throw Exception(
'The previous dev tag $lastVersion is not a direct ancestor of $commit.\n'
'The flag "$kForce" is required to force push a new release past a cherry-pick.');
}
final String hash = repository.reverseParse(commit);
// [commit] can be a prefix for [hash].
assert(hash.startsWith(commit));
// PROMPT
if (autoApprove) {
stdio.printStatus(
'Publishing Flutter $version ($hash) to the "dev" channel.');
} else {
stdio.printStatus('Your tree is ready to publish Flutter $version '
'($hash) to the "dev" channel.');
stdio.write('Are you? [yes/no] ');
if (stdio.readLineSync() != 'yes') {
stdio.printError('The dev roll has been aborted.');
return false;
}
}
if (!skipTagging) {
repository.tag(commit, version.toString(), remoteName);
}
repository.updateChannel(
commit,
remoteName,
'dev',
force: force,
);
stdio.printStatus(
'Flutter version $version has been rolled to the "dev" channel at $remoteUrl.',
);
return true;
}

View File

@@ -1,378 +0,0 @@
// Copyright 2014 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.
// @dart = 2.8
import 'dart:convert' show jsonEncode;
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:fixnum/fixnum.dart';
import 'package:meta/meta.dart';
import 'package:platform/platform.dart';
import 'package:process/process.dart';
import './git.dart';
import './globals.dart';
import './proto/conductor_state.pb.dart' as pb;
import './proto/conductor_state.pbenum.dart' show ReleasePhase;
import './repository.dart';
import './state.dart';
import './stdio.dart';
const String kCandidateOption = 'candidate-branch';
const String kDartRevisionOption = 'dart-revision';
const String kEngineCherrypicksOption = 'engine-cherrypicks';
const String kEngineUpstreamOption = 'engine-upstream';
const String kFrameworkCherrypicksOption = 'framework-cherrypicks';
const String kFrameworkMirrorOption = 'framework-mirror';
const String kFrameworkUpstreamOption = 'framework-upstream';
const String kEngineMirrorOption = 'engine-mirror';
const String kReleaseOption = 'release-channel';
const String kStateOption = 'state-file';
/// Command to print the status of the current Flutter release.
class StartCommand extends Command<void> {
StartCommand({
@required this.checkouts,
@required this.flutterRoot,
}) : platform = checkouts.platform,
processManager = checkouts.processManager,
fileSystem = checkouts.fileSystem,
stdio = checkouts.stdio {
final String defaultPath = defaultStateFilePath(platform);
argParser.addOption(
kCandidateOption,
help: 'The candidate branch the release will be based on.',
);
argParser.addOption(
kReleaseOption,
help: 'The target release channel for the release.',
allowed: <String>['stable', 'beta', 'dev'],
);
argParser.addOption(
kFrameworkUpstreamOption,
defaultsTo: FrameworkRepository.defaultUpstream,
help:
'Configurable Framework repo upstream remote. Primarily for testing.',
hide: true,
);
argParser.addOption(
kEngineUpstreamOption,
defaultsTo: EngineRepository.defaultUpstream,
help: 'Configurable Engine repo upstream remote. Primarily for testing.',
hide: true,
);
argParser.addOption(
kFrameworkMirrorOption,
help: 'Framework repo mirror remote.',
);
argParser.addOption(
kEngineMirrorOption,
help: 'Engine repo mirror remote.',
);
argParser.addOption(
kStateOption,
defaultsTo: defaultPath,
help: 'Path to persistent state file. Defaults to $defaultPath',
);
argParser.addMultiOption(
kEngineCherrypicksOption,
help: 'Engine cherrypick hashes to be applied.',
defaultsTo: <String>[],
);
argParser.addMultiOption(
kFrameworkCherrypicksOption,
help: 'Framework cherrypick hashes to be applied.',
defaultsTo: <String>[],
);
argParser.addOption(
kDartRevisionOption,
help: 'New Dart revision to cherrypick.',
);
final Git git = Git(processManager);
conductorVersion = git.getOutput(
<String>['rev-parse', 'HEAD'],
'look up the current revision.',
workingDirectory: flutterRoot.path,
).trim();
assert(conductorVersion.isNotEmpty);
}
final Checkouts checkouts;
/// The root directory of the Flutter repository that houses the Conductor.
///
/// This directory is used to check the git revision of the Conductor.
final Directory flutterRoot;
final FileSystem fileSystem;
final Platform platform;
final ProcessManager processManager;
final Stdio stdio;
/// Git revision for the currently running Conductor.
String conductorVersion;
@override
String get name => 'start';
@override
String get description => 'Initialize a new Flutter release.';
@override
void run() {
if (!platform.isMacOS && !platform.isLinux) {
throw ConductorException(
'Error! This tool is only supported on macOS and Linux',
);
}
final File stateFile = checkouts.fileSystem.file(
getValueFromEnvOrArgs(kStateOption, argResults, platform.environment),
);
if (stateFile.existsSync()) {
throw ConductorException(
'Error! A persistent state file already found at ${argResults[kStateOption]}.\n\n'
'Run `conductor clean` to cancel a previous release.');
}
final String frameworkUpstream = getValueFromEnvOrArgs(
kFrameworkUpstreamOption,
argResults,
platform.environment,
);
final String frameworkMirror = getValueFromEnvOrArgs(
kFrameworkMirrorOption,
argResults,
platform.environment,
);
final String engineUpstream = getValueFromEnvOrArgs(
kEngineUpstreamOption,
argResults,
platform.environment,
);
final String engineMirror = getValueFromEnvOrArgs(
kEngineMirrorOption,
argResults,
platform.environment,
);
final String candidateBranch = getValueFromEnvOrArgs(
kCandidateOption,
argResults,
platform.environment,
);
final String releaseChannel = getValueFromEnvOrArgs(
kReleaseOption,
argResults,
platform.environment,
);
final List<String> frameworkCherrypickRevisions = getValuesFromEnvOrArgs(
kFrameworkCherrypicksOption,
argResults,
platform.environment,
);
final List<String> engineCherrypickRevisions = getValuesFromEnvOrArgs(
kEngineCherrypicksOption,
argResults,
platform.environment,
);
final String dartRevision = getValueFromEnvOrArgs(
kDartRevisionOption,
argResults,
platform.environment,
allowNull: true,
);
if (!releaseCandidateBranchRegex.hasMatch(candidateBranch)) {
throw ConductorException(
'Invalid release candidate branch "$candidateBranch". Text should '
'match the regex pattern /${releaseCandidateBranchRegex.pattern}/.',
);
}
final Int64 unixDate = Int64(DateTime.now().millisecondsSinceEpoch);
final pb.ConductorState state = pb.ConductorState();
state.releaseChannel = releaseChannel;
state.createdDate = unixDate;
state.lastUpdatedDate = unixDate;
final EngineRepository engine = EngineRepository(
checkouts,
initialRef: candidateBranch,
fetchRemote: Remote(
name: RemoteName.upstream,
url: engineUpstream,
),
pushRemote: Remote(
name: RemoteName.mirror,
url: engineMirror,
),
);
// Create a new branch so that we don't accidentally push to upstream
// candidateBranch.
engine.newBranch('cherrypicks-$candidateBranch');
if (dartRevision != null && dartRevision.isNotEmpty) {
engine.updateDartRevision(dartRevision);
engine.commit('Update Dart SDK to $dartRevision', addFirst: true);
}
final List<pb.Cherrypick> engineCherrypicks = _sortCherrypicks(
repository: engine,
cherrypicks: engineCherrypickRevisions,
upstreamRef: EngineRepository.defaultBranch,
releaseRef: candidateBranch,
).map((String revision) => pb.Cherrypick(
trunkRevision: revision,
state: pb.CherrypickState.PENDING,
)).toList();
for (final pb.Cherrypick cherrypick in engineCherrypicks) {
final String revision = cherrypick.trunkRevision;
final bool success = engine.canCherryPick(revision);
stdio.printTrace(
'Attempt to cherrypick $revision ${success ? 'succeeded' : 'failed'}',
);
if (success) {
engine.cherryPick(revision);
cherrypick.state = pb.CherrypickState.COMPLETED;
} else {
cherrypick.state = pb.CherrypickState.PENDING_WITH_CONFLICT;
}
}
final String engineHead = engine.reverseParse('HEAD');
state.engine = pb.Repository(
candidateBranch: candidateBranch,
startingGitHead: engineHead,
currentGitHead: engineHead,
checkoutPath: engine.checkoutDirectory.path,
cherrypicks: engineCherrypicks,
dartRevision: dartRevision,
);
final FrameworkRepository framework = FrameworkRepository(
checkouts,
initialRef: candidateBranch,
fetchRemote: Remote(
name: RemoteName.upstream,
url: frameworkUpstream,
),
pushRemote: Remote(
name: RemoteName.mirror,
url: frameworkMirror,
),
);
framework.newBranch('cherrypicks-$candidateBranch');
final List<pb.Cherrypick> frameworkCherrypicks = _sortCherrypicks(
repository: framework,
cherrypicks: frameworkCherrypickRevisions,
upstreamRef: FrameworkRepository.defaultBranch,
releaseRef: candidateBranch,
).map((String revision) => pb.Cherrypick(
trunkRevision: revision,
state: pb.CherrypickState.PENDING,
)).toList();
for (final pb.Cherrypick cherrypick in frameworkCherrypicks) {
final String revision = cherrypick.trunkRevision;
final bool success = framework.canCherryPick(revision);
stdio.printTrace(
'Attempt to cherrypick $cherrypick ${success ? 'succeeded' : 'failed'}',
);
if (success) {
framework.cherryPick(revision);
cherrypick.state = pb.CherrypickState.COMPLETED;
} else {
cherrypick.state = pb.CherrypickState.PENDING_WITH_CONFLICT;
}
}
final String frameworkHead = framework.reverseParse('HEAD');
state.framework = pb.Repository(
candidateBranch: candidateBranch,
startingGitHead: frameworkHead,
currentGitHead: frameworkHead,
checkoutPath: framework.checkoutDirectory.path,
cherrypicks: frameworkCherrypicks,
);
state.lastPhase = ReleasePhase.INITIALIZE;
state.conductorVersion = conductorVersion;
stdio.printTrace('Writing state to file ${stateFile.path}...');
state.logs.addAll(stdio.logs);
stateFile.writeAsStringSync(
jsonEncode(state.toProto3Json()),
flush: true,
);
stdio.printStatus(presentState(state));
}
// To minimize merge conflicts, sort the commits by rev-list order.
List<String> _sortCherrypicks({
@required Repository repository,
@required List<String> cherrypicks,
@required String upstreamRef,
@required String releaseRef,
}) {
if (cherrypicks.isEmpty) {
return cherrypicks;
}
// Input cherrypick hashes that failed to be parsed by git.
final List<String> unknownCherrypicks = <String>[];
// Full 40-char hashes parsed by git.
final List<String> validatedCherrypicks = <String>[];
// Final, validated, sorted list of cherrypicks to be applied.
final List<String> sortedCherrypicks = <String>[];
for (final String cherrypick in cherrypicks) {
try {
final String fullRef = repository.reverseParse(cherrypick);
validatedCherrypicks.add(fullRef);
} on GitException {
// Catch this exception so that we can validate the rest.
unknownCherrypicks.add(cherrypick);
}
}
final String branchPoint = repository.branchPoint(
'${repository.fetchRemote.name}/$upstreamRef',
'${repository.fetchRemote.name}/$releaseRef',
);
// `git rev-list` returns newest first, so reverse this list
final List<String> upstreamRevlist = repository.revList(<String>[
'--ancestry-path',
'$branchPoint..$upstreamRef',
]).reversed.toList();
stdio.printStatus('upstreamRevList:\n${upstreamRevlist.join('\n')}\n');
stdio.printStatus('validatedCherrypicks:\n${validatedCherrypicks.join('\n')}\n');
for (final String upstreamRevision in upstreamRevlist) {
if (validatedCherrypicks.contains(upstreamRevision)) {
validatedCherrypicks.remove(upstreamRevision);
sortedCherrypicks.add(upstreamRevision);
if (unknownCherrypicks.isEmpty && validatedCherrypicks.isEmpty) {
return sortedCherrypicks;
}
}
}
// We were given input cherrypicks that were not present in the upstream
// rev-list
stdio.printError(
'The following ${repository.name} cherrypicks were not found in the '
'upstream $upstreamRef branch:',
);
for (final String cp in <String>[...validatedCherrypicks, ...unknownCherrypicks]) {
stdio.printError('\t$cp');
}
throw ConductorException(
'${validatedCherrypicks.length + unknownCherrypicks.length} unknown cherrypicks provided!',
);
}
}

View File

@@ -1,172 +0,0 @@
// Copyright 2014 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.
// @dart = 2.8
import 'package:platform/platform.dart';
import './globals.dart';
import './proto/conductor_state.pb.dart' as pb;
import './proto/conductor_state.pbenum.dart' show ReleasePhase;
const String kStateFileName = '.flutter_conductor_state.json';
String luciConsoleLink(String channel, String groupName) {
assert(
<String>['stable', 'beta', 'dev', 'master'].contains(channel),
'channel $channel not recognized',
);
assert(
<String>['framework', 'engine', 'devicelab'].contains(groupName),
'group named $groupName not recognized',
);
final String consoleName = channel == 'master' ? groupName : '${channel}_$groupName';
return 'https://ci.chromium.org/p/flutter/g/$consoleName/console';
}
String defaultStateFilePath(Platform platform) {
assert(platform.environment['HOME'] != null);
return <String>[
platform.environment['HOME'],
kStateFileName,
].join(platform.pathSeparator);
}
String presentState(pb.ConductorState state) {
final StringBuffer buffer = StringBuffer();
buffer.writeln('Conductor version: ${state.conductorVersion}');
buffer.writeln('Release channel: ${state.releaseChannel}');
buffer.writeln('');
buffer.writeln(
'Release started at: ${DateTime.fromMillisecondsSinceEpoch(state.createdDate.toInt())}');
buffer.writeln(
'Last updated at: ${DateTime.fromMillisecondsSinceEpoch(state.lastUpdatedDate.toInt())}');
buffer.writeln('');
buffer.writeln('Engine Repo');
buffer.writeln('\tCandidate branch: ${state.engine.candidateBranch}');
buffer.writeln('\tStarting git HEAD: ${state.engine.startingGitHead}');
buffer.writeln('\tCurrent git HEAD: ${state.engine.currentGitHead}');
buffer.writeln('\tPath to checkout: ${state.engine.checkoutPath}');
buffer.writeln('\tPost-submit LUCI dashboard: ${luciConsoleLink(state.releaseChannel, 'engine')}');
if (state.engine.cherrypicks.isNotEmpty) {
buffer.writeln('${state.engine.cherrypicks.length} Engine Cherrypicks:');
for (final pb.Cherrypick cherrypick in state.engine.cherrypicks) {
buffer.writeln('\t${cherrypick.trunkRevision} - ${cherrypick.state}');
}
} else {
buffer.writeln('0 Engine cherrypicks.');
}
if (state.engine.dartRevision != null && state.engine.dartRevision.isNotEmpty) {
buffer.writeln('New Dart SDK revision: ${state.engine.dartRevision}');
}
buffer.writeln('Framework Repo');
buffer.writeln('\tCandidate branch: ${state.framework.candidateBranch}');
buffer.writeln('\tStarting git HEAD: ${state.framework.startingGitHead}');
buffer.writeln('\tCurrent git HEAD: ${state.framework.currentGitHead}');
buffer.writeln('\tPath to checkout: ${state.framework.checkoutPath}');
buffer.writeln('\tPost-submit LUCI dashboard: ${luciConsoleLink(state.releaseChannel, 'framework')}');
buffer.writeln('\tDevicelab LUCI dashboard: ${luciConsoleLink(state.releaseChannel, 'devicelab')}');
if (state.framework.cherrypicks.isNotEmpty) {
buffer.writeln('${state.framework.cherrypicks.length} Framework Cherrypicks:');
for (final pb.Cherrypick cherrypick in state.framework.cherrypicks) {
buffer.writeln('\t${cherrypick.trunkRevision} - ${cherrypick.state}');
}
} else {
buffer.writeln('0 Framework cherrypicks.');
}
buffer.writeln('');
if (state.lastPhase == ReleasePhase.VERIFY_RELEASE) {
buffer.writeln(
'${state.releaseChannel} release ${state.releaseVersion} has been published and verified.\n',
);
return buffer.toString();
}
buffer.writeln('The next step is:');
buffer.writeln(presentPhases(state.lastPhase));
buffer.writeln(phaseInstructions(state));
buffer.writeln('');
buffer.writeln('Issue `conductor next` when you are ready to proceed.');
return buffer.toString();
}
String presentPhases(ReleasePhase lastPhase) {
final ReleasePhase nextPhase = getNextPhase(lastPhase);
final StringBuffer buffer = StringBuffer();
bool phaseCompleted = true;
for (final ReleasePhase phase in ReleasePhase.values) {
if (phase == nextPhase) {
// This phase will execute the next time `conductor next` is run.
buffer.writeln('> ${phase.name} (next)');
phaseCompleted = false;
} else if (phaseCompleted) {
// This phase was already completed.
buffer.writeln('✓ ${phase.name}');
} else {
// This phase has not been completed yet.
buffer.writeln(' ${phase.name}');
}
}
return buffer.toString();
}
String phaseInstructions(pb.ConductorState state) {
switch (state.lastPhase) {
case ReleasePhase.INITIALIZE:
if (state.engine.cherrypicks.isEmpty) {
return <String>[
'There are no engine cherrypicks, so issue `conductor next` to continue',
'to the next step.',
].join('\n');
}
return <String>[
'You must now manually apply the following engine cherrypicks to the checkout',
'at ${state.engine.checkoutPath} in order:',
for (final pb.Cherrypick cherrypick in state.engine.cherrypicks)
'\t${cherrypick.trunkRevision}',
'See $kReleaseDocumentationUrl for more information.',
].join('\n');
case ReleasePhase.APPLY_ENGINE_CHERRYPICKS:
return <String>[
'You must verify Engine CI builds are successful and then codesign the',
'binaries at revision ${state.engine.currentGitHead}.',
].join('\n');
case ReleasePhase.CODESIGN_ENGINE_BINARIES:
return <String>[
'You must now manually apply the following framework cherrypicks to the checkout',
'at ${state.framework.checkoutPath} in order:',
for (final pb.Cherrypick cherrypick in state.framework.cherrypicks)
'\t${cherrypick.trunkRevision}',
].join('\n');
case ReleasePhase.APPLY_FRAMEWORK_CHERRYPICKS:
return <String>[
'You must verify Framework CI builds are successful.',
'See $kReleaseDocumentationUrl for more information.',
].join('\n');
case ReleasePhase.PUBLISH_VERSION:
return 'Issue `conductor next` to publish your release to the release branch.';
case ReleasePhase.PUBLISH_CHANNEL:
return <String>[
'Release archive packages must be verified on cloud storage. Issue',
'`conductor next` to check if they are ready.',
].join('\n');
case ReleasePhase.VERIFY_RELEASE:
return 'This release has been completed.';
}
assert(false);
return ''; // For analyzer
}
/// Returns the next phase in the ReleasePhase enum.
///
/// Will throw a [ConductorException] if [ReleasePhase.RELEASE_VERIFIED] is
/// passed as an argument, as there is no next phase.
ReleasePhase getNextPhase(ReleasePhase previousPhase) {
assert(previousPhase != null);
if (previousPhase == ReleasePhase.VERIFY_RELEASE) {
throw ConductorException('There is no next ReleasePhase!');
}
return ReleasePhase.valueOf(previousPhase.value + 1);
}

View File

@@ -1,70 +0,0 @@
// Copyright 2014 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.
// @dart = 2.8
import 'dart:convert' show jsonDecode;
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:meta/meta.dart';
import 'package:platform/platform.dart';
import './proto/conductor_state.pb.dart' as pb;
import './repository.dart';
import './state.dart';
import './stdio.dart';
const String kVerboseFlag = 'verbose';
const String kStateOption = 'state-file';
/// Command to print the status of the current Flutter release.
class StatusCommand extends Command<void> {
StatusCommand({
@required this.checkouts,
}) : platform = checkouts.platform,
fileSystem = checkouts.fileSystem,
stdio = checkouts.stdio {
final String defaultPath = defaultStateFilePath(platform);
argParser.addOption(
kStateOption,
defaultsTo: defaultPath,
help: 'Path to persistent state file. Defaults to $defaultPath',
);
argParser.addFlag(
kVerboseFlag,
abbr: 'v',
defaultsTo: false,
help: 'Also print logs.',
);
}
final Checkouts checkouts;
final FileSystem fileSystem;
final Platform platform;
final Stdio stdio;
@override
String get name => 'status';
@override
String get description => 'Print status of current release.';
@override
void run() {
final File stateFile = checkouts.fileSystem.file(argResults[kStateOption]);
if (!stateFile.existsSync()) {
stdio.printStatus(
'No persistent state file found at ${argResults[kStateOption]}.');
return;
}
final pb.ConductorState state = pb.ConductorState();
state.mergeFromProto3Json(jsonDecode(stateFile.readAsStringSync()));
stdio.printStatus(presentState(state));
if (argResults[kVerboseFlag] as bool) {
stdio.printStatus('\nLogs:');
state.logs.forEach(stdio.printStatus);
}
}
}

View File

@@ -1,86 +0,0 @@
// Copyright 2014 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:meta/meta.dart';
abstract class Stdio {
final List<String> logs = <String>[];
/// Error/warning messages printed to STDERR.
@mustCallSuper
void printError(String message) {
logs.add('[error] $message');
}
/// Ordinary STDOUT messages.
@mustCallSuper
void printStatus(String message) {
logs.add('[status] $message');
}
/// Debug messages that are only printed in verbose mode.
@mustCallSuper
void printTrace(String message) {
logs.add('[trace] $message');
}
/// Write string to STDOUT without trailing newline.
@mustCallSuper
void write(String message) {
logs.add('[write] $message');
}
/// Read a line of text from STDIN.
String readLineSync();
}
/// A logger that will print out trace messages.
class VerboseStdio extends Stdio {
VerboseStdio({
required this.stdout,
required this.stderr,
required this.stdin,
});
factory VerboseStdio.local() => VerboseStdio(
stdout: io.stdout,
stderr: io.stderr,
stdin: io.stdin,
);
final io.Stdout stdout;
final io.Stdout stderr;
final io.Stdin stdin;
@override
void printError(String message) {
super.printError(message);
stderr.writeln(message);
}
@override
void printStatus(String message) {
super.printStatus(message);
stdout.writeln(message);
}
@override
void printTrace(String message) {
super.printTrace(message);
stdout.writeln(message);
}
@override
void write(String message) {
super.write(message);
stdout.write(message);
}
@override
String readLineSync() {
return stdin.readLineSync()!;
}
}

View File

@@ -1,213 +0,0 @@
// Copyright 2014 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.
/// Possible string formats that `flutter --version` can return.
enum VersionType {
/// A stable flutter release.
///
/// Example: '1.2.3'
stable,
/// A pre-stable flutter release.
///
/// Example: '1.2.3-4.5.pre'
development,
/// A master channel flutter version.
///
/// Example: '1.2.3-4.0.pre.10'
///
/// The last number is the number of commits past the last tagged version.
latest,
}
final Map<VersionType, RegExp> versionPatterns = <VersionType, RegExp>{
VersionType.stable: RegExp(r'^(\d+)\.(\d+)\.(\d+)$'),
VersionType.development: RegExp(r'^(\d+)\.(\d+)\.(\d+)-(\d+)\.(\d+)\.pre$'),
VersionType.latest: RegExp(r'^(\d+)\.(\d+)\.(\d+)-(\d+)\.(\d+)\.pre\.(\d+)$'),
};
class Version {
Version({
required this.x,
required this.y,
required this.z,
this.m,
this.n,
this.commits,
required this.type,
}) {
switch (type) {
case VersionType.stable:
assert(m == null);
assert(n == null);
assert(commits == null);
break;
case VersionType.development:
assert(m != null);
assert(n != null);
assert(commits == null);
break;
case VersionType.latest:
assert(m != null);
assert(n != null);
assert(commits != null);
break;
}
}
/// Create a new [Version] from a version string.
///
/// It is expected that [versionString] will be generated by
/// `flutter --version` and match one of `stablePattern`, `developmentPattern`
/// and `latestPattern`.
factory Version.fromString(String versionString) {
assert(versionString != null);
versionString = versionString.trim();
// stable tag
Match? match = versionPatterns[VersionType.stable]!.firstMatch(versionString);
if (match != null) {
// parse stable
final List<int> parts = match
.groups(<int>[1, 2, 3])
.map((String? s) => int.parse(s!))
.toList();
return Version(
x: parts[0],
y: parts[1],
z: parts[2],
type: VersionType.stable,
);
}
// development tag
match = versionPatterns[VersionType.development]!.firstMatch(versionString);
if (match != null) {
// parse development
final List<int> parts =
match.groups(<int>[1, 2, 3, 4, 5]).map((String? s) => int.parse(s!)).toList();
return Version(
x: parts[0],
y: parts[1],
z: parts[2],
m: parts[3],
n: parts[4],
type: VersionType.development,
);
}
// latest tag
match = versionPatterns[VersionType.latest]!.firstMatch(versionString);
if (match != null) {
// parse latest
final List<int> parts = match.groups(
<int>[1, 2, 3, 4, 5, 6],
).map(
(String? s) => int.parse(s!),
).toList();
return Version(
x: parts[0],
y: parts[1],
z: parts[2],
m: parts[3],
n: parts[4],
commits: parts[5],
type: VersionType.latest,
);
}
throw Exception('${versionString.trim()} cannot be parsed');
}
// Returns a new version with the given [increment] part incremented.
// NOTE new version must be of same type as previousVersion.
factory Version.increment(
Version previousVersion,
String increment, {
VersionType? nextVersionType,
}) {
final int nextX = previousVersion.x;
int nextY = previousVersion.y;
int nextZ = previousVersion.z;
int? nextM = previousVersion.m;
int? nextN = previousVersion.n;
if (nextVersionType == null) {
if (previousVersion.type == VersionType.latest) {
nextVersionType = VersionType.development;
} else {
nextVersionType = previousVersion.type;
}
}
switch (increment) {
case 'x':
// This was probably a mistake.
throw Exception('Incrementing x is not supported by this tool.');
case 'y':
// Dev release following a beta release.
nextY += 1;
nextZ = 0;
if (previousVersion.type != VersionType.stable) {
nextM = 0;
nextN = 0;
}
break;
case 'z':
// Hotfix to stable release.
assert(previousVersion.type == VersionType.stable);
nextZ += 1;
break;
case 'm':
// Regular dev release.
assert(previousVersion.type == VersionType.development);
nextM = nextM! + 1;
nextN = 0;
break;
case 'n':
// Hotfix to internal roll.
nextN = nextN! + 1;
break;
default:
throw Exception('Unknown increment level $increment.');
}
return Version(
x: nextX,
y: nextY,
z: nextZ,
m: nextM,
n: nextN,
type: nextVersionType,
);
}
/// Major version.
final int x;
/// Zero-indexed count of beta releases after a major release.
final int y;
/// Number of hotfix releases after a stable release.
final int z;
/// Zero-indexed count of dev releases after a beta release.
final int? m;
/// Number of hotfixes required to make a dev release.
final int? n;
/// Number of commits past last tagged dev release.
final int? commits;
final VersionType type;
@override
String toString() {
switch (type) {
case VersionType.stable:
return '$x.$y.$z';
case VersionType.development:
return '$x.$y.$z-$m.$n.pre';
case VersionType.latest:
return '$x.$y.$z-$m.$n.pre.$commits';
}
}
}

View File

@@ -1,155 +0,0 @@
// Copyright 2014 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 'package:args/command_runner.dart';
import 'package:dev_tools/candidates.dart';
import 'package:dev_tools/repository.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import '../../../packages/flutter_tools/test/src/fake_process_manager.dart';
import './common.dart';
void main() {
group('candidates command', () {
const String flutterRoot = '/flutter';
const String flutterBinPath = '$flutterRoot/bin/flutter';
const String checkoutsParentDirectory = '$flutterRoot/dev/tools/';
const String remoteName = 'origin';
late MemoryFileSystem fileSystem;
late FakePlatform platform;
late TestStdio stdio;
late FakeProcessManager processManager;
final String operatingSystem = const LocalPlatform().operatingSystem;
setUp(() {
stdio = TestStdio();
fileSystem = MemoryFileSystem.test();
});
CommandRunner<void> createRunner({
required Checkouts checkouts,
}) {
final CandidatesCommand command = CandidatesCommand(
checkouts: checkouts,
flutterRoot: fileSystem.directory(flutterRoot),
);
return CommandRunner<void>('clean-test', '')..addCommand(command);
}
test('prints only branches from targeted remote', () async {
const String currentVersion = '1.2.3';
const String branch = 'flutter-1.3-candidate.0';
processManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['git', 'fetch', remoteName],
),
const FakeCommand(
command: <String>[flutterBinPath, 'help'],
),
const FakeCommand(
command: <String>[flutterBinPath, '--version', '--machine'],
stdout: '{"frameworkVersion": "$currentVersion"}',
),
FakeCommand(
command: const <String>[
'git',
'branch',
'--no-color',
'--remotes',
'--list',
'$remoteName/*',
],
stdout: <String>[
'other-remote/flutter-5.0-candidate.0',
'$remoteName/$branch',
].join('\n'),
),
]);
final String pathSeparator = operatingSystem == 'windows' ? r'\' : '/';
platform = FakePlatform(
environment: <String, String>{
'HOME': <String>['path', 'to', 'home'].join(pathSeparator),
},
pathSeparator: pathSeparator,
);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(checkoutsParentDirectory),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final CommandRunner<void> runner = createRunner(checkouts: checkouts);
await runner.run(<String>['candidates', '--$kRemote', remoteName]);
expect(stdio.stdout.contains('currentVersion = $currentVersion'), true);
expect(stdio.stdout.contains(branch), true);
expect(stdio.stdout.contains('flutter-5.0-candidate.0'), false);
});
test('does not print branches older or equal to current version', () async {
const String currentVersion = '2.3.0-13.0.pre.48';
const String newBranch = 'flutter-2.4-candidate.0';
const String oldBranch = 'flutter-1.0-candidate.0';
const String currentBranch = 'flutter-2.3-candidate.13';
processManager = FakeProcessManager.list(<FakeCommand>[
const FakeCommand(
command: <String>['git', 'fetch', remoteName],
),
const FakeCommand(
command: <String>[flutterBinPath, 'help'],
),
const FakeCommand(
command: <String>[flutterBinPath, '--version', '--machine'],
stdout: '{"frameworkVersion": "$currentVersion"}',
),
FakeCommand(
command: const <String>[
'git',
'branch',
'--no-color',
'--remotes',
'--list',
'$remoteName/*',
],
stdout: <String>[
'$remoteName/$oldBranch',
'$remoteName/$currentBranch',
'$remoteName/$newBranch',
].join('\n'),
),
]);
final String pathSeparator = operatingSystem == 'windows' ? r'\' : '/';
platform = FakePlatform(
environment: <String, String>{
'HOME': <String>['path', 'to', 'home'].join(pathSeparator),
},
pathSeparator: pathSeparator,
);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(checkoutsParentDirectory),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final CommandRunner<void> runner = createRunner(checkouts: checkouts);
await runner.run(<String>['candidates', '--$kRemote', remoteName]);
expect(stdio.stdout.contains('currentVersion = $currentVersion'), true);
expect(stdio.stdout.contains(newBranch), true);
expect(stdio.stdout.contains(oldBranch), false);
expect(stdio.stdout.contains(currentBranch), false);
print(stdio.stdout);
});
}, onPlatform: <String, dynamic>{
'windows': const Skip('Flutter Conductor only supported on macos/linux'),
});
}

View File

@@ -1,99 +0,0 @@
// Copyright 2014 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.
// @dart = 2.8
import 'package:args/command_runner.dart';
import 'package:dev_tools/clean.dart';
import 'package:dev_tools/repository.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import '../../../packages/flutter_tools/test/src/fake_process_manager.dart';
import './common.dart';
void main() {
group('clean command', () {
const String flutterRoot = '/flutter';
const String checkoutsParentDirectory = '$flutterRoot/dev/tools/';
MemoryFileSystem fileSystem;
FakePlatform platform;
TestStdio stdio;
FakeProcessManager processManager;
setUp(() {
stdio = TestStdio();
fileSystem = MemoryFileSystem.test();
});
tearDown(() {
// Ensure these don't get re-used between tests
stdio = null;
fileSystem = null;
processManager = null;
platform = null;
});
CommandRunner<void> createRunner({
List<FakeCommand> commands,
String operatingSystem,
}) {
operatingSystem ??= const LocalPlatform().operatingSystem;
final String pathSeparator = operatingSystem == 'windows' ? r'\' : '/';
processManager = FakeProcessManager.list(commands ?? <FakeCommand>[]);
platform = FakePlatform(
environment: <String, String>{'HOME': '/path/to/user/home'},
pathSeparator: pathSeparator,
);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(checkoutsParentDirectory),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final CleanCommand command = CleanCommand(
checkouts: checkouts,
);
return CommandRunner<void>('clean-test', '')..addCommand(command);
}
test('throws if no state file found', () async {
final CommandRunner<void> runner = createRunner();
const String stateFile = '/state-file.json';
await expectLater(
() async => runner.run(<String>[
'clean',
'--$kStateOption',
stateFile,
'--$kYesFlag',
]),
throwsExceptionWith(
'No persistent state file found at $stateFile',
),
);
});
test('deletes state file', () async {
final CommandRunner<void> runner = createRunner();
final File stateFile = fileSystem.file('/state-file.json');
stateFile.writeAsStringSync('{}');
await runner.run(<String>[
'clean',
'--$kStateOption',
stateFile.path,
'--$kYesFlag',
]);
expect(stateFile.existsSync(), false);
});
}, onPlatform: <String, dynamic>{
'windows': const Skip('Flutter Conductor only supported on macos/linux'),
});
}

View File

@@ -1,72 +0,0 @@
// Copyright 2014 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 'package:args/command_runner.dart';
import 'package:dev_tools/codesign.dart' show CodesignCommand;
import 'package:dev_tools/globals.dart';
import 'package:dev_tools/repository.dart' show Checkouts;
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:platform/platform.dart';
import 'package:process/process.dart';
import './common.dart';
/// Verify all binaries in the Flutter cache are expected by Conductor.
void main() {
test(
'validate the expected binaries from the conductor codesign command are present in the cache',
() async {
const Platform platform = LocalPlatform();
const FileSystem fileSystem = LocalFileSystem();
final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_conductor_integration_test.');
const ProcessManager processManager = LocalProcessManager();
final TestStdio stdio = TestStdio(verbose: true);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: tempDir,
platform: platform,
processManager: processManager,
stdio: stdio,
);
final CommandRunner<void> runner = CommandRunner<void>('codesign-test', '')
..addCommand(
CodesignCommand(checkouts: checkouts, flutterRoot: localFlutterRoot));
try {
await runner.run(<String>[
'codesign',
'--verify',
// Only verify if the correct binaries are in the cache
'--no-signatures',
]);
} on ConductorException catch (e) {
print(stdio.error);
print(fixItInstructions);
fail(e.message);
} on Exception {
print('stdout:\n${stdio.stdout}');
print('stderr:\n${stdio.error}');
rethrow;
}
}, onPlatform: <String, dynamic>{
'windows': const Skip('codesign command is only supported on macos'),
'linux': const Skip('codesign command is only supported on macos'),
});
}
const String fixItInstructions = '''
Codesign integration test failed.
This means that the binary files found in the Flutter cache do not match those
expected by the conductor tool (either an expected file was not found in the
cache or an unexpected file was found in the cache).
This usually happens either during an engine roll or a change to the caching
logic in flutter_tools. If this is a valid change, then the conductor source
code should be updated, specifically either the [binariesWithEntitlements] or
[binariesWithoutEntitlements] lists, depending on if the file should have macOS
entitlements applied during codesigning.
''';

View File

@@ -1,423 +0,0 @@
// Copyright 2014 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 'package:args/command_runner.dart';
import 'package:dev_tools/codesign.dart';
import 'package:dev_tools/globals.dart';
import 'package:dev_tools/repository.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import '../../../packages/flutter_tools/test/src/fake_process_manager.dart';
import './common.dart';
void main() {
group('codesign command', () {
const String flutterRoot = '/flutter';
const String checkoutsParentDirectory = '$flutterRoot/dev/tools/';
const String flutterCache =
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework/bin/cache';
const String flutterBin =
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework/bin/flutter';
const String revision = 'abcd1234';
late CommandRunner<void> runner;
late Checkouts checkouts;
late MemoryFileSystem fileSystem;
late FakePlatform platform;
late TestStdio stdio;
late FakeProcessManager processManager;
const List<String> binariesWithEntitlements = <String>[
'$flutterCache/dart-sdk/bin/dart',
'$flutterCache/dart-sdk/bin/dartaotruntime',
];
const List<String> binariesWithoutEntitlements = <String>[
'$flutterCache/engine/darwin-x64/font-subset',
];
const List<String> allBinaries = <String>[
...binariesWithEntitlements,
...binariesWithoutEntitlements,
];
void createRunner({
String operatingSystem = 'macos',
List<FakeCommand>? commands,
}) {
stdio = TestStdio();
fileSystem = MemoryFileSystem.test();
platform = FakePlatform(operatingSystem: operatingSystem);
processManager = FakeProcessManager.list(commands ?? <FakeCommand>[]);
checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(checkoutsParentDirectory),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final FakeCodesignCommand command = FakeCodesignCommand(
checkouts: checkouts,
binariesWithEntitlements: binariesWithEntitlements,
binariesWithoutEntitlements: binariesWithoutEntitlements,
flutterRoot: fileSystem.directory(flutterRoot),
);
runner = CommandRunner<void>('codesign-test', '')
..addCommand(command);
}
test('throws exception if not run from macos', () async {
createRunner(operatingSystem: 'linux');
expect(
() async => runner.run(<String>['codesign']),
throwsExceptionWith('Error! Expected operating system "macos"'),
);
});
test('throws exception if verify flag is not provided', () async {
createRunner();
expect(
() async => runner.run(<String>['codesign']),
throwsExceptionWith(
'Sorry, but codesigning is not implemented yet. Please pass the --$kVerify flag to verify signatures'),
);
});
test('succeeds if every binary is codesigned and has correct entitlements', () async {
final List<FakeCommand> codesignCheckCommands = <FakeCommand>[];
for (final String bin in binariesWithEntitlements) {
codesignCheckCommands.add(
FakeCommand(
command: <String>['codesign', '-vvv', bin],
),
);
codesignCheckCommands.add(
FakeCommand(
command: <String>['codesign', '--display', '--entitlements', ':-', bin],
stdout: expectedEntitlements.join('\n'),
),
);
}
for (final String bin in binariesWithoutEntitlements) {
codesignCheckCommands.add(
FakeCommand(
command: <String>['codesign', '-vvv', bin],
),
);
}
createRunner(commands: <FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
'file://$flutterRoot/',
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: revision),
const FakeCommand(command: <String>[
'git',
'checkout',
revision,
]),
const FakeCommand(command: <String>[
flutterBin,
'help',
]),
const FakeCommand(command: <String>[
flutterBin,
'help',
]),
const FakeCommand(command: <String>[
flutterBin,
'precache',
'--android',
'--ios',
'--macos',
]),
FakeCommand(
command: const <String>[
'find',
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework/bin/cache',
'-type',
'f',
],
stdout: allBinaries.join('\n'),
),
for (String bin in allBinaries)
FakeCommand(
command: <String>['file', '--mime-type', '-b', bin],
stdout: 'application/x-mach-binary',
),
...codesignCheckCommands,
]);
await runner.run(<String>['codesign', '--$kVerify', '--$kRevision', revision]);
expect(processManager.hasRemainingExpectations, false);
});
test('fails if a single binary is not codesigned', () async {
final List<FakeCommand> codesignCheckCommands = <FakeCommand>[];
codesignCheckCommands.add(
const FakeCommand(
command: <String>['codesign', '-vvv', '$flutterCache/dart-sdk/bin/dart'],
),
);
codesignCheckCommands.add(
FakeCommand(
command: const <String>[
'codesign',
'--display',
'--entitlements',
':-',
'$flutterCache/dart-sdk/bin/dart',
],
stdout: expectedEntitlements.join('\n'),
)
);
// Not signed
codesignCheckCommands.add(
const FakeCommand(
command: <String>['codesign', '-vvv', '$flutterCache/dart-sdk/bin/dartaotruntime'],
exitCode: 1,
),
);
codesignCheckCommands.add(
const FakeCommand(
command: <String>['codesign', '-vvv', '$flutterCache/engine/darwin-x64/font-subset'],
),
);
createRunner(commands: <FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
'file://$flutterRoot/',
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: revision),
const FakeCommand(command: <String>[
'git',
'checkout',
revision,
]),
const FakeCommand(command: <String>[
flutterBin,
'help',
]),
const FakeCommand(command: <String>[
flutterBin,
'help',
]),
const FakeCommand(command: <String>[
flutterBin,
'precache',
'--android',
'--ios',
'--macos',
]),
FakeCommand(
command: const <String>[
'find',
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework/bin/cache',
'-type',
'f',
],
stdout: allBinaries.join('\n'),
),
for (String bin in allBinaries)
FakeCommand(
command: <String>['file', '--mime-type', '-b', bin],
stdout: 'application/x-mach-binary',
),
...codesignCheckCommands,
]);
expect(
() async => runner.run(<String>['codesign', '--$kVerify', '--$kRevision', revision]),
throwsExceptionWith('Test failed because unsigned binaries detected.'),
);
expect(processManager.hasRemainingExpectations, false);
});
test('fails if a single binary has the wrong entitlements', () async {
final List<FakeCommand> codesignCheckCommands = <FakeCommand>[];
codesignCheckCommands.add(
const FakeCommand(
command: <String>['codesign', '-vvv', '$flutterCache/dart-sdk/bin/dart'],
),
);
codesignCheckCommands.add(
FakeCommand(
command: const <String>['codesign', '--display', '--entitlements', ':-', '$flutterCache/dart-sdk/bin/dart'],
stdout: expectedEntitlements.join('\n'),
)
);
codesignCheckCommands.add(
const FakeCommand(
command: <String>['codesign', '-vvv', '$flutterCache/dart-sdk/bin/dartaotruntime'],
),
);
// No entitlements
codesignCheckCommands.add(
const FakeCommand(
command: <String>['codesign', '--display', '--entitlements', ':-', '$flutterCache/dart-sdk/bin/dartaotruntime'],
)
);
codesignCheckCommands.add(
const FakeCommand(
command: <String>['codesign', '-vvv', '$flutterCache/engine/darwin-x64/font-subset'],
),
);
createRunner(commands: <FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
'file://$flutterRoot/',
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: revision),
const FakeCommand(command: <String>[
'git',
'checkout',
revision,
]),
const FakeCommand(command: <String>[
flutterBin,
'help',
]),
const FakeCommand(command: <String>[
flutterBin,
'help',
]),
const FakeCommand(command: <String>[
flutterBin,
'precache',
'--android',
'--ios',
'--macos',
]),
FakeCommand(
command: const <String>[
'find',
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework/bin/cache',
'-type',
'f',
],
stdout: allBinaries.join('\n'),
),
for (String bin in allBinaries)
FakeCommand(
command: <String>['file', '--mime-type', '-b', bin],
stdout: 'application/x-mach-binary',
),
...codesignCheckCommands,
]);
expect(
() async => runner.run(<String>['codesign', '--$kVerify', '--$kRevision', revision]),
throwsExceptionWith('Test failed because files found with the wrong entitlements'),
);
expect(processManager.hasRemainingExpectations, false);
});
test('does not check signatures or entitlements if --no-$kSignatures specified', () async {
createRunner(commands: <FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
'file://$flutterRoot/',
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: revision),
const FakeCommand(command: <String>[
'git',
'checkout',
revision,
]),
const FakeCommand(command: <String>[
flutterBin,
'help',
]),
const FakeCommand(command: <String>[
flutterBin,
'help',
]),
const FakeCommand(command: <String>[
flutterBin,
'precache',
'--android',
'--ios',
'--macos',
]),
FakeCommand(
command: const <String>[
'find',
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework/bin/cache',
'-type',
'f',
],
stdout: allBinaries.join('\n'),
),
for (String bin in allBinaries)
FakeCommand(
command: <String>['file', '--mime-type', '-b', bin],
stdout: 'application/x-mach-binary',
),
]);
try {
await runner.run(<String>[
'codesign',
'--$kVerify',
'--no-$kSignatures',
'--$kRevision',
revision,
]);
} on ConductorException {
//print(stdio.error);
rethrow;
}
expect(
processManager.hasRemainingExpectations,
false,
);
});
});
}
class FakeCodesignCommand extends CodesignCommand {
FakeCodesignCommand({
required Checkouts checkouts,
required this.binariesWithEntitlements,
required this.binariesWithoutEntitlements,
required Directory flutterRoot,
}) : super(checkouts: checkouts, flutterRoot: flutterRoot);
@override
final List<String> binariesWithEntitlements;
@override
final List<String> binariesWithoutEntitlements;
}

View File

@@ -1,115 +0,0 @@
// Copyright 2014 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 'package:args/args.dart';
import 'package:dev_tools/stdio.dart';
import 'package:file/file.dart';
import 'package:test/test.dart';
export 'package:test/test.dart' hide isInstanceOf;
/// A matcher that compares the type of the actual value to the type argument T.
TypeMatcher<T> isInstanceOf<T>() => isA<T>();
void tryToDelete(Directory directory) {
// 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 {
directory.deleteSync(recursive: true);
} on FileSystemException catch (error) {
print('Failed to delete ${directory.path}: $error');
}
}
Matcher throwsExceptionWith(String messageSubString) {
return throwsA(
isA<Exception>().having(
(Exception e) => e.toString(),
'description',
contains(messageSubString),
),
);
}
class TestStdio extends Stdio {
TestStdio({
this.verbose = false,
List<String>? stdin,
}) : _stdin = stdin ?? <String>[];
String get error => logs.where((String log) => log.startsWith(r'[error] ')).join('\n');
String get stdout => logs.where((String log) {
return log.startsWith(r'[status] ') || log.startsWith(r'[trace] ');
}).join('\n');
final bool verbose;
late final List<String> _stdin;
@override
String readLineSync() {
if (_stdin.isEmpty) {
throw Exception('Unexpected call to readLineSync!');
}
return _stdin.removeAt(0);
}
}
class FakeArgResults implements ArgResults {
FakeArgResults({
required String level,
required String commit,
String remote = 'upstream',
bool justPrint = false,
bool autoApprove = true, // so we don't have to mock stdin
bool help = false,
bool force = false,
bool skipTagging = false,
}) : _parsedArgs = <String, dynamic>{
'increment': level,
'commit': commit,
'remote': remote,
'just-print': justPrint,
'yes': autoApprove,
'help': help,
'force': force,
'skip-tagging': skipTagging,
};
@override
String? name;
@override
ArgResults? command;
@override
final List<String> rest = <String>[];
@override
List<String> get arguments {
assert(false, 'not yet implemented');
return <String>[];
}
final Map<String, dynamic> _parsedArgs;
@override
Iterable<String> get options {
assert(false, 'not yet implemented');
return <String>[];
}
@override
dynamic operator [](String name) {
return _parsedArgs[name];
}
@override
bool wasParsed(String name) {
assert(false, 'not yet implemented');
return false;
}
}

View File

@@ -1,297 +0,0 @@
// Copyright 2014 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 'package:dev_tools/repository.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import '../../../packages/flutter_tools/test/src/fake_process_manager.dart';
import './common.dart';
void main() {
group('repository', () {
late FakePlatform platform;
const String rootDir = '/';
setUp(() {
final String pathSeparator = const LocalPlatform().pathSeparator;
platform = FakePlatform(
environment: <String, String>{
'HOME': <String>['path', 'to', 'home'].join(pathSeparator),
},
pathSeparator: pathSeparator,
);
});
test('canCherryPick returns true if git cherry-pick returns 0', () {
const String commit = 'abc123';
final TestStdio stdio = TestStdio();
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final FakeProcessManager processManager =
FakeProcessManager.list(<FakeCommand>[
FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
fileSystem.path
.join(rootDir, 'flutter_conductor_checkouts', 'framework'),
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
const FakeCommand(command: <String>[
'git',
'cherry-pick',
'--no-commit',
commit,
], exitCode: 0),
const FakeCommand(command: <String>[
'git',
'reset',
'HEAD',
'--hard',
]),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final Repository repository = FrameworkRepository(checkouts);
expect(repository.canCherryPick(commit), true);
});
test('canCherryPick returns false if git cherry-pick returns non-zero', () {
const String commit = 'abc123';
final TestStdio stdio = TestStdio();
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final FakeProcessManager processManager =
FakeProcessManager.list(<FakeCommand>[
FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
fileSystem.path
.join(rootDir, 'flutter_conductor_checkouts', 'framework'),
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
const FakeCommand(command: <String>[
'git',
'cherry-pick',
'--no-commit',
commit,
], exitCode: 1),
const FakeCommand(command: <String>[
'git',
'diff',
]),
const FakeCommand(command: <String>[
'git',
'reset',
'HEAD',
'--hard',
]),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final Repository repository = FrameworkRepository(checkouts);
expect(repository.canCherryPick(commit), false);
});
test('cherryPick() applies the commit', () {
const String commit = 'abc123';
final TestStdio stdio = TestStdio();
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final FakeProcessManager processManager =
FakeProcessManager.list(<FakeCommand>[
FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
fileSystem.path
.join(rootDir, 'flutter_conductor_checkouts', 'framework'),
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
const FakeCommand(command: <String>[
'git',
'cherry-pick',
commit,
]),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final Repository repository = FrameworkRepository(checkouts);
repository.cherryPick(commit);
expect(processManager.hasRemainingExpectations, false);
});
test('updateDartRevision() updates the DEPS file', () {
const String previousDartRevision = '171876a4e6cf56ee6da1f97d203926bd7afda7ef';
const String nextDartRevision = 'f6c91128be6b77aef8351e1e3a9d07c85bc2e46e';
final TestStdio stdio = TestStdio();
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final FakeProcessManager processManager = FakeProcessManager.empty();
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final EngineRepository repo = EngineRepository(checkouts);
final File depsFile = fileSystem.file('/DEPS');
depsFile.writeAsStringSync(generateMockDeps(previousDartRevision));
repo.updateDartRevision(nextDartRevision, depsFile: depsFile);
final String updatedDepsFileContent = depsFile.readAsStringSync();
expect(updatedDepsFileContent, generateMockDeps(nextDartRevision));
});
test('updateDartRevision() throws exception on malformed DEPS file', () {
const String nextDartRevision = 'f6c91128be6b77aef8351e1e3a9d07c85bc2e46e';
final TestStdio stdio = TestStdio();
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final FakeProcessManager processManager = FakeProcessManager.empty();
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final EngineRepository repo = EngineRepository(checkouts);
final File depsFile = fileSystem.file('/DEPS');
depsFile.writeAsStringSync('''
vars = {
}''');
expect(
() => repo.updateDartRevision(nextDartRevision, depsFile: depsFile),
throwsExceptionWith('Unexpected content in the DEPS file at'),
);
});
test('commit() passes correct commit message', () {
const String commit1 = 'abc123';
const String commit2 = 'def456';
const String message = 'This is a commit message.';
final TestStdio stdio = TestStdio();
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
EngineRepository.defaultUpstream,
fileSystem.path
.join(rootDir, 'flutter_conductor_checkouts', 'engine'),
]),
const FakeCommand(command: <String>[
'git',
'checkout',
'upstream/master',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit1),
const FakeCommand(command: <String>[
'git',
'commit',
"--message='$message'",
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit2),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final EngineRepository repo = EngineRepository(checkouts);
repo.commit(message);
});
});
}
String generateMockDeps(String dartRevision) {
return '''
vars = {
'chromium_git': 'https://chromium.googlesource.com',
'swiftshader_git': 'https://swiftshader.googlesource.com',
'dart_git': 'https://dart.googlesource.com',
'flutter_git': 'https://flutter.googlesource.com',
'fuchsia_git': 'https://fuchsia.googlesource.com',
'github_git': 'https://github.com',
'skia_git': 'https://skia.googlesource.com',
'ocmock_git': 'https://github.com/erikdoe/ocmock.git',
'skia_revision': '4e9d5e2bdf04c58bc0bff57be7171e469e5d7175',
'dart_revision': '$dartRevision',
'dart_boringssl_gen_rev': '7322fc15cc065d8d2957fccce6b62a509dc4d641',
}''';
}

View File

@@ -1,91 +0,0 @@
// Copyright 2014 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 'package:dev_tools/repository.dart';
import 'package:dev_tools/roll_dev.dart' show rollDev;
import 'package:dev_tools/version.dart';
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:platform/platform.dart';
import 'package:process/process.dart';
import './common.dart';
void main() {
group('roll-dev', () {
late TestStdio stdio;
late Platform platform;
late ProcessManager processManager;
late FileSystem fileSystem;
const String usageString = 'Usage: flutter conductor.';
late Checkouts checkouts;
late FrameworkRepository frameworkUpstream;
late FrameworkRepository framework;
late Directory tempDir;
setUp(() {
platform = const LocalPlatform();
fileSystem = const LocalFileSystem();
processManager = const LocalProcessManager();
stdio = TestStdio(verbose: true);
tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_conductor_checkouts.');
checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: tempDir,
platform: platform,
processManager: processManager,
stdio: stdio,
);
frameworkUpstream = FrameworkRepository(checkouts, localUpstream: true);
// This repository has [frameworkUpstream] set as its push/pull remote.
framework = FrameworkRepository(
checkouts,
name: 'test-framework',
fetchRemote: Remote(name: RemoteName.upstream, url: 'file://${frameworkUpstream.checkoutDirectory.path}/'),
);
});
test('increment m', () {
final Version initialVersion = framework.flutterVersion();
final String latestCommit = framework.authorEmptyCommit();
final FakeArgResults fakeArgResults = FakeArgResults(
level: 'm',
commit: latestCommit,
// Ensure this test passes after a dev release with hotfixes
force: true,
remote: 'upstream',
);
expect(
rollDev(
usage: usageString,
argResults: fakeArgResults,
stdio: stdio,
repository: framework,
),
true,
);
expect(
stdio.stdout,
contains(RegExp(r'Publishing Flutter \d+\.\d+\.\d+-\d+\.\d+\.pre \(')),
);
final Version finalVersion = framework.flutterVersion();
expect(
initialVersion.toString() != finalVersion.toString(),
true,
reason: 'initialVersion = $initialVersion; finalVersion = $finalVersion',
);
expect(finalVersion.n, 0);
expect(finalVersion.commits, null);
});
}, onPlatform: <String, dynamic>{
'windows': const Skip('Flutter Conductor only supported on macos/linux'),
});
}

View File

@@ -1,732 +0,0 @@
// Copyright 2014 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.
// @dart = 2.8
import 'package:dev_tools/globals.dart';
import 'package:dev_tools/repository.dart';
import 'package:dev_tools/roll_dev.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import '../../../packages/flutter_tools/test/src/fake_process_manager.dart';
import './common.dart';
void main() {
group('rollDev()', () {
const String usage = 'usage info...';
const String level = 'm';
const String commit = 'abcde012345';
const String remote = 'origin';
const String lastVersion = '1.2.0-0.0.pre';
const String nextVersion = '1.2.0-1.0.pre';
const String checkoutsParentDirectory = '/path/to/directory/';
FakeArgResults fakeArgResults;
MemoryFileSystem fileSystem;
TestStdio stdio;
FrameworkRepository repo;
Checkouts checkouts;
FakePlatform platform;
FakeProcessManager processManager;
setUp(() {
stdio = TestStdio();
fileSystem = MemoryFileSystem.test();
platform = FakePlatform();
processManager = FakeProcessManager.list(<FakeCommand>[]);
checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(checkoutsParentDirectory),
platform: platform,
processManager: processManager,
stdio: stdio,
);
repo = FrameworkRepository(checkouts);
});
test('returns false if level not provided', () {
fakeArgResults = FakeArgResults(
level: null,
commit: commit,
remote: remote,
);
expect(
rollDev(
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
usage: usage,
),
false,
);
});
test('returns false if commit not provided', () {
fakeArgResults = FakeArgResults(
level: level,
commit: null,
remote: remote,
);
expect(
rollDev(
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
usage: usage,
),
false,
);
});
test('throws exception if git checkout not clean', () {
processManager.addCommands(<FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
kUpstreamRemote,
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'remote',
'get-url',
remote,
], stdout: kUpstreamRemote),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
], stdout: ' M dev/conductor/bin/conductor.dart'),
]);
fakeArgResults = FakeArgResults(
level: level,
commit: commit,
remote: remote,
);
Exception exception;
try {
rollDev(
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
usage: usage,
);
} on Exception catch (e) {
exception = e;
}
const String pattern = r'Your git repository is not clean. Try running '
'"git clean -fd". Warning, this will delete files! Run with -n to find '
'out which ones.';
expect(exception?.toString(), contains(pattern));
});
test('does not reset or tag if --just-print is specified', () {
processManager.addCommands(<FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
kUpstreamRemote,
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'remote',
'get-url',
remote,
], stdout: kUpstreamRemote),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
const FakeCommand(command: <String>[
'git',
'fetch',
remote,
'--tags',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
commit,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*-*.*.pre',
'--exact-match',
'--tags',
'refs/remotes/$remote/dev',
], stdout: lastVersion),
const FakeCommand(command: <String>[
'git',
'rev-parse',
lastVersion,
], stdout: 'zxy321'),
]);
fakeArgResults = FakeArgResults(
level: level,
commit: commit,
remote: remote,
justPrint: true,
);
expect(
rollDev(
usage: usage,
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
),
false,
);
expect(stdio.logs.join('').contains(nextVersion), true);
});
test("exits with exception if --skip-tagging is provided but commit isn't already tagged", () {
processManager.addCommands(<FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
kUpstreamRemote,
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'remote',
'get-url',
remote,
], stdout: kUpstreamRemote),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
const FakeCommand(command: <String>[
'git',
'fetch',
remote,
'--tags',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
commit,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*-*.*.pre',
'--exact-match',
'--tags',
'refs/remotes/$remote/dev',
], stdout: lastVersion),
const FakeCommand(command: <String>[
'git',
'rev-parse',
lastVersion,
], stdout: 'zxy321'),
const FakeCommand(command: <String>[
'git',
'describe',
'--exact-match',
'--tags',
commit,
], exitCode: 1),
]);
const String exceptionMessage =
'The $kSkipTagging flag is only supported '
'for tagged commits.';
fakeArgResults = FakeArgResults(
level: level,
commit: commit,
remote: remote,
skipTagging: true,
);
expect(
() => rollDev(
usage: usage,
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
),
throwsExceptionWith(exceptionMessage),
);
});
test('throws exception if desired commit is already tip of dev branch', () {
processManager.addCommands(<FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
kUpstreamRemote,
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'remote',
'get-url',
remote,
], stdout: kUpstreamRemote),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
const FakeCommand(command: <String>[
'git',
'fetch',
remote,
'--tags',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
commit,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*-*.*.pre',
'--exact-match',
'--tags',
'refs/remotes/$remote/dev',
], stdout: lastVersion),
// [commit] is already [lastVersion]
const FakeCommand(command: <String>[
'git',
'rev-parse',
lastVersion,
], stdout: commit),
]);
fakeArgResults = FakeArgResults(
level: level,
commit: commit,
remote: remote,
justPrint: true,
);
expect(
() => rollDev(
usage: usage,
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
),
throwsExceptionWith(
'Commit $commit is already on the dev branch as $lastVersion',
),
);
});
test(
'does not tag if last release is not direct ancestor of desired '
'commit and --force not supplied', () {
processManager.addCommands(<FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
kUpstreamRemote,
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'remote',
'get-url',
remote,
], stdout: kUpstreamRemote),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
const FakeCommand(command: <String>[
'git',
'fetch',
remote,
'--tags',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
commit,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*-*.*.pre',
'--exact-match',
'--tags',
'refs/remotes/$remote/dev',
], stdout: lastVersion),
const FakeCommand(command: <String>[
'git',
'rev-parse',
lastVersion,
], stdout: 'zxy321'),
const FakeCommand(command: <String>[
'git',
'merge-base',
'--is-ancestor',
lastVersion,
commit,
], exitCode: 1),
]);
fakeArgResults = FakeArgResults(
level: level,
commit: commit,
remote: remote,
);
const String errorMessage = 'The previous dev tag $lastVersion is not a '
'direct ancestor of $commit.';
expect(
() => rollDev(
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
usage: usage,
),
throwsExceptionWith(errorMessage),
);
});
test('does not tag but updates branch if --skip-tagging provided', () {
processManager.addCommands(<FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
kUpstreamRemote,
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'remote',
'get-url',
remote,
], stdout: kUpstreamRemote),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
const FakeCommand(command: <String>[
'git',
'fetch',
remote,
'--tags',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
commit,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*-*.*.pre',
'--exact-match',
'--tags',
'refs/remotes/$remote/dev',
], stdout: lastVersion),
const FakeCommand(command: <String>[
'git',
'rev-parse',
lastVersion,
], stdout: 'zxy321'),
const FakeCommand(command: <String>[
'git',
'describe',
'--exact-match',
'--tags',
commit,
]),
const FakeCommand(command: <String>[
'git',
'merge-base',
'--is-ancestor',
lastVersion,
commit,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
commit,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'push',
remote,
'$commit:dev',
]),
]);
fakeArgResults = FakeArgResults(
level: level,
commit: commit,
remote: remote,
skipTagging: true,
);
expect(
rollDev(
usage: usage,
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
),
true,
);
});
test('successfully tags and publishes release', () {
processManager.addCommands(<FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
kUpstreamRemote,
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'remote',
'get-url',
remote,
], stdout: kUpstreamRemote),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
const FakeCommand(command: <String>[
'git',
'fetch',
remote,
'--tags',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
commit,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*-*.*.pre',
'--exact-match',
'--tags',
'refs/remotes/$remote/dev',
], stdout: lastVersion),
const FakeCommand(command: <String>[
'git',
'rev-parse',
lastVersion,
], stdout: 'zxy321'),
const FakeCommand(command: <String>[
'git',
'merge-base',
'--is-ancestor',
lastVersion,
commit,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
commit,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'tag',
nextVersion,
commit,
]),
const FakeCommand(command: <String>[
'git',
'push',
remote,
nextVersion,
]),
const FakeCommand(command: <String>[
'git',
'push',
remote,
'$commit:dev',
]),
]);
fakeArgResults = FakeArgResults(
level: level,
commit: commit,
remote: remote,
);
expect(
rollDev(
usage: usage,
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
),
true,
);
});
test('successfully publishes release with --force', () {
processManager.addCommands(<FakeCommand>[
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
kUpstreamRemote,
'${checkoutsParentDirectory}flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'remote',
'get-url',
remote,
], stdout: kUpstreamRemote),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
const FakeCommand(command: <String>[
'git',
'fetch',
remote,
'--tags',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
commit,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*-*.*.pre',
'--exact-match',
'--tags',
'refs/remotes/$remote/dev',
], stdout: lastVersion),
const FakeCommand(command: <String>[
'git',
'rev-parse',
lastVersion,
], stdout: 'zxy321'),
const FakeCommand(command: <String>[
'git',
'rev-parse',
commit,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'tag',
nextVersion,
commit,
]),
const FakeCommand(command: <String>[
'git',
'push',
remote,
nextVersion,
]),
const FakeCommand(command: <String>[
'git',
'push',
'--force',
remote,
'$commit:dev',
]),
]);
fakeArgResults = FakeArgResults(
level: level,
commit: commit,
remote: remote,
force: true,
);
expect(
rollDev(
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
usage: usage,
),
true,
);
expect(processManager.hasRemainingExpectations, false);
});
}, onPlatform: <String, dynamic>{
'windows': const Skip('Flutter Conductor only supported on macos/linux'),
});
}

View File

@@ -1,297 +0,0 @@
// Copyright 2014 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.
// @dart = 2.8
import 'dart:convert' show jsonDecode;
import 'package:args/command_runner.dart';
import 'package:dev_tools/proto/conductor_state.pb.dart' as pb;
import 'package:dev_tools/proto/conductor_state.pbenum.dart' show ReleasePhase;
import 'package:dev_tools/repository.dart';
import 'package:dev_tools/start.dart';
import 'package:dev_tools/state.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import '../../../packages/flutter_tools/test/src/fake_process_manager.dart';
import './common.dart';
void main() {
group('start command', () {
const String flutterRoot = '/flutter';
const String checkoutsParentDirectory = '$flutterRoot/dev/tools/';
const String frameworkMirror = 'https://github.com/user/flutter.git';
const String engineMirror = 'https://github.com/user/engine.git';
const String candidateBranch = 'flutter-1.2-candidate.3';
const String releaseChannel = 'stable';
const String revision = 'abcd1234';
Checkouts checkouts;
MemoryFileSystem fileSystem;
FakePlatform platform;
TestStdio stdio;
FakeProcessManager processManager;
setUp(() {
stdio = TestStdio();
fileSystem = MemoryFileSystem.test();
});
CommandRunner<void> createRunner({
Map<String, String> environment,
String operatingSystem,
List<FakeCommand> commands,
}) {
operatingSystem ??= const LocalPlatform().operatingSystem;
final String pathSeparator = operatingSystem == 'windows' ? r'\' : '/';
environment ??= <String, String>{
'HOME': '/path/to/user/home',
};
final Directory homeDir = fileSystem.directory(
environment['HOME'],
);
// Tool assumes this exists
homeDir.createSync(recursive: true);
platform = FakePlatform(
environment: environment,
operatingSystem: operatingSystem,
pathSeparator: pathSeparator,
);
processManager = FakeProcessManager.list(commands ?? <FakeCommand>[]);
checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(checkoutsParentDirectory),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final StartCommand command = StartCommand(
checkouts: checkouts,
flutterRoot: fileSystem.directory(flutterRoot),
);
return CommandRunner<void>('codesign-test', '')..addCommand(command);
}
tearDown(() {
// Ensure we don't re-use these between tests.
processManager = null;
checkouts = null;
platform = null;
});
test('throws exception if run from Windows', () async {
final CommandRunner<void> runner = createRunner(
commands: <FakeCommand>[
const FakeCommand(
command: <String>['git', 'rev-parse', 'HEAD'],
stdout: revision,
),
],
operatingSystem: 'windows',
);
await expectLater(
() async => runner.run(<String>['start']),
throwsExceptionWith(
'Error! This tool is only supported on macOS and Linux',
),
);
});
test('throws if --$kFrameworkMirrorOption not provided', () async {
final CommandRunner<void> runner = createRunner(
commands: <FakeCommand>[
const FakeCommand(
command: <String>['git', 'rev-parse', 'HEAD'],
stdout: revision,
),
],
);
await expectLater(
() async => runner.run(<String>['start']),
throwsExceptionWith(
'Expected either the CLI arg --$kFrameworkMirrorOption or the environment variable FRAMEWORK_MIRROR to be provided',
),
);
});
test('creates state file if provided correct inputs', () async {
const String revision2 = 'def789';
const String revision3 = '123abc';
const String previousDartRevision = '171876a4e6cf56ee6da1f97d203926bd7afda7ef';
const String nextDartRevision = 'f6c91128be6b77aef8351e1e3a9d07c85bc2e46e';
final Directory engine = fileSystem.directory(checkoutsParentDirectory)
.childDirectory('flutter_conductor_checkouts')
.childDirectory('engine');
final File depsFile = engine.childFile('DEPS');
final List<FakeCommand> engineCommands = <FakeCommand>[
FakeCommand(
command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
EngineRepository.defaultUpstream,
engine.path,
],
onRun: () {
// Create the DEPS file which the tool will update
engine.createSync(recursive: true);
depsFile.writeAsStringSync(generateMockDeps(previousDartRevision));
}
),
const FakeCommand(
command: <String>['git', 'remote', 'add', 'mirror', engineMirror],
),
const FakeCommand(
command: <String>['git', 'fetch', 'mirror'],
),
const FakeCommand(
command: <String>['git', 'checkout', 'upstream/$candidateBranch'],
),
const FakeCommand(
command: <String>['git', 'rev-parse', 'HEAD'],
stdout: revision2,
),
const FakeCommand(
command: <String>[
'git',
'checkout',
'-b',
'cherrypicks-$candidateBranch',
],
),
const FakeCommand(
command: <String>['git', 'add', '--all'],
),
const FakeCommand(
command: <String>['git', 'commit', "--message='Update Dart SDK to $nextDartRevision'"],
),
const FakeCommand(
command: <String>['git', 'rev-parse', 'HEAD'],
stdout: revision2,
),
const FakeCommand(
command: <String>['git', 'rev-parse', 'HEAD'],
stdout: revision2,
),
];
final List<FakeCommand> frameworkCommands = <FakeCommand>[
FakeCommand(
command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
fileSystem.path.join(
checkoutsParentDirectory,
'flutter_conductor_checkouts',
'framework',
),
],
),
const FakeCommand(
command: <String>['git', 'remote', 'add', 'mirror', frameworkMirror],
),
const FakeCommand(
command: <String>['git', 'fetch', 'mirror'],
),
const FakeCommand(
command: <String>['git', 'checkout', 'upstream/$candidateBranch'],
),
const FakeCommand(
command: <String>['git', 'rev-parse', 'HEAD'],
stdout: revision3,
),
const FakeCommand(
command: <String>[
'git',
'checkout',
'-b',
'cherrypicks-$candidateBranch',
],
),
const FakeCommand(
command: <String>['git', 'rev-parse', 'HEAD'],
stdout: revision3,
),
];
final CommandRunner<void> runner = createRunner(
commands: <FakeCommand>[
const FakeCommand(
command: <String>['git', 'rev-parse', 'HEAD'],
stdout: revision,
),
...engineCommands,
...frameworkCommands,
],
);
final String stateFilePath = fileSystem.path.join(
platform.environment['HOME'],
kStateFileName,
);
await runner.run(<String>[
'start',
'--$kFrameworkMirrorOption',
frameworkMirror,
'--$kEngineMirrorOption',
engineMirror,
'--$kCandidateOption',
candidateBranch,
'--$kReleaseOption',
releaseChannel,
'--$kStateOption',
stateFilePath,
'--$kDartRevisionOption',
nextDartRevision,
]);
final File stateFile = fileSystem.file(stateFilePath);
final pb.ConductorState state = pb.ConductorState();
state.mergeFromProto3Json(
jsonDecode(stateFile.readAsStringSync()),
);
expect(state.isInitialized(), true);
expect(state.releaseChannel, releaseChannel);
expect(state.engine.candidateBranch, candidateBranch);
expect(state.engine.startingGitHead, revision2);
expect(state.engine.dartRevision, nextDartRevision);
expect(state.framework.candidateBranch, candidateBranch);
expect(state.framework.startingGitHead, revision3);
expect(state.lastPhase, ReleasePhase.INITIALIZE);
expect(state.conductorVersion, revision);
});
}, onPlatform: <String, dynamic>{
'windows': const Skip('Flutter Conductor only supported on macos/linux'),
});
}
String generateMockDeps(String dartRevision) {
return '''
vars = {
'chromium_git': 'https://chromium.googlesource.com',
'swiftshader_git': 'https://swiftshader.googlesource.com',
'dart_git': 'https://dart.googlesource.com',
'flutter_git': 'https://flutter.googlesource.com',
'fuchsia_git': 'https://fuchsia.googlesource.com',
'github_git': 'https://github.com',
'skia_git': 'https://skia.googlesource.com',
'ocmock_git': 'https://github.com/erikdoe/ocmock.git',
'skia_revision': '4e9d5e2bdf04c58bc0bff57be7171e469e5d7175',
'dart_revision': '$dartRevision',
'dart_boringssl_gen_rev': '7322fc15cc065d8d2957fccce6b62a509dc4d641',
}''';
}

View File

@@ -1,87 +0,0 @@
// Copyright 2014 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 'package:dev_tools/version.dart';
import './common.dart';
void main() {
group('Version.increment()', () {
test('throws exception on nonsensical `level`', () {
final List<String> levels = <String>['f', '0', 'xyz'];
for (final String level in levels) {
final Version version = Version.fromString('1.0.0-0.0.pre');
expect(
() => Version.increment(version, level).toString(),
throwsExceptionWith('Unknown increment level $level.'),
);
}
});
test('does not support incrementing x', () {
const String level = 'x';
final Version version = Version.fromString('1.0.0-0.0.pre');
expect(
() => Version.increment(version, level).toString(),
throwsExceptionWith(
'Incrementing $level is not supported by this tool'),
);
});
test('successfully increments y', () {
const String level = 'y';
Version version = Version.fromString('1.0.0-0.0.pre');
expect(Version.increment(version, level).toString(), '1.1.0-0.0.pre');
version = Version.fromString('10.20.0-40.50.pre');
expect(Version.increment(version, level).toString(), '10.21.0-0.0.pre');
version = Version.fromString('1.18.0-3.0.pre');
expect(Version.increment(version, level).toString(), '1.19.0-0.0.pre');
});
test('successfully increments z', () {
const String level = 'm';
Version version = Version.fromString('1.0.0-0.0.pre');
expect(Version.increment(version, level).toString(), '1.0.0-1.0.pre');
version = Version.fromString('10.20.0-40.50.pre');
expect(Version.increment(version, level).toString(), '10.20.0-41.0.pre');
version = Version.fromString('1.18.0-3.0.pre');
expect(Version.increment(version, level).toString(), '1.18.0-4.0.pre');
});
test('successfully increments m', () {
const String level = 'm';
Version version = Version.fromString('1.0.0-0.0.pre');
expect(Version.increment(version, level).toString(), '1.0.0-1.0.pre');
version = Version.fromString('10.20.0-40.50.pre');
expect(Version.increment(version, level).toString(), '10.20.0-41.0.pre');
version = Version.fromString('1.18.0-3.0.pre');
expect(Version.increment(version, level).toString(), '1.18.0-4.0.pre');
});
test('successfully increments n', () {
const String level = 'n';
Version version = Version.fromString('1.0.0-0.0.pre');
expect(Version.increment(version, level).toString(), '1.0.0-0.1.pre');
version = Version.fromString('10.20.0-40.50.pre');
expect(Version.increment(version, level).toString(), '10.20.0-40.51.pre');
version = Version.fromString('1.18.0-3.0.pre');
expect(Version.increment(version, level).toString(), '1.18.0-3.1.pre');
});
}, onPlatform: <String, dynamic>{
'windows': const Skip('Flutter Conductor only supported on macos/linux'),
});
}