[flutter_conductor] implement UI scaffold (#90621)

This commit is contained in:
Christopher Fujino
2021-09-24 15:30:09 -07:00
committed by GitHub
parent 08a30fdb92
commit 69ae50310b
82 changed files with 1883 additions and 54 deletions

View File

@@ -0,0 +1,15 @@
# Use the analysis options settings from the top level of the repo (not
# the ones from above, which include the `public_member_api_docs` rule).
include: ../../../analysis_options.yaml
analyzer:
exclude:
# Ignore protoc generated files
- "lib/src/proto/*"
linter:
rules:
avoid_catches_without_on_clauses: true
curly_braces_in_flow_control_structures: true
prefer_relative_imports: true
unawaited_futures: true

View File

@@ -0,0 +1,83 @@
// 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.
// See: https://github.com/flutter/flutter/wiki/Release-process
import 'dart:io' as io;
import 'package:args/command_runner.dart';
import 'package:conductor_core/conductor_core.dart';
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:platform/platform.dart';
import 'package:process/process.dart';
const String readmeUrl = 'https://github.com/flutter/flutter/tree/master/dev/conductor/README.md';
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. For more documentation on '
'usage, please see $readmeUrl.',
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,
),
NextCommand(
checkouts: checkouts,
),
].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

@@ -0,0 +1,6 @@
# codesign_integration_test takes longer than the default timeout which is 30s
# since it has to clone both the engine and framework repos, and that test is running
# asynchronously. The async function is being awaited more than 30s which counts as inactivity
# The default timeout needs to be extended to accomodate codesign_integration_test
timeout: 5m

View File

@@ -0,0 +1,17 @@
// 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.
// See: https://github.com/flutter/flutter/wiki/Release-process
export 'src/candidates.dart';
export 'src/clean.dart';
export 'src/codesign.dart';
export 'src/globals.dart';
export 'src/next.dart' hide kStateOption, kYesFlag;
export 'src/repository.dart';
export 'src/roll_dev.dart';
export 'src/start.dart' hide kStateOption;
export 'src/state.dart';
export 'src/status.dart' hide kStateOption;
export 'src/stdio.dart';

View File

@@ -0,0 +1,6 @@
// 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.
export 'src/proto/conductor_state.pb.dart';
export 'src/proto/conductor_state.pbenum.dart';

View File

@@ -0,0 +1,102 @@
// 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
Future<void> run() async {
final ArgResults results = argResults!;
await 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 = await framework.flutterVersion();
stdio.printStatus('currentVersion = $currentVersion');
final List<String> branches = (await 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

@@ -0,0 +1,76 @@
// 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: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 ArgResults argumentResults = argResults!;
final File stateFile = checkouts.fileSystem.file(argumentResults[kStateOption]);
if (!stateFile.existsSync()) {
throw ConductorException(
'No persistent state file found at ${stateFile.path}!');
}
if (!(argumentResults[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

@@ -0,0 +1,409 @@
// 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
Future<void> run() async {
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 = ((await processManager.run(
<String>['git', 'rev-parse', 'HEAD'],
workingDirectory: (await framework.checkoutDirectory).path,
)).stdout as String).trim();
assert(revision.isNotEmpty);
}
await framework.checkout(revision);
// Ensure artifacts present
await framework.runFlutter(<String>['precache', '--android', '--ios', '--macos']);
await verifyExist();
if (argResults![kSignatures] as bool) {
await 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.
Future<List<String>> get binariesWithEntitlements async {
final String frameworkCacheDirectory = await framework.cacheDirectory;
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(frameworkCacheDirectory, 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.
Future<List<String>> get binariesWithoutEntitlements async {
final String frameworkCacheDirectory = await framework.cacheDirectory;
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-arm64_armv7/Flutter.framework/Flutter',
'artifacts/engine/ios-profile/Flutter.xcframework/ios-arm64_x86_64-simulator/Flutter.framework/Flutter',
'artifacts/engine/ios-release/Flutter.xcframework/ios-arm64_armv7/Flutter.framework/Flutter',
'artifacts/engine/ios-release/Flutter.xcframework/ios-arm64_x86_64-simulator/Flutter.framework/Flutter',
'artifacts/engine/ios/Flutter.xcframework/ios-arm64_armv7/Flutter.framework/Flutter',
'artifacts/engine/ios/Flutter.xcframework/ios-arm64_x86_64-simulator/Flutter.framework/Flutter',
'artifacts/ios-deploy/ios-deploy',
]
.map((String relativePath) =>
fileSystem.path.join(frameworkCacheDirectory, 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
Future<void> verifyExist() async {
final Set<String> foundFiles = <String>{};
for (final String binaryPath
in await findBinaryPaths(await framework.cacheDirectory)) {
if ((await binariesWithEntitlements).contains(binaryPath)) {
foundFiles.add(binaryPath);
} else if ((await binariesWithoutEntitlements).contains(binaryPath)) {
foundFiles.add(binaryPath);
} else {
throw ConductorException(
'Found unexpected binary in cache: $binaryPath');
}
}
final List<String> allExpectedFiles =
(await binariesWithEntitlements) + (await 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
Future<void> verifySignatures() async {
final List<String> unsignedBinaries = <String>[];
final List<String> wrongEntitlementBinaries = <String>[];
final List<String> unexpectedBinaries = <String>[];
for (final String binaryPath
in await findBinaryPaths(await framework.cacheDirectory)) {
bool verifySignature = false;
bool verifyEntitlements = false;
if ((await binariesWithEntitlements).contains(binaryPath)) {
verifySignature = true;
verifyEntitlements = true;
}
if ((await 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 = await processManager.run(
<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 (!(await hasExpectedEntitlements(binaryPath))) {
wrongEntitlementBinaries.add(binaryPath);
}
}
}
// First print all deviations from expectations
if (unsignedBinaries.isNotEmpty) {
stdio.printError('Found ${unsignedBinaries.length} unsigned binaries:');
unsignedBinaries.forEach(stdio.printError);
}
if (wrongEntitlementBinaries.isNotEmpty) {
stdio.printError(
'Found ${wrongEntitlementBinaries.length} binaries with unexpected entitlements:');
wrongEntitlementBinaries.forEach(stdio.printError);
}
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.');
}
final String? desiredRevision = argResults![kRevision] as String?;
if (desiredRevision == null) {
stdio.printStatus(
'Verified that binaries are codesigned and have expected entitlements.');
} else {
stdio.printStatus(
'Verified that binaries for commit $desiredRevision are codesigned and have '
'expected entitlements.');
}
}
List<String>? _allBinaryPaths;
/// Find every binary file in the given [rootDirectory].
Future<List<String>> findBinaryPaths(String rootDirectory) async {
if (_allBinaryPaths != null) {
return _allBinaryPaths!;
}
final List<String> allBinaryPaths = <String>[];
final io.ProcessResult result = await processManager.run(
<String>[
'find',
rootDirectory,
'-type',
'f',
],
);
final List<String> allFiles = (result.stdout as String)
.split('\n')
.where((String s) => s.isNotEmpty)
.toList();
await Future.forEach(allFiles, (String filePath) async {
if (await isBinary(filePath)) {
allBinaryPaths.add(filePath);
}
});
_allBinaryPaths = allBinaryPaths;
return _allBinaryPaths!;
}
/// Check mime-type of file at [filePath] to determine if it is binary.
Future<bool> isBinary(String filePath) async {
final io.ProcessResult result = await processManager.run(
<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.
Future<bool> hasExpectedEntitlements(String binaryPath) async {
final io.ProcessResult entitlementResult = await processManager.run(
<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 =
(await 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

@@ -0,0 +1,83 @@
// 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;
Future<String> getOutput(
List<String> args,
String explanation, {
required String workingDirectory,
bool allowFailures = false,
}) async {
final ProcessResult result = await _run(args, workingDirectory);
if (result.exitCode == 0) {
return stdoutToString(result.stdout);
}
_reportFailureAndExit(args, workingDirectory, result, explanation);
}
Future<int> run(
List<String> args,
String explanation, {
bool allowNonZeroExitCode = false,
required String workingDirectory,
}) async {
final ProcessResult result = await _run(args, workingDirectory);
if (result.exitCode != 0 && !allowNonZeroExitCode) {
_reportFailureAndExit(args, workingDirectory, result, explanation);
}
return result.exitCode;
}
Future<ProcessResult> _run(List<String> args, String workingDirectory) async {
return processManager.run(
<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

@@ -0,0 +1,207 @@
// 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';
import 'proto/conductor_state.pb.dart' as pb;
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';
const String kLuciPackagingConsoleLink = 'https://ci.chromium.org/p/flutter/g/packaging/console';
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();
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'_');
}
/// Return a web link for the user to open a new PR.
///
/// Includes PR title and body via query params.
String getNewPrLink({
required String userName,
required String repoName,
required pb.ConductorState state,
}) {
assert(state.releaseChannel.isNotEmpty);
assert(state.releaseVersion.isNotEmpty);
late final String candidateBranch;
late final String workingBranch;
late final String repoLabel;
switch (repoName) {
case 'flutter':
candidateBranch = state.framework.candidateBranch;
workingBranch = state.framework.workingBranch;
repoLabel = 'Framework';
break;
case 'engine':
candidateBranch = state.engine.candidateBranch;
workingBranch = state.engine.workingBranch;
repoLabel = 'Engine';
break;
default:
throw ConductorException('Expected repoName to be one of flutter or engine but got $repoName.');
}
assert(candidateBranch.isNotEmpty);
assert(workingBranch.isNotEmpty);
final String title = '[flutter_releases] Flutter ${state.releaseChannel} '
'${state.releaseVersion} $repoLabel Cherrypicks';
final StringBuffer body = StringBuffer();
body.write('''
# Flutter ${state.releaseChannel} ${state.releaseVersion} $repoLabel
## Scheduled Cherrypicks
''');
if (repoName == 'engine') {
if (state.engine.dartRevision.isNotEmpty) {
// shorten hashes to make final link manageable
// prefix with github org/repo so GitHub will auto-generate a hyperlink
body.writeln('- Roll dart revision: dart-lang/sdk@${state.engine.dartRevision.substring(0, 9)}');
}
for (final pb.Cherrypick cp in state.engine.cherrypicks) {
// Only list commits that map to a commit that exists upstream.
if (cp.trunkRevision.isNotEmpty) {
body.writeln('- commit: flutter/engine@${cp.trunkRevision.substring(0, 9)}');
}
}
} else {
for (final pb.Cherrypick cp in state.framework.cherrypicks) {
// Only list commits that map to a commit that exists upstream.
if (cp.trunkRevision.isNotEmpty) {
body.writeln('- commit: ${cp.trunkRevision.substring(0, 9)}');
}
}
}
return 'https://github.com/flutter/$repoName/compare/'
'$candidateBranch...$userName:$workingBranch?'
'expand=1'
'&title=${Uri.encodeQueryComponent(title)}'
'&body=${Uri.encodeQueryComponent(body.toString())}';
}

View File

@@ -0,0 +1,399 @@
// 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:file/file.dart' show File;
import 'package:meta/meta.dart' show visibleForTesting;
import './globals.dart';
import './proto/conductor_state.pb.dart' as pb;
import './proto/conductor_state.pbenum.dart';
import './repository.dart';
import './state.dart';
import './stdio.dart';
const String kStateOption = 'state-file';
const String kYesFlag = 'yes';
const String kForceFlag = 'force';
/// Command to proceed from one [pb.ReleasePhase] to the next.
class NextCommand extends Command<void> {
NextCommand({
required this.checkouts,
}) {
final String defaultPath = defaultStateFilePath(checkouts.platform);
argParser.addOption(
kStateOption,
defaultsTo: defaultPath,
help: 'Path to persistent state file. Defaults to $defaultPath',
);
argParser.addFlag(
kYesFlag,
help: 'Auto-accept any confirmation prompts.',
hide: true, // primarily for integration testing
);
argParser.addFlag(
kForceFlag,
help: 'Force push when updating remote git branches.',
);
}
final Checkouts checkouts;
@override
String get name => 'next';
@override
String get description => 'Proceed to the next release phase.';
@override
Future<void> run() async {
await runNext(
autoAccept: argResults![kYesFlag] as bool,
checkouts: checkouts,
force: argResults![kForceFlag] as bool,
stateFile: checkouts.fileSystem.file(argResults![kStateOption]),
);
}
}
@visibleForTesting
bool prompt(String message, Stdio stdio) {
stdio.write('${message.trim()} (y/n) ');
final String response = stdio.readLineSync().trim();
final String firstChar = response[0].toUpperCase();
if (firstChar == 'Y') {
return true;
}
if (firstChar == 'N') {
return false;
}
throw ConductorException(
'Unknown user input (expected "y" or "n"): $response',
);
}
@visibleForTesting
Future<void> runNext({
required bool autoAccept,
required bool force,
required Checkouts checkouts,
required File stateFile,
}) async {
final Stdio stdio = checkouts.stdio;
const List<CherrypickState> finishedStates = <CherrypickState>[
CherrypickState.COMPLETED,
CherrypickState.ABANDONED,
];
if (!stateFile.existsSync()) {
throw ConductorException(
'No persistent state file found at ${stateFile.path}.',
);
}
final pb.ConductorState state = readStateFromFile(stateFile);
switch (state.currentPhase) {
case pb.ReleasePhase.APPLY_ENGINE_CHERRYPICKS:
final Remote upstream = Remote(
name: RemoteName.upstream,
url: state.engine.upstream.url,
);
final EngineRepository engine = EngineRepository(
checkouts,
initialRef: state.engine.workingBranch,
upstreamRemote: upstream,
previousCheckoutLocation: state.engine.checkoutPath,
);
// check if the candidate branch is enabled in .ci.yaml
final CiYaml engineCiYaml = await engine.ciYaml;
if (!engineCiYaml.enabledBranches.contains(state.engine.candidateBranch)) {
engineCiYaml.enableBranch(state.engine.candidateBranch);
// commit
final String revision = await engine.commit(
'add branch ${state.engine.candidateBranch} to enabled_branches in .ci.yaml',
addFirst: true,
);
// append to list of cherrypicks so we know a PR is required
state.engine.cherrypicks.add(pb.Cherrypick(
appliedRevision: revision,
state: pb.CherrypickState.COMPLETED,
));
}
if (!requiresEnginePR(state)) {
stdio.printStatus(
'This release has no engine cherrypicks. No Engine PR is necessary.\n',
);
break;
}
final List<pb.Cherrypick> unappliedCherrypicks = <pb.Cherrypick>[];
for (final pb.Cherrypick cherrypick in state.engine.cherrypicks) {
if (!finishedStates.contains(cherrypick.state)) {
unappliedCherrypicks.add(cherrypick);
}
}
if (unappliedCherrypicks.isEmpty) {
stdio.printStatus('All engine cherrypicks have been auto-applied by the conductor.\n');
} else {
if (unappliedCherrypicks.length == 1) {
stdio.printStatus('There was ${unappliedCherrypicks.length} cherrypick that was not auto-applied.');
} else {
stdio.printStatus('There were ${unappliedCherrypicks.length} cherrypicks that were not auto-applied.');
}
stdio.printStatus('These must be applied manually in the directory '
'${state.engine.checkoutPath} before proceeding.\n');
}
if (autoAccept == false) {
final bool response = prompt(
'Are you ready to push your engine branch to the repository '
'${state.engine.mirror.url}?',
stdio,
);
if (!response) {
stdio.printError('Aborting command.');
writeStateToFile(stateFile, state, stdio.logs);
return;
}
}
await engine.pushRef(
fromRef: 'HEAD',
// Explicitly create new branch
toRef: 'refs/heads/${state.engine.workingBranch}',
remote: state.engine.mirror.name,
);
break;
case pb.ReleasePhase.CODESIGN_ENGINE_BINARIES:
stdio.printStatus(<String>[
'You must validate pre-submit CI for your engine PR, merge it, and codesign',
'binaries before proceeding.\n',
].join('\n'));
if (autoAccept == false) {
// TODO(fujino): actually test if binaries have been codesigned on macOS
final bool response = prompt(
'Has CI passed for the engine PR and binaries been codesigned?',
stdio,
);
if (!response) {
stdio.printError('Aborting command.');
writeStateToFile(stateFile, state, stdio.logs);
return;
}
}
break;
case pb.ReleasePhase.APPLY_FRAMEWORK_CHERRYPICKS:
if (state.engine.cherrypicks.isEmpty && state.engine.dartRevision.isEmpty) {
stdio.printStatus(
'This release has no engine cherrypicks, and thus the engine.version file\n'
'in the framework does not need to be updated.',
);
if (state.framework.cherrypicks.isEmpty) {
stdio.printStatus(
'This release also has no framework cherrypicks. Therefore, a framework\n'
'pull request is not required.',
);
break;
}
}
final Remote engineUpstreamRemote = Remote(
name: RemoteName.upstream,
url: state.engine.upstream.url,
);
final EngineRepository engine = EngineRepository(
checkouts,
// We explicitly want to check out the merged version from upstream
initialRef: '${engineUpstreamRemote.name}/${state.engine.candidateBranch}',
upstreamRemote: engineUpstreamRemote,
previousCheckoutLocation: state.engine.checkoutPath,
);
final String engineRevision = await engine.reverseParse('HEAD');
final Remote upstream = Remote(
name: RemoteName.upstream,
url: state.framework.upstream.url,
);
final FrameworkRepository framework = FrameworkRepository(
checkouts,
initialRef: state.framework.workingBranch,
upstreamRemote: upstream,
previousCheckoutLocation: state.framework.checkoutPath,
);
// Check if the current candidate branch is enabled
if (!(await framework.ciYaml).enabledBranches.contains(state.framework.candidateBranch)) {
(await framework.ciYaml).enableBranch(state.framework.candidateBranch);
// commit
final String revision = await framework.commit(
'add branch ${state.framework.candidateBranch} to enabled_branches in .ci.yaml',
addFirst: true,
);
// append to list of cherrypicks so we know a PR is required
state.framework.cherrypicks.add(pb.Cherrypick(
appliedRevision: revision,
state: pb.CherrypickState.COMPLETED,
));
}
stdio.printStatus('Rolling new engine hash $engineRevision to framework checkout...');
final bool needsCommit = await framework.updateEngineRevision(engineRevision);
if (needsCommit) {
final String revision = await framework.commit(
'Update Engine revision to $engineRevision for ${state.releaseChannel} release ${state.releaseVersion}',
addFirst: true,
);
// append to list of cherrypicks so we know a PR is required
state.framework.cherrypicks.add(pb.Cherrypick(
appliedRevision: revision,
state: pb.CherrypickState.COMPLETED,
));
}
final List<pb.Cherrypick> unappliedCherrypicks = <pb.Cherrypick>[];
for (final pb.Cherrypick cherrypick in state.framework.cherrypicks) {
if (!finishedStates.contains(cherrypick.state)) {
unappliedCherrypicks.add(cherrypick);
}
}
if (state.framework.cherrypicks.isEmpty) {
stdio.printStatus(
'This release has no framework cherrypicks. However, a framework PR is still\n'
'required to roll engine cherrypicks.',
);
} else if (unappliedCherrypicks.isEmpty) {
stdio.printStatus('All framework cherrypicks were auto-applied by the conductor.');
} else {
if (unappliedCherrypicks.length == 1) {
stdio.printStatus('There was ${unappliedCherrypicks.length} cherrypick that was not auto-applied.',);
}
else {
stdio.printStatus('There were ${unappliedCherrypicks.length} cherrypicks that were not auto-applied.',);
}
stdio.printStatus(
'These must be applied manually in the directory '
'${state.framework.checkoutPath} before proceeding.\n',
);
}
if (autoAccept == false) {
final bool response = prompt(
'Are you ready to push your framework branch to the repository '
'${state.framework.mirror.url}?',
stdio,
);
if (!response) {
stdio.printError('Aborting command.');
writeStateToFile(stateFile, state, stdio.logs);
return;
}
}
await framework.pushRef(
fromRef: 'HEAD',
// Explicitly create new branch
toRef: 'refs/heads/${state.framework.workingBranch}',
remote: state.framework.mirror.name,
);
break;
case pb.ReleasePhase.PUBLISH_VERSION:
stdio.printStatus('Please ensure that you have merged your framework PR and that');
stdio.printStatus('post-submit CI has finished successfully.\n');
final Remote upstream = Remote(
name: RemoteName.upstream,
url: state.framework.upstream.url,
);
final FrameworkRepository framework = FrameworkRepository(
checkouts,
// We explicitly want to check out the merged version from upstream
initialRef: '${upstream.name}/${state.framework.candidateBranch}',
upstreamRemote: upstream,
previousCheckoutLocation: state.framework.checkoutPath,
);
final String headRevision = await framework.reverseParse('HEAD');
if (autoAccept == false) {
final bool response = prompt(
'Are you ready to tag commit $headRevision as ${state.releaseVersion}\n'
'and push to remote ${state.framework.upstream.url}?',
stdio,
);
if (!response) {
stdio.printError('Aborting command.');
writeStateToFile(stateFile, state, stdio.logs);
return;
}
}
await framework.tag(headRevision, state.releaseVersion, upstream.name);
break;
case pb.ReleasePhase.PUBLISH_CHANNEL:
final Remote upstream = Remote(
name: RemoteName.upstream,
url: state.framework.upstream.url,
);
final FrameworkRepository framework = FrameworkRepository(
checkouts,
// We explicitly want to check out the merged version from upstream
initialRef: '${upstream.name}/${state.framework.candidateBranch}',
upstreamRemote: upstream,
previousCheckoutLocation: state.framework.checkoutPath,
);
final String headRevision = await framework.reverseParse('HEAD');
if (autoAccept == false) {
// dryRun: true means print out git command
await framework.pushRef(
fromRef: headRevision,
toRef: state.releaseChannel,
remote: state.framework.upstream.url,
force: force,
dryRun: true,
);
final bool response = prompt(
'Are you ready to publish this release?',
stdio,
);
if (!response) {
stdio.printError('Aborting command.');
writeStateToFile(stateFile, state, stdio.logs);
return;
}
}
await framework.pushRef(
fromRef: headRevision,
toRef: state.releaseChannel,
remote: state.framework.upstream.url,
force: force,
);
break;
case pb.ReleasePhase.VERIFY_RELEASE:
stdio.printStatus(
'The current status of packaging builds can be seen at:\n'
'\t$kLuciPackagingConsoleLink',
);
if (autoAccept == false) {
final bool response = prompt(
'Have all packaging builds finished successfully?',
stdio,
);
if (!response) {
stdio.printError('Aborting command.');
writeStateToFile(stateFile, state, stdio.logs);
return;
}
}
break;
case pb.ReleasePhase.RELEASE_COMPLETED:
throw ConductorException('This release is finished.');
}
final ReleasePhase nextPhase = getNextPhase(state.currentPhase);
stdio.printStatus('\nUpdating phase from ${state.currentPhase} to $nextPhase...\n');
state.currentPhase = nextPhase;
stdio.printStatus(phaseInstructions(state));
writeStateToFile(stateFile, state, stdio.logs);
}

View File

@@ -0,0 +1,8 @@
## 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

@@ -0,0 +1,45 @@
#!/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
# Use null-safe protoc_plugin
dart pub global activate protoc_plugin 20.0.0
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 "$DIR/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

@@ -0,0 +1,593 @@
// 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.12
// 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')
..aOS(9, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'workingBranch',
protoName: 'workingBranch')
..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,
$core.String? workingBranch,
}) {
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;
}
if (workingBranch != null) {
_result.workingBranch = workingBranch;
}
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);
@$pb.TagNumber(9)
$core.String get workingBranch => $_getSZ(8);
@$pb.TagNumber(9)
set workingBranch($core.String v) {
$_setString(8, v);
}
@$pb.TagNumber(9)
$core.bool hasWorkingBranch() => $_has(8);
@$pb.TagNumber(9)
void clearWorkingBranch() => clearField(9);
}
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') ? '' : 'currentPhase', $pb.PbFieldType.OE,
protoName: 'currentPhase',
defaultOrMaker: ReleasePhase.APPLY_ENGINE_CHERRYPICKS,
valueOf: ReleasePhase.valueOf,
enumValues: ReleasePhase.values)
..aOS(10, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'conductorVersion',
protoName: 'conductorVersion')
..aOS(11, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'incrementLevel',
protoName: 'incrementLevel')
..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? currentPhase,
$core.String? conductorVersion,
$core.String? incrementLevel,
}) {
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 (currentPhase != null) {
_result.currentPhase = currentPhase;
}
if (conductorVersion != null) {
_result.conductorVersion = conductorVersion;
}
if (incrementLevel != null) {
_result.incrementLevel = incrementLevel;
}
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 currentPhase => $_getN(7);
@$pb.TagNumber(9)
set currentPhase(ReleasePhase v) {
setField(9, v);
}
@$pb.TagNumber(9)
$core.bool hasCurrentPhase() => $_has(7);
@$pb.TagNumber(9)
void clearCurrentPhase() => 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);
@$pb.TagNumber(11)
$core.String get incrementLevel => $_getSZ(9);
@$pb.TagNumber(11)
set incrementLevel($core.String v) {
$_setString(9, v);
}
@$pb.TagNumber(11)
$core.bool hasIncrementLevel() => $_has(9);
@$pb.TagNumber(11)
void clearIncrementLevel() => clearField(11);
}

View File

@@ -0,0 +1,69 @@
// 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.12
// 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 APPLY_ENGINE_CHERRYPICKS =
ReleasePhase._(0, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'APPLY_ENGINE_CHERRYPICKS');
static const ReleasePhase CODESIGN_ENGINE_BINARIES =
ReleasePhase._(1, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'CODESIGN_ENGINE_BINARIES');
static const ReleasePhase APPLY_FRAMEWORK_CHERRYPICKS = ReleasePhase._(
2, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'APPLY_FRAMEWORK_CHERRYPICKS');
static const ReleasePhase PUBLISH_VERSION =
ReleasePhase._(3, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PUBLISH_VERSION');
static const ReleasePhase PUBLISH_CHANNEL =
ReleasePhase._(4, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'PUBLISH_CHANNEL');
static const ReleasePhase VERIFY_RELEASE =
ReleasePhase._(5, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'VERIFY_RELEASE');
static const ReleasePhase RELEASE_COMPLETED =
ReleasePhase._(6, const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'RELEASE_COMPLETED');
static const $core.List<ReleasePhase> values = <ReleasePhase>[
APPLY_ENGINE_CHERRYPICKS,
CODESIGN_ENGINE_BINARIES,
APPLY_FRAMEWORK_CHERRYPICKS,
PUBLISH_VERSION,
PUBLISH_CHANNEL,
VERIFY_RELEASE,
RELEASE_COMPLETED,
];
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

@@ -0,0 +1,110 @@
// 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.12
// 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': 'APPLY_ENGINE_CHERRYPICKS', '2': 0},
const {'1': 'CODESIGN_ENGINE_BINARIES', '2': 1},
const {'1': 'APPLY_FRAMEWORK_CHERRYPICKS', '2': 2},
const {'1': 'PUBLISH_VERSION', '2': 3},
const {'1': 'PUBLISH_CHANNEL', '2': 4},
const {'1': 'VERIFY_RELEASE', '2': 5},
const {'1': 'RELEASE_COMPLETED', '2': 6},
],
};
/// Descriptor for `ReleasePhase`. Decode as a `google.protobuf.EnumDescriptorProto`.
final $typed_data.Uint8List releasePhaseDescriptor = $convert.base64Decode(
'CgxSZWxlYXNlUGhhc2USHAoYQVBQTFlfRU5HSU5FX0NIRVJSWVBJQ0tTEAASHAoYQ09ERVNJR05fRU5HSU5FX0JJTkFSSUVTEAESHwobQVBQTFlfRlJBTUVXT1JLX0NIRVJSWVBJQ0tTEAISEwoPUFVCTElTSF9WRVJTSU9OEAMSEwoPUFVCTElTSF9DSEFOTkVMEAQSEgoOVkVSSUZZX1JFTEVBU0UQBRIVChFSRUxFQVNFX0NPTVBMRVRFRBAG');
@$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'},
const {'1': 'workingBranch', '3': 9, '4': 1, '5': 9, '10': 'workingBranch'},
],
};
/// Descriptor for `Repository`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List repositoryDescriptor = $convert.base64Decode(
'CgpSZXBvc2l0b3J5EigKD2NhbmRpZGF0ZUJyYW5jaBgBIAEoCVIPY2FuZGlkYXRlQnJhbmNoEigKD3N0YXJ0aW5nR2l0SGVhZBgCIAEoCVIPc3RhcnRpbmdHaXRIZWFkEiYKDmN1cnJlbnRHaXRIZWFkGAMgASgJUg5jdXJyZW50R2l0SGVhZBIiCgxjaGVja291dFBhdGgYBCABKAlSDGNoZWNrb3V0UGF0aBIzCgh1cHN0cmVhbRgFIAEoCzIXLmNvbmR1Y3Rvcl9zdGF0ZS5SZW1vdGVSCHVwc3RyZWFtEi8KBm1pcnJvchgGIAEoCzIXLmNvbmR1Y3Rvcl9zdGF0ZS5SZW1vdGVSBm1pcnJvchI9CgtjaGVycnlwaWNrcxgHIAMoCzIbLmNvbmR1Y3Rvcl9zdGF0ZS5DaGVycnlwaWNrUgtjaGVycnlwaWNrcxIiCgxkYXJ0UmV2aXNpb24YCCABKAlSDGRhcnRSZXZpc2lvbhIkCg13b3JraW5nQnJhbmNoGAkgASgJUg13b3JraW5nQnJhbmNo');
@$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': 'currentPhase', '3': 9, '4': 1, '5': 14, '6': '.conductor_state.ReleasePhase', '10': 'currentPhase'},
const {'1': 'conductorVersion', '3': 10, '4': 1, '5': 9, '10': 'conductorVersion'},
const {'1': 'incrementLevel', '3': 11, '4': 1, '5': 9, '10': 'incrementLevel'},
],
};
/// Descriptor for `ConductorState`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List conductorStateDescriptor = $convert.base64Decode(
'Cg5Db25kdWN0b3JTdGF0ZRImCg5yZWxlYXNlQ2hhbm5lbBgBIAEoCVIOcmVsZWFzZUNoYW5uZWwSJgoOcmVsZWFzZVZlcnNpb24YAiABKAlSDnJlbGVhc2VWZXJzaW9uEjMKBmVuZ2luZRgEIAEoCzIbLmNvbmR1Y3Rvcl9zdGF0ZS5SZXBvc2l0b3J5UgZlbmdpbmUSOQoJZnJhbWV3b3JrGAUgASgLMhsuY29uZHVjdG9yX3N0YXRlLlJlcG9zaXRvcnlSCWZyYW1ld29yaxIgCgtjcmVhdGVkRGF0ZRgGIAEoA1ILY3JlYXRlZERhdGUSKAoPbGFzdFVwZGF0ZWREYXRlGAcgASgDUg9sYXN0VXBkYXRlZERhdGUSEgoEbG9ncxgIIAMoCVIEbG9ncxJBCgxjdXJyZW50UGhhc2UYCSABKA4yHS5jb25kdWN0b3Jfc3RhdGUuUmVsZWFzZVBoYXNlUgxjdXJyZW50UGhhc2USKgoQY29uZHVjdG9yVmVyc2lvbhgKIAEoCVIQY29uZHVjdG9yVmVyc2lvbhImCg5pbmNyZW1lbnRMZXZlbBgLIAEoCVIOaW5jcmVtZW50TGV2ZWw=');

View File

@@ -0,0 +1,12 @@
// 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.12
// 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

@@ -0,0 +1,117 @@
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.
APPLY_ENGINE_CHERRYPICKS = 0;
CODESIGN_ENGINE_BINARIES = 1;
APPLY_FRAMEWORK_CHERRYPICKS = 2;
// Git tag applied to framework RC branch HEAD and pushed upstream.
PUBLISH_VERSION = 3;
// RC branch HEAD pushed to upstream release branch.
//
// For example, flutter-1.2-candidate.3 -> upstream/beta
PUBLISH_CHANNEL = 4;
// Package artifacts verified to exist on cloud storage.
VERIFY_RELEASE = 5;
// There is no further work to be done.
RELEASE_COMPLETED = 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;
// Name of local and remote branch for applying cherrypicks.
//
// When the pull request is merged, all commits here will be squashed to a
// single commit on the [candidateBranch].
string workingBranch = 9;
}
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 current [ReleasePhase] that has yet to be completed.
ReleasePhase currentPhase = 9;
// Commit hash of the Conductor tool.
string conductorVersion = 10;
// One of x, y, z, m, or n.
string incrementLevel = 11;
}

View File

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

@@ -0,0 +1,874 @@
// 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 'package:yaml/yaml.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,
assert(url != null),
assert(url != '');
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.upstreamRemote,
required this.processManager,
required this.stdio,
required this.platform,
required this.fileSystem,
required this.parentDirectory,
this.initialRef,
this.localUpstream = false,
this.previousCheckoutLocation,
this.mirrorRemote,
}) : git = Git(processManager),
assert(localUpstream != null),
assert(upstreamRemote.url.isNotEmpty);
final String name;
final Remote upstreamRemote;
/// Remote for user's mirror.
///
/// This value can be null, in which case attempting to access it will lead to
/// a [ConductorException].
final Remote? mirrorRemote;
/// 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;
/// If the repository will be used as an upstream for a test repo.
final bool localUpstream;
Directory? _checkoutDirectory;
String? previousCheckoutLocation;
/// 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.
Future<Directory> get checkoutDirectory async {
if (_checkoutDirectory != null) {
return _checkoutDirectory!;
}
if (previousCheckoutLocation != null) {
_checkoutDirectory = fileSystem.directory(previousCheckoutLocation);
if (!_checkoutDirectory!.existsSync()) {
throw ConductorException(
'Provided previousCheckoutLocation $previousCheckoutLocation does not exist on disk!');
}
if (initialRef != null) {
assert(initialRef != '');
await git.run(
<String>['fetch', upstreamRemote.name],
'Fetch ${upstreamRemote.name} to ensure we have latest refs',
workingDirectory: _checkoutDirectory!.path,
);
// Note: if [initialRef] is a remote ref the checkout will be left in a
// detached HEAD state.
await git.run(
<String>['checkout', initialRef!],
'Checking out initialRef $initialRef',
workingDirectory: _checkoutDirectory!.path,
);
}
return _checkoutDirectory!;
}
_checkoutDirectory = parentDirectory.childDirectory(name);
await lazilyInitialize(_checkoutDirectory!);
return _checkoutDirectory!;
}
/// Ensure the repository is cloned to disk and initialized with proper state.
Future<void> lazilyInitialize(Directory checkoutDirectory) async {
if (checkoutDirectory.existsSync()) {
stdio.printTrace('Deleting $name from ${checkoutDirectory.path}...');
checkoutDirectory.deleteSync(recursive: true);
}
stdio.printTrace(
'Cloning $name from ${upstreamRemote.url} to ${checkoutDirectory.path}...',
);
await git.run(
<String>[
'clone',
'--origin',
upstreamRemote.name,
'--',
upstreamRemote.url,
checkoutDirectory.path
],
'Cloning $name repo',
workingDirectory: parentDirectory.path,
);
if (mirrorRemote != null) {
await git.run(
<String>['remote', 'add', mirrorRemote!.name, mirrorRemote!.url],
'Adding remote ${mirrorRemote!.url} as ${mirrorRemote!.name}',
workingDirectory: checkoutDirectory.path,
);
await git.run(
<String>['fetch', mirrorRemote!.name],
'Fetching git remote ${mirrorRemote!.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) {
await git.run(
<String>['checkout', channel, '--'],
'check out branch $channel locally',
workingDirectory: checkoutDirectory.path,
);
}
}
if (initialRef != null) {
await git.run(
<String>['checkout', '${upstreamRemote.name}/$initialRef'],
'Checking out initialRef $initialRef',
workingDirectory: checkoutDirectory.path,
);
}
final String revision = await reverseParse('HEAD');
stdio.printTrace(
'Repository $name is checked out at revision "$revision".',
);
}
/// The URL of the remote named [remoteName].
Future<String> remoteUrl(String remoteName) async {
assert(remoteName != null);
return git.getOutput(
<String>['remote', 'get-url', remoteName],
'verify the URL of the $remoteName remote',
workingDirectory: (await checkoutDirectory).path,
);
}
/// Verify the repository's git checkout is clean.
Future<bool> gitCheckoutClean() async {
final String output = await git.getOutput(
<String>['status', '--porcelain'],
'check that the git checkout is clean',
workingDirectory: (await checkoutDirectory).path,
);
return output == '';
}
/// Return the revision for the branch point between two refs.
Future<String> branchPoint(String firstRef, String secondRef) async {
return (await git.getOutput(
<String>['merge-base', firstRef, secondRef],
'determine the merge base between $firstRef and $secondRef',
workingDirectory: (await checkoutDirectory).path,
)).trim();
}
/// Fetch all branches and associated commits and tags from [remoteName].
Future<void> fetch(String remoteName) async {
await git.run(
<String>['fetch', remoteName, '--tags'],
'fetch $remoteName --tags',
workingDirectory: (await checkoutDirectory).path,
);
}
/// Create (and checkout) a new branch based on the current HEAD.
///
/// Runs `git checkout -b $branchName`.
Future<void> newBranch(String branchName) async {
await git.run(
<String>['checkout', '-b', branchName],
'create & checkout new branch $branchName',
workingDirectory: (await checkoutDirectory).path,
);
}
/// Check out the given ref.
Future<void> checkout(String ref) async {
await git.run(
<String>['checkout', ref],
'checkout ref',
workingDirectory: (await checkoutDirectory).path,
);
}
/// Obtain the version tag at the tip of a release branch.
Future<String> getFullTag(
String remoteName,
String branchName, {
bool exact = true,
}) async {
// includes both stable (e.g. 1.2.3) and dev tags (e.g. 1.2.3-4.5.pre)
const String glob = '*.*.*';
// describe the latest dev release
final String ref = 'refs/remotes/$remoteName/$branchName';
return git.getOutput(
<String>[
'describe',
'--match',
glob,
if (exact) '--exact-match',
'--tags',
ref,
],
'obtain last released version number',
workingDirectory: (await checkoutDirectory).path,
);
}
/// List commits in reverse chronological order.
Future<List<String>> revList(List<String> args) async {
return (await git.getOutput(<String>['rev-list', ...args],
'rev-list with args ${args.join(' ')}',
workingDirectory: (await checkoutDirectory).path))
.trim()
.split('\n');
}
/// Look up the commit for [ref].
Future<String> reverseParse(String ref) async {
final String revisionHash = await git.getOutput(
<String>['rev-parse', ref],
'look up the commit for the ref $ref',
workingDirectory: (await checkoutDirectory).path,
);
assert(revisionHash.isNotEmpty);
return revisionHash;
}
/// Determines if one ref is an ancestor for another.
Future<bool> isAncestor(String possibleAncestor, String possibleDescendant) async {
final int exitcode = await git.run(
<String>[
'merge-base',
'--is-ancestor',
possibleDescendant,
possibleAncestor
],
'verify $possibleAncestor is a direct ancestor of $possibleDescendant.',
allowNonZeroExitCode: true,
workingDirectory: (await checkoutDirectory).path,
);
return exitcode == 0;
}
/// Determines if a given commit has a tag.
Future<bool> isCommitTagged(String commit) async {
final int exitcode = await git.run(
<String>['describe', '--exact-match', '--tags', commit],
'verify $commit is already tagged',
allowNonZeroExitCode: true,
workingDirectory: (await checkoutDirectory).path,
);
return exitcode == 0;
}
/// Determines if a commit will cherry-pick to current HEAD without conflict.
Future<bool> canCherryPick(String commit) async {
assert(
await gitCheckoutClean(),
'cannot cherry-pick because git checkout ${(await checkoutDirectory).path} is not clean',
);
final int exitcode = await git.run(
<String>['cherry-pick', '--no-commit', commit],
'attempt to cherry-pick $commit without committing',
allowNonZeroExitCode: true,
workingDirectory: (await checkoutDirectory).path,
);
final bool result = exitcode == 0;
if (result == false) {
stdio.printError(await git.getOutput(
<String>['diff'],
'get diff of failed cherry-pick',
workingDirectory: (await checkoutDirectory).path,
));
}
await reset('HEAD');
return result;
}
/// Cherry-pick a [commit] to the current HEAD.
///
/// This method will throw a [GitException] if the command fails.
Future<void> cherryPick(String commit) async {
assert(
await gitCheckoutClean(),
'cannot cherry-pick because git checkout ${(await checkoutDirectory).path} is not clean',
);
await git.run(
<String>['cherry-pick', commit],
'cherry-pick $commit',
workingDirectory: (await checkoutDirectory).path,
);
}
/// Resets repository HEAD to [ref].
Future<void> reset(String ref) async {
await git.run(
<String>['reset', ref, '--hard'],
'reset to $ref',
workingDirectory: (await checkoutDirectory).path,
);
}
/// Push [commit] to the release channel [branch].
Future<void> pushRef({
required String fromRef,
required String remote,
required String toRef,
bool force = false,
bool dryRun = false,
}) async {
final List<String> args = <String>[
'push',
if (force) '--force',
remote,
'$fromRef:$toRef',
];
final String command = <String>[
'git',
...args,
].join(' ');
if (dryRun) {
stdio.printStatus('About to execute command: `$command`');
} else {
await git.run(
args,
'update the release branch with the commit',
workingDirectory: (await checkoutDirectory).path,
);
stdio.printStatus('Executed command: `$command`');
}
}
Future<String> commit(
String message, {
bool addFirst = false,
}) async {
assert(!message.contains("'"));
final bool hasChanges = (await git.getOutput(
<String>['status', '--porcelain'],
'check for uncommitted changes',
workingDirectory: (await checkoutDirectory).path,
)).trim().isNotEmpty;
if (!hasChanges) {
throw ConductorException(
'Tried to commit with message $message but no changes were present');
}
if (addFirst) {
await git.run(
<String>['add', '--all'],
'add all changes to the index',
workingDirectory: (await checkoutDirectory).path,
);
}
await git.run(
<String>['commit', "--message='$message'"],
'commit changes',
workingDirectory: (await checkoutDirectory).path,
);
return reverseParse('HEAD');
}
/// Create an empty commit and return the revision.
@visibleForTesting
Future<String> authorEmptyCommit([String message = 'An empty commit']) async {
await git.run(
<String>[
'-c',
'user.name=Conductor',
'-c',
'user.email=conductor@flutter.dev',
'commit',
'--allow-empty',
'-m',
"'$message'",
],
'create an empty commit',
workingDirectory: (await 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
Future<Repository> cloneRepository(String cloneName);
}
class FrameworkRepository extends Repository {
FrameworkRepository(
this.checkouts, {
String name = 'framework',
Remote upstreamRemote = const Remote(
name: RemoteName.upstream, url: FrameworkRepository.defaultUpstream),
bool localUpstream = false,
String? previousCheckoutLocation,
String? initialRef,
Remote? mirrorRemote,
}) : super(
name: name,
upstreamRemote: upstreamRemote,
mirrorRemote: mirrorRemote,
initialRef: initialRef,
fileSystem: checkouts.fileSystem,
localUpstream: localUpstream,
parentDirectory: checkouts.directory,
platform: checkouts.platform,
processManager: checkouts.processManager,
stdio: checkouts.stdio,
previousCheckoutLocation: previousCheckoutLocation,
);
/// 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',
String? previousCheckoutLocation,
required String upstreamPath,
}) {
return FrameworkRepository(
checkouts,
name: name,
upstreamRemote: Remote(
name: RemoteName.upstream,
url: 'file://$upstreamPath/',
),
localUpstream: false,
previousCheckoutLocation: previousCheckoutLocation,
);
}
final Checkouts checkouts;
static const String defaultUpstream =
'https://github.com/flutter/flutter.git';
static const String defaultBranch = 'master';
Future<CiYaml> get ciYaml async {
final CiYaml ciYaml =
CiYaml((await checkoutDirectory).childFile('.ci.yaml'));
return ciYaml;
}
Future<String> get cacheDirectory async {
return fileSystem.path.join(
(await checkoutDirectory).path,
'bin',
'cache',
);
}
/// Tag [commit] and push the tag to the remote.
Future<void> tag(String commit, String tagName, String remote) async {
assert(commit.isNotEmpty);
assert(tagName.isNotEmpty);
assert(remote.isNotEmpty);
stdio.printStatus('About to tag commit $commit as $tagName...');
await git.run(
<String>['tag', tagName, commit],
'tag the commit with the version label',
workingDirectory: (await checkoutDirectory).path,
);
stdio.printStatus('Tagging successful.');
stdio.printStatus('About to push $tagName to remote $remote...');
await git.run(
<String>['push', remote, tagName],
'publish the tag to the repo',
workingDirectory: (await checkoutDirectory).path,
);
stdio.printStatus('Tag push successful.');
}
@override
Future<Repository> cloneRepository(String? cloneName) async {
assert(localUpstream);
cloneName ??= 'clone-of-$name';
return FrameworkRepository(
checkouts,
name: cloneName,
upstreamRemote: Remote(
name: RemoteName.upstream,
url: 'file://${(await checkoutDirectory).path}/'),
);
}
Future<void> _ensureToolReady() async {
final File toolsStamp = fileSystem
.directory(await cacheDirectory)
.childFile('flutter_tools.stamp');
if (toolsStamp.existsSync()) {
final String toolsStampHash = toolsStamp.readAsStringSync().trim();
final String repoHeadHash = await reverseParse('HEAD');
if (toolsStampHash == repoHeadHash) {
return;
}
}
stdio.printTrace('Building tool...');
// Build tool
await processManager.run(<String>[
fileSystem.path.join((await checkoutDirectory).path, 'bin', 'flutter'),
'help',
]);
}
Future<io.ProcessResult> runFlutter(List<String> args) async {
await _ensureToolReady();
return processManager.run(<String>[
fileSystem.path.join((await checkoutDirectory).path, 'bin', 'flutter'),
...args,
]);
}
@override
Future<void> checkout(String ref) async {
await 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(await cacheDirectory);
if (cache.existsSync()) {
stdio.printTrace('Deleting cache...');
cache.deleteSync(recursive: true);
}
await _ensureToolReady();
}
Future<Version> flutterVersion() async {
// Check version
final io.ProcessResult result =
await runFlutter(<String>['--version', '--machine']);
final Map<String, dynamic> versionJson = jsonDecode(
stdoutToString(result.stdout),
) as Map<String, dynamic>;
return Version.fromString(versionJson['frameworkVersion'] as String);
}
/// Update this framework's engine version file.
///
/// Returns [true] if the version file was updated and a commit is needed.
Future<bool> updateEngineRevision(
String newEngine, {
@visibleForTesting File? engineVersionFile,
}) async {
assert(newEngine.isNotEmpty);
engineVersionFile ??= (await checkoutDirectory)
.childDirectory('bin')
.childDirectory('internal')
.childFile('engine.version');
assert(engineVersionFile.existsSync());
final String oldEngine = engineVersionFile.readAsStringSync();
if (oldEngine.trim() == newEngine.trim()) {
stdio.printTrace(
'Tried to update the engine revision but version file is already up to date at: $newEngine',
);
return false;
}
stdio.printStatus('Updating engine revision from $oldEngine to $newEngine');
engineVersionFile.writeAsStringSync(
// Version files have trailing newlines
'${newEngine.trim()}\n',
flush: true,
);
return true;
}
}
/// 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',
required String upstreamPath,
}) : super(
checkouts,
name: name,
upstreamRemote: Remote(
name: RemoteName.upstream,
url: 'file://$upstreamPath/',
),
localUpstream: false,
) {
_checkoutDirectory = checkouts.fileSystem.directory(upstreamPath);
}
@override
Future<Directory> get checkoutDirectory async => _checkoutDirectory!;
@override
Future<void> newBranch(String branchName) async {
throw ConductorException(
'newBranch not implemented for the host repository');
}
@override
Future<void> checkout(String ref) async {
throw ConductorException(
'checkout not implemented for the host repository');
}
@override
Future<String> cherryPick(String commit) async {
throw ConductorException(
'cherryPick not implemented for the host repository');
}
@override
Future<String> reset(String ref) async {
throw ConductorException('reset not implemented for the host repository');
}
@override
Future<void> tag(String commit, String tagName, String remote) async {
throw ConductorException('tag not implemented for the host repository');
}
void updateChannel(
String commit,
String remote,
String branch, {
bool force = false,
bool dryRun = false,
}) {
throw ConductorException(
'updateChannel not implemented for the host repository');
}
@override
Future<String> authorEmptyCommit([String message = 'An empty commit']) async {
throw ConductorException(
'authorEmptyCommit not implemented for the host repository',
);
}
}
class EngineRepository extends Repository {
EngineRepository(
this.checkouts, {
String name = 'engine',
String initialRef = EngineRepository.defaultBranch,
Remote upstreamRemote = const Remote(
name: RemoteName.upstream, url: EngineRepository.defaultUpstream),
bool localUpstream = false,
String? previousCheckoutLocation,
Remote? mirrorRemote,
}) : super(
name: name,
upstreamRemote: upstreamRemote,
mirrorRemote: mirrorRemote,
initialRef: initialRef,
fileSystem: checkouts.fileSystem,
localUpstream: localUpstream,
parentDirectory: checkouts.directory,
platform: checkouts.platform,
processManager: checkouts.processManager,
stdio: checkouts.stdio,
previousCheckoutLocation: previousCheckoutLocation,
);
final Checkouts checkouts;
Future<CiYaml> get ciYaml async {
final CiYaml ciYaml = CiYaml((await checkoutDirectory).childFile('.ci.yaml'));
return ciYaml;
}
static const String defaultUpstream = 'https://github.com/flutter/engine.git';
static const String defaultBranch = 'master';
/// Update the `dart_revision` entry in the DEPS file.
Future<void> updateDartRevision(
String newRevision, {
@visibleForTesting File? depsFile,
}) async {
assert(newRevision.length == 40);
depsFile ??= (await 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, flush: true);
}
@override
Future<Repository> cloneRepository(String? cloneName) async {
assert(localUpstream);
cloneName ??= 'clone-of-$name';
return EngineRepository(
checkouts,
name: cloneName,
upstreamRemote: Remote(
name: RemoteName.upstream,
url: 'file://${(await checkoutDirectory).path}/'),
);
}
}
/// 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;
}
class CiYaml {
CiYaml(this.file) {
if (!file.existsSync()) {
throw ConductorException('Could not find the .ci.yaml file at ${file.path}');
}
}
/// Underlying [File] that this object wraps.
final File file;
/// Returns the raw string contents of this file.
///
/// This is not cached as the contents can be written to while the conductor
/// is running.
String get stringContents => file.readAsStringSync();
/// Returns the parsed contents of the file as a [YamlMap].
///
/// This is not cached as the contents can be written to while the conductor
/// is running.
YamlMap get contents => loadYaml(stringContents) as YamlMap;
List<String> get enabledBranches {
final YamlList yamlList = contents['enabled_branches'] as YamlList;
return yamlList.map<String>((dynamic element) {
return element as String;
}).toList();
}
static final RegExp _enabledBranchPattern = RegExp(r'enabled_branches:');
/// Update this .ci.yaml file with the given branch name.
///
/// The underlying [File] is written to, but not committed to git. This method
/// will throw a [ConductorException] if the [branchName] is already present
/// in the file or if the file does not have an "enabled_branches:" field.
void enableBranch(String branchName) {
final List<String> newStrings = <String>[];
if (enabledBranches.contains(branchName)) {
throw ConductorException('${file.path} already contains the branch $branchName');
}
if (!_enabledBranchPattern.hasMatch(stringContents)) {
throw ConductorException(
'Did not find the expected string "enabled_branches:" in the file ${file.path}',
);
}
final List<String> lines = stringContents.split('\n');
bool insertedCurrentBranch = false;
for (final String line in lines) {
// Every existing line should be copied to the new Yaml
newStrings.add(line);
if (insertedCurrentBranch) {
continue;
}
if (_enabledBranchPattern.hasMatch(line)) {
insertedCurrentBranch = true;
// Indent two spaces
final String indent = ' ' * 2;
newStrings.add('$indent- ${branchName.trim()}');
}
}
file.writeAsStringSync(newStrings.join('\n'), flush: true);
}
}

View File

@@ -0,0 +1,205 @@
// 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 kCandidateBranch = 'candidate-branch';
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(
kCandidateBranch,
help: 'Specifies which git branch to roll to the dev branch. Required.',
valueHelp: 'branch',
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
Future<void> run() async {
await rollDev(
argResults: argResults!,
repository: FrameworkRepository(checkouts),
stdio: stdio,
usage: argParser.usage,
);
}
}
/// Main script execution.
///
/// Returns true if publishing was successful, else false.
@visibleForTesting
Future<bool> rollDev({
required String usage,
required ArgResults argResults,
required Stdio stdio,
required FrameworkRepository repository,
}) async {
final String remoteName = argResults[kRemoteName] as String;
final String? level = argResults[kIncrement] as String?;
final String candidateBranch = argResults[kCandidateBranch] 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 || candidateBranch == null) {
throw Exception(
'roll_dev.dart --$kIncrement=level --$kCandidateBranch=branch • update the version tags '
'and roll a new dev build.\n$usage');
}
final String remoteUrl = await repository.remoteUrl(remoteName);
if (!(await 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.');
}
await repository.fetch(remoteName);
// Verify [commit] is valid
final String commit = await repository.reverseParse(candidateBranch);
stdio.printStatus('remoteName is $remoteName');
// Get the name of the last dev release
final Version lastVersion = Version.fromString(
await repository.getFullTag(remoteName, 'dev'),
);
final Version version =
skipTagging ? lastVersion : Version.fromCandidateBranch(candidateBranch);
final String tagName = version.toString();
if ((await 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 && !(await repository.isCommitTagged(commit))) {
throw Exception(
'The $kSkipTagging flag is only supported for tagged commits.');
}
if (!force && !(await 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 = await 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) {
await repository.tag(commit, version.toString(), remoteName);
}
await repository.pushRef(
fromRef: commit,
remote: remoteName,
toRef: 'dev',
force: force,
);
stdio.printStatus(
'Flutter version $version has been rolled to the "dev" channel at $remoteUrl.',
);
return true;
}

View File

@@ -0,0 +1,424 @@
// 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:fixnum/fixnum.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';
import './version.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 kIncrementOption = 'increment';
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.',
);
argParser.addOption(
kIncrementOption,
help: 'Specifies which part of the x.y.z version number to increment. Required.',
valueHelp: 'level',
allowed: <String>['y', 'z', 'm', 'n'],
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.',
'n': 'Indicates a hotfix to a dev or beta release.',
},
);
}
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.
late final String conductorVersion;
@override
String get name => 'start';
@override
String get description => 'Initialize a new Flutter release.';
@override
Future<void> run() async {
final Git git = Git(processManager);
conductorVersion = (await git.getOutput(
<String>['rev-parse', 'HEAD'],
'look up the current revision.',
workingDirectory: flutterRoot.path,
)).trim();
assert(conductorVersion.isNotEmpty);
final ArgResults argumentResults = argResults!;
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, argumentResults, 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,
argumentResults,
platform.environment,
)!;
final String frameworkMirror = getValueFromEnvOrArgs(
kFrameworkMirrorOption,
argumentResults,
platform.environment,
)!;
final String engineUpstream = getValueFromEnvOrArgs(
kEngineUpstreamOption,
argumentResults,
platform.environment,
)!;
final String engineMirror = getValueFromEnvOrArgs(
kEngineMirrorOption,
argumentResults,
platform.environment,
)!;
final String candidateBranch = getValueFromEnvOrArgs(
kCandidateOption,
argumentResults,
platform.environment,
)!;
final String releaseChannel = getValueFromEnvOrArgs(
kReleaseOption,
argumentResults,
platform.environment,
)!;
final List<String> frameworkCherrypickRevisions = getValuesFromEnvOrArgs(
kFrameworkCherrypicksOption,
argumentResults,
platform.environment,
);
final List<String> engineCherrypickRevisions = getValuesFromEnvOrArgs(
kEngineCherrypicksOption,
argumentResults,
platform.environment,
);
final String? dartRevision = getValueFromEnvOrArgs(
kDartRevisionOption,
argumentResults,
platform.environment,
allowNull: true,
);
final String incrementLetter = getValueFromEnvOrArgs(
kIncrementOption,
argumentResults,
platform.environment,
)!;
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;
state.incrementLevel = incrementLetter;
final EngineRepository engine = EngineRepository(
checkouts,
initialRef: candidateBranch,
upstreamRemote: Remote(
name: RemoteName.upstream,
url: engineUpstream,
),
mirrorRemote: Remote(
name: RemoteName.mirror,
url: engineMirror,
),
);
// Create a new branch so that we don't accidentally push to upstream
// candidateBranch.
final String workingBranchName = 'cherrypicks-$candidateBranch';
await engine.newBranch(workingBranchName);
if (dartRevision != null && dartRevision.isNotEmpty) {
await engine.updateDartRevision(dartRevision);
await engine.commit('Update Dart SDK to $dartRevision', addFirst: true);
}
final List<pb.Cherrypick> engineCherrypicks = (await _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 = await engine.canCherryPick(revision);
stdio.printTrace(
'Attempt to cherrypick $revision ${success ? 'succeeded' : 'failed'}',
);
if (success) {
await engine.cherryPick(revision);
cherrypick.state = pb.CherrypickState.COMPLETED;
} else {
cherrypick.state = pb.CherrypickState.PENDING_WITH_CONFLICT;
}
}
final String engineHead = await engine.reverseParse('HEAD');
state.engine = pb.Repository(
candidateBranch: candidateBranch,
workingBranch: workingBranchName,
startingGitHead: engineHead,
currentGitHead: engineHead,
checkoutPath: (await engine.checkoutDirectory).path,
cherrypicks: engineCherrypicks,
dartRevision: dartRevision,
upstream: pb.Remote(name: 'upstream', url: engine.upstreamRemote.url),
mirror: pb.Remote(name: 'mirror', url: engine.mirrorRemote!.url),
);
final FrameworkRepository framework = FrameworkRepository(
checkouts,
initialRef: candidateBranch,
upstreamRemote: Remote(
name: RemoteName.upstream,
url: frameworkUpstream,
),
mirrorRemote: Remote(
name: RemoteName.mirror,
url: frameworkMirror,
),
);
await framework.newBranch(workingBranchName);
final List<pb.Cherrypick> frameworkCherrypicks = (await _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 = await framework.canCherryPick(revision);
stdio.printTrace(
'Attempt to cherrypick $cherrypick ${success ? 'succeeded' : 'failed'}',
);
if (success) {
await framework.cherryPick(revision);
cherrypick.state = pb.CherrypickState.COMPLETED;
} else {
cherrypick.state = pb.CherrypickState.PENDING_WITH_CONFLICT;
}
}
// Get framework version
final Version lastVersion = Version.fromString(await framework.getFullTag(
framework.upstreamRemote.name, candidateBranch,
exact: false));
Version nextVersion;
if (incrementLetter == 'm') {
nextVersion = Version.fromCandidateBranch(candidateBranch);
} else {
if (incrementLetter == 'z') {
if (lastVersion.type == VersionType.stable) {
nextVersion = Version.increment(lastVersion, incrementLetter);
} else {
// This is the first stable release, so hardcode the z as 0
nextVersion = Version(
x: lastVersion.x,
y: lastVersion.y,
z: 0,
type: VersionType.stable,
);
}
} else {
nextVersion = Version.increment(lastVersion, incrementLetter);
}
}
state.releaseVersion = nextVersion.toString();
final String frameworkHead = await framework.reverseParse('HEAD');
state.framework = pb.Repository(
candidateBranch: candidateBranch,
workingBranch: workingBranchName,
startingGitHead: frameworkHead,
currentGitHead: frameworkHead,
checkoutPath: (await framework.checkoutDirectory).path,
cherrypicks: frameworkCherrypicks,
upstream: pb.Remote(name: 'upstream', url: framework.upstreamRemote.url),
mirror: pb.Remote(name: 'mirror', url: framework.mirrorRemote!.url),
);
state.currentPhase = ReleasePhase.APPLY_ENGINE_CHERRYPICKS;
state.conductorVersion = conductorVersion;
stdio.printTrace('Writing state to file ${stateFile.path}...');
writeStateToFile(stateFile, state, stdio.logs);
stdio.printStatus(presentState(state));
}
// To minimize merge conflicts, sort the commits by rev-list order.
Future<List<String>> _sortCherrypicks({
required Repository repository,
required List<String> cherrypicks,
required String upstreamRef,
required String releaseRef,
}) async {
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 = await repository.reverseParse(cherrypick);
validatedCherrypicks.add(fullRef);
} on GitException {
// Catch this exception so that we can validate the rest.
unknownCherrypicks.add(cherrypick);
}
}
final String branchPoint = await repository.branchPoint(
'${repository.upstreamRemote.name}/$upstreamRef',
'${repository.upstreamRemote.name}/$releaseRef',
);
// `git rev-list` returns newest first, so reverse this list
final List<String> upstreamRevlist = (await 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

@@ -0,0 +1,281 @@
// 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 JsonEncoder, jsonDecode;
import 'package:file/file.dart' show File;
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', 'packaging'].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) {
final String? home = platform.environment['HOME'];
if (home == null) {
throw ConductorException(r'Environment variable $HOME must be set!');
}
return <String>[
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('Release version: ${state.releaseVersion}');
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.currentPhase == ReleasePhase.VERIFY_RELEASE) {
buffer.writeln(
'${state.releaseChannel} release ${state.releaseVersion} has been published and verified.\n',
);
return buffer.toString();
}
buffer.writeln('The current phase is:');
buffer.writeln(presentPhases(state.currentPhase));
buffer.writeln(phaseInstructions(state));
buffer.writeln('');
buffer.writeln('Issue `conductor next` when you are ready to proceed.');
return buffer.toString();
}
String presentPhases(ReleasePhase currentPhase) {
final StringBuffer buffer = StringBuffer();
bool phaseCompleted = true;
for (final ReleasePhase phase in ReleasePhase.values) {
if (phase == currentPhase) {
// This phase will execute the next time `conductor next` is run.
buffer.writeln('> ${phase.name} (current)');
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.currentPhase) {
case ReleasePhase.APPLY_ENGINE_CHERRYPICKS:
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.CODESIGN_ENGINE_BINARIES:
if (!requiresEnginePR(state)) {
return 'You must now codesign the engine binaries for commit '
'${state.engine.startingGitHead}.';
}
// User's working branch was pushed to their mirror, but a PR needs to be
// opened on GitHub.
final String newPrLink = getNewPrLink(
userName: githubAccount(state.engine.mirror.url),
repoName: 'engine',
state: state,
);
return <String>[
'Your working branch ${state.engine.workingBranch} was pushed to your mirror.',
'You must now open a pull request at $newPrLink, verify pre-submit CI',
'builds on your engine pull request are successful, merge your pull request,',
'validate post-submit CI, and then codesign the binaries on the merge commit.',
].join('\n');
case ReleasePhase.APPLY_FRAMEWORK_CHERRYPICKS:
final List<pb.Cherrypick> outstandingCherrypicks = state.framework.cherrypicks.where(
(pb.Cherrypick cp) {
return cp.state == pb.CherrypickState.PENDING || cp.state == pb.CherrypickState.PENDING_WITH_CONFLICT;
},
).toList();
if (outstandingCherrypicks.isNotEmpty) {
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 outstandingCherrypicks) '\t${cherrypick.trunkRevision}',
].join('\n');
}
return <String>['Either all cherrypicks have been auto-applied or there were none.'].join('\n');
case ReleasePhase.PUBLISH_VERSION:
if (!requiresFrameworkPR(state)) {
return 'Since there are no code changes in this release, no Framework '
'PR is necessary.';
}
final String newPrLink = getNewPrLink(
userName: githubAccount(state.framework.mirror.url),
repoName: 'flutter',
state: state,
);
return <String>[
'Your working branch ${state.framework.workingBranch} was pushed to your mirror.',
'You must now open a pull request at $newPrLink',
'verify pre-submit CI builds on your pull request are successful, merge your ',
'pull request, validate post-submit CI.',
].join('\n');
case ReleasePhase.PUBLISH_CHANNEL:
return 'Issue `conductor next` to publish your release to the release branch.';
case ReleasePhase.VERIFY_RELEASE:
return 'Release archive packages must be verified on cloud storage: ${luciConsoleLink(state.releaseChannel, 'packaging')}';
case ReleasePhase.RELEASE_COMPLETED:
return 'This release has been completed.';
}
// For analyzer
throw ConductorException('Unimplemented phase ${state.currentPhase}');
}
/// Regex pattern for git remote host URLs.
///
/// First group = git host (currently must be github.com)
/// Second group = account name
/// Third group = repo name
final RegExp githubRemotePattern =
RegExp(r'^(git@github\.com:|https?:\/\/github\.com\/)([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_-]+)(\.git)?$');
/// Parses a Git remote URL and returns the account name.
///
/// Uses [githubRemotePattern].
String githubAccount(String remoteUrl) {
final String engineUrl = remoteUrl;
final RegExpMatch? match = githubRemotePattern.firstMatch(engineUrl);
if (match == null) {
throw ConductorException(
'Cannot determine the GitHub account from $engineUrl',
);
}
final String? accountName = match.group(2);
if (accountName == null || accountName.isEmpty) {
throw ConductorException(
'Cannot determine the GitHub account from $match',
);
}
return accountName;
}
/// Returns the next phase in the ReleasePhase enum.
///
/// Will throw a [ConductorException] if [ReleasePhase.RELEASE_COMPLETED] is
/// passed as an argument, as there is no next phase.
ReleasePhase getNextPhase(ReleasePhase currentPhase) {
assert(currentPhase != null);
final ReleasePhase? nextPhase = ReleasePhase.valueOf(currentPhase.value + 1);
if (nextPhase == null) {
throw ConductorException('There is no next ReleasePhase!');
}
return nextPhase;
}
// Indent two spaces.
const JsonEncoder _encoder = JsonEncoder.withIndent(' ');
void writeStateToFile(File file, pb.ConductorState state, List<String> logs) {
state.logs.addAll(logs);
file.writeAsStringSync(
_encoder.convert(state.toProto3Json()),
flush: true,
);
}
pb.ConductorState readStateFromFile(File file) {
final pb.ConductorState state = pb.ConductorState();
final String stateAsString = file.readAsStringSync();
state.mergeFromProto3Json(
jsonDecode(stateAsString),
);
return state;
}
/// This release will require a new Engine PR.
///
/// The logic is if there are engine cherrypicks that have not been abandoned OR
/// there is a new Dart revision, then return true, else false.
bool requiresEnginePR(pb.ConductorState state) {
final bool hasRequiredCherrypicks = state.engine.cherrypicks.any(
(pb.Cherrypick cp) => cp.state != pb.CherrypickState.ABANDONED,
);
if (hasRequiredCherrypicks) {
return true;
}
return state.engine.dartRevision.isNotEmpty;
}
/// This release will require a new Framework PR.
///
/// The logic is if there was an Engine PR OR there are framework cherrypicks
/// that have not been abandoned.
bool requiresFrameworkPR(pb.ConductorState state) {
if (requiresEnginePR(state)) {
return true;
}
final bool hasRequiredCherrypicks =
state.framework.cherrypicks.any((pb.Cherrypick cp) => cp.state != pb.CherrypickState.ABANDONED);
if (hasRequiredCherrypicks) {
return true;
}
return false;
}

View File

@@ -0,0 +1,65 @@
// 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:file/file.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 = readStateFromFile(stateFile);
stdio.printStatus(presentState(state));
if (argResults![kVerboseFlag] as bool) {
stdio.printStatus('\nLogs:');
state.logs.forEach(stdio.printStatus);
}
}
}

View File

@@ -0,0 +1,86 @@
// 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

@@ -0,0 +1,267 @@
// 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 './globals.dart' show ConductorException;
/// 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,
/// A master channel flutter version from git describe.
///
/// Example: '1.2.3-4.0.pre-10-gabc123'.
gitDescribe,
}
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+)$'),
VersionType.gitDescribe: RegExp(r'^(\d+)\.(\d+)\.(\d+)-(\d+)\.(\d+)\.pre-(\d+)-g[a-f0-9]+$'),
};
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;
case VersionType.gitDescribe:
throw ConductorException(
'VersionType.gitDescribe not supported! Use VersionType.latest instead.',
);
}
}
/// 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,
);
}
match = versionPatterns[VersionType.gitDescribe]!.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 || previousVersion.type == VersionType.gitDescribe) {
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':
assert(false, "Do not increment 'm' via Version.increment, use instead Version.fromCandidateBranch()");
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,
);
}
factory Version.fromCandidateBranch(String branchName) {
// Regular dev release.
final RegExp pattern = RegExp(r'flutter-(\d+)\.(\d+)-candidate.(\d+)');
final RegExpMatch? match = pattern.firstMatch(branchName);
late final int x;
late final int y;
late final int m;
try {
x = int.parse(match!.group(1)!);
y = int.parse(match.group(2)!);
m = int.parse(match.group(3)!);
} on Exception {
throw ConductorException('branch named $branchName not recognized as a valid candidate branch');
}
return Version(
type: VersionType.development,
x: x,
y: y,
z: 0,
m: m,
n: 0,
);
}
/// 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';
case VersionType.gitDescribe:
return '$x.$y.$z-$m.$n.pre.$commits';
}
}
}

View File

@@ -0,0 +1,71 @@
name: conductor_core
description: Flutter Automated Release Tool
publish_to: none
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
archive: 3.1.2
args: 2.3.0
http: 0.13.3
intl: 0.17.0
meta: 1.7.0
path: 1.8.0
process: 4.2.3
protobuf: 2.0.0
async: 2.8.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
charcode: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
clock: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
collection: 1.15.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
crypto: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
file: 6.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
fixnum: 1.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
http_parser: 4.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
pedantic: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
platform: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_span: 1.8.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
string_scanner: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
term_glyph: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
typed_data: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
dev_dependencies:
test: 1.17.12
test_api: 0.4.3
_fe_analyzer_shared: 26.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
analyzer: 2.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
boolean_selector: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
cli_util: 0.3.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
convert: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
coverage: 1.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
frontend_server_client: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
glob: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
http_multi_server: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
io: 1.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
js: 0.6.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
logging: 1.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
matcher: 0.12.11 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
mime: 1.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
node_preamble: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
package_config: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
pool: 1.5.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
pub_semver: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf: 1.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_packages_handler: 3.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_static: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_web_socket: 1.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_map_stack_trace: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_maps: 0.10.10 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stack_trace: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stream_channel: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
test_core: 0.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vm_service: 7.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
watcher: 1.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
web_socket_channel: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
webkit_inspection_protocol: 1.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
yaml: 3.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
# PUBSPEC CHECKSUM: 134a

View File

@@ -0,0 +1,153 @@
// 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:conductor_core/src/candidates.dart';
import 'package:conductor_core/src/repository.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.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);
});
}, onPlatform: <String, dynamic>{
'windows': const Skip('Flutter Conductor only supported on macos/linux'),
});
}

View File

@@ -0,0 +1,81 @@
// 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:conductor_core/src/clean.dart';
import 'package:conductor_core/src/repository.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import './common.dart';
void main() {
group('clean command', () {
const String flutterRoot = '/flutter';
const String checkoutsParentDirectory = '$flutterRoot/dev/tools/';
late MemoryFileSystem fileSystem;
late FakePlatform platform;
late TestStdio stdio;
late FakeProcessManager processManager;
late CommandRunner<void> runner;
setUp(() {
stdio = TestStdio();
fileSystem = MemoryFileSystem.test();
final String operatingSystem = const LocalPlatform().operatingSystem;
final String pathSeparator = operatingSystem == 'windows' ? r'\' : '/';
processManager = FakeProcessManager.empty();
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,
);
runner = CommandRunner<void>('clean-test', '')..addCommand(command);
});
test('throws if no state file found', () async {
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 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

@@ -0,0 +1,83 @@
// 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:conductor_core/src/codesign.dart' show CodesignCommand;
import 'package:conductor_core/src/globals.dart';
import 'package:conductor_core/src/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 Directory flutterRoot = _flutterRootFromDartBinary(
fileSystem.file(platform.executable),
);
final CommandRunner<void> runner = CommandRunner<void>('codesign-test', '')
..addCommand(
CodesignCommand(checkouts: checkouts, flutterRoot: flutterRoot));
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'),
});
}
Directory _flutterRootFromDartBinary(File dartBinary) {
final Directory flutterDartSdkDir = dartBinary.parent.parent;
final Directory flutterCache = flutterDartSdkDir.parent;
final Directory flutterSdkDir = flutterCache.parent.parent;
return flutterSdkDir;
}
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

@@ -0,0 +1,501 @@
// 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:conductor_core/src/codesign.dart';
import 'package:conductor_core/src/repository.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import './common.dart';
void main() {
group('codesign command', () {
const String flutterRoot = '/flutter';
const String checkoutsParentDirectory = '$flutterRoot/dev/conductor/';
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: Future<List<String>>.value(binariesWithEntitlements),
binariesWithoutEntitlements: Future<List<String>>.value(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('does not fail if --revision flag not provided', () 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',
'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']);
expect(processManager.hasRemainingExpectations, false);
expect(stdio.stdout, contains('Verified that binaries are codesigned and have expected entitlements'));
});
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);
expect(stdio.stdout, contains('Verified that binaries for commit $revision are codesigned and have expected entitlements'));
});
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,
]);
await expectLater(
() => 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,
]);
await expectLater(
() => 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',
),
]);
await runner.run(<String>[
'codesign',
'--$kVerify',
'--no-$kSignatures',
'--$kRevision',
revision,
]);
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 Future<List<String>> binariesWithEntitlements;
@override
final Future<List<String>> binariesWithoutEntitlements;
}

View File

@@ -0,0 +1,112 @@
// 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:conductor_core/src/stdio.dart';
import 'package:test/test.dart';
export 'package:test/test.dart' hide isInstanceOf;
export '../../../../packages/flutter_tools/test/src/fake_process_manager.dart';
Matcher throwsAssertionWith(String messageSubString) {
return throwsA(
isA<AssertionError>().having(
(AssertionError e) => e.toString(),
'description',
contains(messageSubString),
),
);
}
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] ') || log.startsWith(r'[write] ');
}).join('\n');
final bool verbose;
late final List<String> _stdin;
List<String> get stdin => _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 candidateBranch,
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,
'candidate-branch': candidateBranch,
'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

@@ -0,0 +1,132 @@
// 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:conductor_core/src/globals.dart';
import 'package:conductor_core/src/proto/conductor_state.pb.dart' as pb;
import './common.dart';
void main() {
test('assertsEnabled returns true in test suite', () {
expect(assertsEnabled(), true);
});
group('getNewPrLink', () {
const String userName = 'flutterer';
const String releaseChannel = 'beta';
const String releaseVersion = '1.2.0-3.4.pre';
const String candidateBranch = 'flutter-1.2-candidate.3';
const String workingBranch = 'cherrypicks-$candidateBranch';
const String dartRevision = 'fe9708ab688dcda9923f584ba370a66fcbc3811f';
const String engineCherrypick1 = 'a5a25cd702b062c24b2c67b8d30b5cb33e0ef6f0';
const String engineCherrypick2 = '94d06a2e1d01a3b0c693b94d70c5e1df9d78d249';
const String frameworkCherrypick =
'a5a25cd702b062c24b2c67b8d30b5cb33e0ef6f0';
final RegExp titlePattern = RegExp(r'&title=(.*)&');
final RegExp bodyPattern = RegExp(r'&body=(.*)$');
late pb.ConductorState state;
setUp(() {
state = pb.ConductorState(
engine: pb.Repository(
candidateBranch: candidateBranch,
cherrypicks: <pb.Cherrypick>[
pb.Cherrypick(trunkRevision: engineCherrypick1),
pb.Cherrypick(trunkRevision: engineCherrypick2),
],
dartRevision: dartRevision,
workingBranch: workingBranch,
),
framework: pb.Repository(
candidateBranch: candidateBranch,
cherrypicks: <pb.Cherrypick>[
pb.Cherrypick(trunkRevision: frameworkCherrypick),
],
workingBranch: workingBranch,
),
releaseChannel: releaseChannel,
releaseVersion: releaseVersion,
);
});
test('throws on an invalid repoName', () {
expect(
() => getNewPrLink(
repoName: 'flooter',
userName: userName,
state: state,
),
throwsExceptionWith(
'Expected repoName to be one of flutter or engine but got flooter.',
),
);
});
test('returns a valid URL for engine', () {
final String link = getNewPrLink(
repoName: 'engine',
userName: userName,
state: state,
);
expect(
link,
contains('https://github.com/flutter/engine/compare/'),
);
expect(
link,
contains('$candidateBranch...$userName:$workingBranch?expand=1'),
);
expect(
Uri.decodeQueryComponent(
titlePattern.firstMatch(link)?.group(1) ?? ''),
'[flutter_releases] Flutter $releaseChannel $releaseVersion Engine Cherrypicks');
final String expectedBody = '''
# Flutter $releaseChannel $releaseVersion Engine
## Scheduled Cherrypicks
- Roll dart revision: dart-lang/sdk@${dartRevision.substring(0, 9)}
- commit: flutter/engine@${engineCherrypick1.substring(0, 9)}
- commit: flutter/engine@${engineCherrypick2.substring(0, 9)}
''';
expect(
Uri.decodeQueryComponent(bodyPattern.firstMatch(link)?.group(1) ?? ''),
expectedBody,
);
});
test('returns a valid URL for framework', () {
final String link = getNewPrLink(
repoName: 'flutter',
userName: userName,
state: state,
);
expect(
link,
contains('https://github.com/flutter/flutter/compare/'),
);
expect(
link,
contains('$candidateBranch...$userName:$workingBranch?expand=1'),
);
expect(
Uri.decodeQueryComponent(
titlePattern.firstMatch(link)?.group(1) ?? ''),
'[flutter_releases] Flutter $releaseChannel $releaseVersion Framework Cherrypicks');
final String expectedBody = '''
# Flutter $releaseChannel $releaseVersion Framework
## Scheduled Cherrypicks
- commit: ${frameworkCherrypick.substring(0, 9)}
''';
expect(
Uri.decodeQueryComponent(bodyPattern.firstMatch(link)?.group(1) ?? ''),
expectedBody,
);
});
});
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,523 @@
// 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:conductor_core/src/repository.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.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', () async {
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(await repository.canCherryPick(commit), true);
});
test('canCherryPick returns false if git cherry-pick returns non-zero', () async {
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(await repository.canCherryPick(commit), false);
});
test('cherryPick() applies the commit', () async {
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);
await repository.cherryPick(commit);
expect(processManager.hasRemainingExpectations, false);
});
test('updateDartRevision() updates the DEPS file', () async {
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));
await 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(
() async => repo.updateDartRevision(nextDartRevision, depsFile: depsFile),
throwsExceptionWith('Unexpected content in the DEPS file at'),
);
});
test('commit() throws if there are no local changes to commit', () {
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',
'status',
'--porcelain',
]),
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);
expect(
() async => repo.commit(message),
throwsExceptionWith('Tried to commit with message $message but no changes were present'),
);
});
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', 'status', '--porcelain'],
stdout: 'MM path/to/file.txt',
),
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);
});
test('updateEngineRevision() returns false if newCommit is the same as version file', () async {
const String commit1 = 'abc123';
const String commit2 = 'def456';
final TestStdio stdio = TestStdio();
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final File engineVersionFile = fileSystem.file('/engine.version')..writeAsStringSync(commit2);
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: commit1),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final FrameworkRepository repo = FrameworkRepository(checkouts);
final bool didUpdate = await repo.updateEngineRevision(commit2, engineVersionFile: engineVersionFile);
expect(didUpdate, false);
});
test('CiYaml(file) will throw if file does not exist', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final File file = fileSystem.file('/non/existent/file.txt');
expect(
() => CiYaml(file),
throwsExceptionWith('Could not find the .ci.yaml file at /non/existent/file.txt'),
);
});
test('ciYaml.enableBranch() will prepend the given branch to the yaml list of enabled_branches', () async {
const String commit1 = 'abc123';
final TestStdio stdio = TestStdio();
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final File ciYaml = fileSystem.file('/flutter_conductor_checkouts/framework/.ci.yaml');
final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
fileSystem.path
.join(rootDir, 'flutter_conductor_checkouts', 'framework'),
],
onRun: () {
ciYaml.createSync(recursive: true);
ciYaml.writeAsStringSync('''
# Friendly note
enabled_branches:
- master
- dev
- beta
- stable
''');
}),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit1),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final FrameworkRepository framework = FrameworkRepository(checkouts);
expect(
(await framework.ciYaml).enabledBranches,
<String>['master', 'dev', 'beta', 'stable'],
);
(await framework.ciYaml).enableBranch('foo');
expect(
(await framework.ciYaml).enabledBranches,
<String>['foo', 'master', 'dev', 'beta', 'stable'],
);
expect(
(await framework.ciYaml).stringContents,
'''
# Friendly note
enabled_branches:
- foo
- master
- dev
- beta
- stable
'''
);
});
test('ciYaml.enableBranch() will throw if the input branch is already present in the yaml file', () {
const String commit1 = 'abc123';
final TestStdio stdio = TestStdio();
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final File ciYaml = fileSystem.file('/flutter_conductor_checkouts/framework/.ci.yaml');
final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
fileSystem.path
.join(rootDir, 'flutter_conductor_checkouts', 'framework'),
],
onRun: () {
ciYaml.createSync(recursive: true);
ciYaml.writeAsStringSync('''
enabled_branches:
- master
- dev
- beta
- stable
''');
}),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: commit1),
]);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(rootDir),
platform: platform,
processManager: processManager,
stdio: stdio,
);
final FrameworkRepository framework = FrameworkRepository(checkouts);
expect(
() async => (await framework.ciYaml).enableBranch('master'),
throwsExceptionWith('.ci.yaml already contains the branch master'),
);
});
});
}
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

@@ -0,0 +1,707 @@
// 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:conductor_core/src/globals.dart';
import 'package:conductor_core/src/repository.dart';
import 'package:conductor_core/src/roll_dev.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.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-2.0.pre';
const String candidateBranch = 'flutter-1.2-candidate.2';
const String checkoutsParentDirectory = '/path/to/directory/';
late FakeArgResults fakeArgResults;
late MemoryFileSystem fileSystem;
late TestStdio stdio;
late FrameworkRepository repo;
late Checkouts checkouts;
late FakePlatform platform;
late 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('throws Exception if level not provided', () {
fakeArgResults = FakeArgResults(
level: null,
candidateBranch: candidateBranch,
remote: remote,
);
expect(
() async => rollDev(
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
usage: usage,
),
throwsExceptionWith(usage),
);
});
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,
candidateBranch: candidateBranch,
remote: remote,
);
expect(
() async => rollDev(
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
usage: usage,
),
throwsExceptionWith('Your git repository is not clean.'),
);
});
test('does not reset or tag if --just-print is specified', () async {
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',
candidateBranch,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*',
'--exact-match',
'--tags',
'refs/remotes/$remote/dev',
], stdout: lastVersion),
const FakeCommand(command: <String>[
'git',
'rev-parse',
lastVersion,
], stdout: 'zxy321'),
]);
fakeArgResults = FakeArgResults(
level: level,
candidateBranch: candidateBranch,
remote: remote,
justPrint: true,
);
expect(
await 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',
candidateBranch,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*',
'--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,
candidateBranch: candidateBranch,
remote: remote,
skipTagging: true,
);
expect(
() async => 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',
candidateBranch,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*',
'--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,
candidateBranch: candidateBranch,
remote: remote,
justPrint: true,
);
expect(
() async => 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',
candidateBranch,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*',
'--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,
candidateBranch: candidateBranch,
remote: remote,
);
const String errorMessage = 'The previous dev tag $lastVersion is not a '
'direct ancestor of $commit.';
expect(
() async => rollDev(
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
usage: usage,
),
throwsExceptionWith(errorMessage),
);
});
test('does not tag but updates branch if --skip-tagging provided', () async {
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',
candidateBranch,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*',
'--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,
candidateBranch: candidateBranch,
remote: remote,
skipTagging: true,
);
expect(
await rollDev(
usage: usage,
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
),
true,
);
});
test('successfully tags and publishes release', () async {
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',
candidateBranch,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*',
'--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,
candidateBranch: candidateBranch,
remote: remote,
);
expect(
await rollDev(
usage: usage,
argResults: fakeArgResults,
repository: repo,
stdio: stdio,
),
true,
);
});
test('successfully publishes release with --force', () async {
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',
candidateBranch,
], stdout: commit),
const FakeCommand(command: <String>[
'git',
'describe',
'--match',
'*.*.*',
'--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,
candidateBranch: candidateBranch,
remote: remote,
force: true,
);
expect(
await 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

@@ -0,0 +1,494 @@
// 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 'package:args/command_runner.dart';
import 'package:conductor_core/src/proto/conductor_state.pb.dart' as pb;
import 'package:conductor_core/src/proto/conductor_state.pbenum.dart' show ReleasePhase;
import 'package:conductor_core/src/repository.dart';
import 'package:conductor_core/src/start.dart';
import 'package:conductor_core/src/state.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.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';
late Checkouts checkouts;
late MemoryFileSystem fileSystem;
late FakePlatform platform;
late TestStdio stdio;
late 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);
}
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';
const String previousVersion = '1.2.0-1.0.pre';
const String nextVersion = '1.2.0-3.0.pre';
const String incrementLevel = 'm';
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', 'status', '--porcelain'],
stdout: 'MM path/to/DEPS',
),
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',
'describe',
'--match',
'*.*.*',
'--tags',
'refs/remotes/upstream/$candidateBranch',
],
stdout: '$previousVersion-42-gabc123',
),
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,
'--$kIncrementOption',
incrementLevel,
]);
final File stateFile = fileSystem.file(stateFilePath);
final pb.ConductorState state = pb.ConductorState();
state.mergeFromProto3Json(
jsonDecode(stateFile.readAsStringSync()),
);
expect(processManager.hasRemainingExpectations, false);
expect(state.isInitialized(), true);
expect(state.releaseChannel, releaseChannel);
expect(state.releaseVersion, nextVersion);
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.currentPhase, ReleasePhase.APPLY_ENGINE_CHERRYPICKS);
expect(state.conductorVersion, revision);
expect(state.incrementLevel, incrementLevel);
});
test('can convert from dev style version to stable version', () async {
const String revision2 = 'def789';
const String revision3 = '123abc';
const String previousDartRevision = '171876a4e6cf56ee6da1f97d203926bd7afda7ef';
const String nextDartRevision = 'f6c91128be6b77aef8351e1e3a9d07c85bc2e46e';
const String previousVersion = '1.2.0-1.0.pre';
const String nextVersion = '1.2.0';
const String incrementLevel = 'z';
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', 'status', '--porcelain'],
stdout: 'MM path/to/DEPS',
),
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',
'describe',
'--match',
'*.*.*',
'--tags',
'refs/remotes/upstream/$candidateBranch',
],
stdout: '$previousVersion-42-gabc123',
),
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,
'--$kIncrementOption',
incrementLevel,
]);
final File stateFile = fileSystem.file(stateFilePath);
final pb.ConductorState state = pb.ConductorState();
state.mergeFromProto3Json(
jsonDecode(stateFile.readAsStringSync()),
);
expect(processManager.hasRemainingExpectations, false);
expect(state.isInitialized(), true);
expect(state.releaseChannel, releaseChannel);
expect(state.releaseVersion, nextVersion);
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.currentPhase, ReleasePhase.APPLY_ENGINE_CHERRYPICKS);
expect(state.conductorVersion, revision);
expect(state.incrementLevel, incrementLevel);
});
}, 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

@@ -0,0 +1,68 @@
// 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:conductor_core/src/proto/conductor_state.pb.dart' as pb;
import 'package:conductor_core/src/state.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import './common.dart';
void main() {
test('writeStateToFile() pretty-prints JSON with 2 spaces', () {
final MemoryFileSystem fileSystem = MemoryFileSystem.test();
final File stateFile = fileSystem.file('/path/to/statefile.json')
..createSync(recursive: true);
const String candidateBranch = 'flutter-2.3-candidate.0';
final pb.ConductorState state = pb.ConductorState(
releaseChannel: 'stable',
releaseVersion: '2.3.4',
incrementLevel: 'z',
engine: pb.Repository(
candidateBranch: candidateBranch,
upstream: pb.Remote(
name: 'upstream',
url: 'https://github.com/flutter/engine.git',
),
),
framework: pb.Repository(
candidateBranch: candidateBranch,
upstream: pb.Remote(
name: 'upstream',
url: 'https://github.com/flutter/flutter.git',
),
),
);
writeStateToFile(
stateFile,
state,
<String>['[status] hello world'],
);
final String serializedState = stateFile.readAsStringSync();
const String expectedString = '''
{
"releaseChannel": "stable",
"releaseVersion": "2.3.4",
"engine": {
"candidateBranch": "flutter-2.3-candidate.0",
"upstream": {
"name": "upstream",
"url": "https://github.com/flutter/engine.git"
}
},
"framework": {
"candidateBranch": "flutter-2.3-candidate.0",
"upstream": {
"name": "upstream",
"url": "https://github.com/flutter/flutter.git"
}
},
"logs": [
"[status] hello world"
],
"incrementLevel": "z"
}''';
expect(serializedState, expectedString);
});
}

View File

@@ -0,0 +1,84 @@
// 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:conductor_core/src/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 = 'z';
Version version = Version.fromString('1.0.0');
expect(Version.increment(version, level).toString(), '1.0.1');
version = Version.fromString('10.20.0');
expect(Version.increment(version, level).toString(), '10.20.1');
version = Version.fromString('1.18.3');
expect(Version.increment(version, level).toString(), '1.18.4');
});
test('does not support incrementing m', () {
const String level = 'm';
final Version version = Version.fromString('1.0.0-0.0.pre');
expect(
() => Version.increment(version, level).toString(),
throwsAssertionWith("Do not increment 'm' via Version.increment"),
);
});
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'),
});
}