repository.dart 19.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// 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';
11
import 'package:process/process.dart';
12 13

import './git.dart';
14
import './globals.dart';
15 16 17
import './stdio.dart';
import './version.dart';

18 19 20 21 22 23 24 25
/// Allowed git remote names.
enum RemoteName {
  upstream,
  mirror,
}

class Remote {
  const Remote({
26 27
    required RemoteName name,
    required this.url,
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
  }) : _name = name;

  final RemoteName _name;

  /// The name of the remote.
  String get name {
    switch (_name) {
      case RemoteName.upstream:
        return 'upstream';
      case RemoteName.mirror:
        return 'mirror';
    }
  }

  /// The URL of the remote.
  final String url;
}

46
/// A source code repository.
47
abstract class Repository {
48
  Repository({
49 50 51 52 53 54 55
    required this.name,
    required this.fetchRemote,
    required this.processManager,
    required this.stdio,
    required this.platform,
    required this.fileSystem,
    required this.parentDirectory,
56
    this.initialRef,
57 58
    this.localUpstream = false,
    this.useExistingCheckout = false,
59
    this.pushRemote,
60 61 62 63 64
  })  : git = Git(processManager),
        assert(localUpstream != null),
        assert(useExistingCheckout != null);

  final String name;
65 66 67 68 69 70
  final Remote fetchRemote;

  /// Remote to publish tags and commits to.
  ///
  /// This value can be null, in which case attempting to publish will lead to
  /// a [ConductorException].
71
  final Remote? pushRemote;
72 73

  /// The initial ref (branch or commit name) to check out.
74
  final String? initialRef;
75 76 77 78 79 80 81 82 83 84 85
  final Git git;
  final ProcessManager processManager;
  final Stdio stdio;
  final Platform platform;
  final FileSystem fileSystem;
  final Directory parentDirectory;
  final bool useExistingCheckout;

  /// If the repository will be used as an upstream for a test repo.
  final bool localUpstream;

86
  Directory? _checkoutDirectory;
87

88
  /// Directory for the repository checkout.
89
  ///
90 91
  /// Since cloning a repository takes a long time, we do not ensure it is
  /// cloned on the filesystem until this getter is accessed.
92 93
  Directory get checkoutDirectory {
    if (_checkoutDirectory != null) {
94
      return _checkoutDirectory!;
95 96
    }
    _checkoutDirectory = parentDirectory.childDirectory(name);
97 98
    lazilyInitialize(_checkoutDirectory!);
    return _checkoutDirectory!;
99 100 101
  }

  /// Ensure the repository is cloned to disk and initialized with proper state.
102 103 104 105
  void lazilyInitialize(Directory checkoutDirectory) {
    if (!useExistingCheckout && checkoutDirectory.existsSync()) {
      stdio.printTrace('Deleting $name from ${checkoutDirectory.path}...');
      checkoutDirectory.deleteSync(recursive: true);
106
    }
107

108
    if (!checkoutDirectory.existsSync()) {
109
      stdio.printTrace(
110
        'Cloning $name from ${fetchRemote.url} to ${checkoutDirectory.path}...',
111
      );
112
      git.run(
113 114 115 116 117 118
        <String>[
          'clone',
          '--origin',
          fetchRemote.name,
          '--',
          fetchRemote.url,
119
          checkoutDirectory.path
120
        ],
121 122 123
        'Cloning $name repo',
        workingDirectory: parentDirectory.path,
      );
124 125
      if (pushRemote != null) {
        git.run(
126 127 128
          <String>['remote', 'add', pushRemote!.name, pushRemote!.url],
          'Adding remote ${pushRemote!.url} as ${pushRemote!.name}',
          workingDirectory: checkoutDirectory.path,
129 130
        );
        git.run(
131 132 133
          <String>['fetch', pushRemote!.name],
          'Fetching git remote ${pushRemote!.name}',
          workingDirectory: checkoutDirectory.path,
134 135
        );
      }
136 137 138
      if (localUpstream) {
        // These branches must exist locally for the repo that depends on it
        // to fetch and push to.
139
        for (final String channel in kReleaseChannels) {
140 141 142
          git.run(
            <String>['checkout', channel, '--'],
            'check out branch $channel locally',
143
            workingDirectory: checkoutDirectory.path,
144 145 146 147 148
          );
        }
      }
    }

149 150 151 152
    if (initialRef != null) {
      git.run(
        <String>['checkout', '${fetchRemote.name}/$initialRef'],
        'Checking out initialRef $initialRef',
153
        workingDirectory: checkoutDirectory.path,
154 155
      );
    }
156
    final String revision = reverseParse('HEAD');
157 158 159
    stdio.printTrace(
      'Repository $name is checked out at revision "$revision".',
    );
160 161
  }

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
  /// The URL of the remote named [remoteName].
  String remoteUrl(String remoteName) {
    assert(remoteName != null);
    return git.getOutput(
      <String>['remote', 'get-url', remoteName],
      'verify the URL of the $remoteName remote',
      workingDirectory: checkoutDirectory.path,
    );
  }

  /// Verify the repository's git checkout is clean.
  bool gitCheckoutClean() {
    final String output = git.getOutput(
      <String>['status', '--porcelain'],
      'check that the git checkout is clean',
      workingDirectory: checkoutDirectory.path,
    );
    return output == '';
  }

182 183 184 185 186 187 188 189 190
  /// Return the revision for the branch point between two refs.
  String branchPoint(String firstRef, String secondRef) {
    return git.getOutput(
      <String>['merge-base', firstRef, secondRef],
      'determine the merge base between $firstRef and $secondRef',
      workingDirectory: checkoutDirectory.path,
    ).trim();
  }

191 192 193 194 195 196 197 198 199
  /// Fetch all branches and associated commits and tags from [remoteName].
  void fetch(String remoteName) {
    git.run(
      <String>['fetch', remoteName, '--tags'],
      'fetch $remoteName --tags',
      workingDirectory: checkoutDirectory.path,
    );
  }

200 201 202 203
  /// Create (and checkout) a new branch based on the current HEAD.
  ///
  /// Runs `git checkout -b $branchName`.
  void newBranch(String branchName) {
204
    git.run(
205 206 207 208 209 210 211 212 213 214 215
      <String>['checkout', '-b', branchName],
      'create & checkout new branch $branchName',
      workingDirectory: checkoutDirectory.path,
    );
  }

  /// Check out the given ref.
  void checkout(String ref) {
    git.run(
      <String>['checkout', ref],
      'checkout ref',
216 217 218 219
      workingDirectory: checkoutDirectory.path,
    );
  }

220 221 222 223 224 225 226 227 228 229 230 231
  /// Obtain the version tag of the previous dev release.
  String getFullTag(String remoteName) {
    const String glob = '*.*.*-*.*.pre';
    // describe the latest dev release
    final String ref = 'refs/remotes/$remoteName/dev';
    return git.getOutput(
      <String>['describe', '--match', glob, '--exact-match', '--tags', ref],
      'obtain last released version number',
      workingDirectory: checkoutDirectory.path,
    );
  }

232 233 234 235 236 237 238 239 240 241 242 243
  /// List commits in reverse chronological order.
  List<String> revList(List<String> args) {
    return git
        .getOutput(
          <String>['rev-list', ...args],
          'rev-list with args ${args.join(' ')}',
          workingDirectory: checkoutDirectory.path,
        )
        .trim()
        .split('\n');
  }

244 245 246 247 248 249
  /// Look up the commit for [ref].
  String reverseParse(String ref) {
    final String revisionHash = git.getOutput(
      <String>['rev-parse', ref],
      'look up the commit for the ref $ref',
      workingDirectory: checkoutDirectory.path,
250
    );
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    assert(revisionHash.isNotEmpty);
    return revisionHash;
  }

  /// Determines if one ref is an ancestor for another.
  bool isAncestor(String possibleAncestor, String possibleDescendant) {
    final int exitcode = git.run(
      <String>[
        'merge-base',
        '--is-ancestor',
        possibleDescendant,
        possibleAncestor
      ],
      'verify $possibleAncestor is a direct ancestor of $possibleDescendant.',
      allowNonZeroExitCode: true,
      workingDirectory: checkoutDirectory.path,
    );
    return exitcode == 0;
  }

  /// Determines if a given commit has a tag.
  bool isCommitTagged(String commit) {
    final int exitcode = git.run(
      <String>['describe', '--exact-match', '--tags', commit],
      'verify $commit is already tagged',
      allowNonZeroExitCode: true,
      workingDirectory: checkoutDirectory.path,
    );
    return exitcode == 0;
  }

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
  /// Determines if a commit will cherry-pick to current HEAD without conflict.
  bool canCherryPick(String commit) {
    assert(
      gitCheckoutClean(),
      'cannot cherry-pick because git checkout ${checkoutDirectory.path} is not clean',
    );

    final int exitcode = git.run(
      <String>['cherry-pick', '--no-commit', commit],
      'attempt to cherry-pick $commit without committing',
      allowNonZeroExitCode: true,
      workingDirectory: checkoutDirectory.path,
    );

    final bool result = exitcode == 0;

    if (result == false) {
      stdio.printError(git.getOutput(
        <String>['diff'],
        'get diff of failed cherry-pick',
        workingDirectory: checkoutDirectory.path,
      ));
    }

    reset('HEAD');
    return result;
  }

  /// Cherry-pick a [commit] to the current HEAD.
  ///
  /// This method will throw a [GitException] if the command fails.
  void cherryPick(String commit) {
    assert(
      gitCheckoutClean(),
      'cannot cherry-pick because git checkout ${checkoutDirectory.path} is not clean',
    );

    git.run(
320 321
      <String>['cherry-pick', commit],
      'cherry-pick $commit',
322 323 324 325 326 327
      workingDirectory: checkoutDirectory.path,
    );
  }

  /// Resets repository HEAD to [ref].
  void reset(String ref) {
328
    git.run(
329 330
      <String>['reset', ref, '--hard'],
      'reset to $ref',
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
      workingDirectory: checkoutDirectory.path,
    );
  }

  /// Tag [commit] and push the tag to the remote.
  void tag(String commit, String tagName, String remote) {
    git.run(
      <String>['tag', tagName, commit],
      'tag the commit with the version label',
      workingDirectory: checkoutDirectory.path,
    );
    git.run(
      <String>['push', remote, tagName],
      'publish the tag to the repo',
      workingDirectory: checkoutDirectory.path,
    );
  }

  /// Push [commit] to the release channel [branch].
  void updateChannel(
    String commit,
    String remote,
    String branch, {
    bool force = false,
  }) {
    git.run(
      <String>[
        'push',
        if (force) '--force',
        remote,
        '$commit:$branch',
      ],
      'update the release branch with the commit',
      workingDirectory: checkoutDirectory.path,
    );
  }

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
  String commit(
    String message, {
    bool addFirst = false,
  }) {
    assert(!message.contains("'"));
    if (addFirst) {
      git.run(
        <String>['add', '--all'],
        'add all changes to the index',
        workingDirectory: checkoutDirectory.path,
      );
    }
    git.run(
      <String>['commit', "--message='$message'"],
      'commit changes',
      workingDirectory: checkoutDirectory.path,
    );
    return reverseParse('HEAD');
  }

388 389 390 391 392 393 394 395 396 397 398 399
  /// Create an empty commit and return the revision.
  @visibleForTesting
  String authorEmptyCommit([String message = 'An empty commit']) {
    git.run(
      <String>[
        '-c',
        'user.name=Conductor',
        '-c',
        'user.email=conductor@flutter.dev',
        'commit',
        '--allow-empty',
        '-m',
400
        "'$message'",
401 402 403 404 405 406 407 408 409 410 411 412 413 414
      ],
      'create an empty commit',
      workingDirectory: checkoutDirectory.path,
    );
    return reverseParse('HEAD');
  }

  /// Create a new clone of the current repository.
  ///
  /// The returned repository will inherit all properties from this one, except
  /// for the upstream, which will be the path to this repository on disk.
  ///
  /// This method is for testing purposes.
  @visibleForTesting
415 416 417 418 419 420 421
  Repository cloneRepository(String cloneName);
}

class FrameworkRepository extends Repository {
  FrameworkRepository(
    this.checkouts, {
    String name = 'framework',
422 423
    Remote fetchRemote = const Remote(
        name: RemoteName.upstream, url: FrameworkRepository.defaultUpstream),
424 425
    bool localUpstream = false,
    bool useExistingCheckout = false,
426 427
    String? initialRef,
    Remote? pushRemote,
428 429
  }) : super(
          name: name,
430 431 432
          fetchRemote: fetchRemote,
          pushRemote: pushRemote,
          initialRef: initialRef,
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
          fileSystem: checkouts.fileSystem,
          localUpstream: localUpstream,
          parentDirectory: checkouts.directory,
          platform: checkouts.platform,
          processManager: checkouts.processManager,
          stdio: checkouts.stdio,
          useExistingCheckout: useExistingCheckout,
        );

  /// A [FrameworkRepository] with the host conductor's repo set as upstream.
  ///
  /// This is useful when testing a commit that has not been merged upstream
  /// yet.
  factory FrameworkRepository.localRepoAsUpstream(
    Checkouts checkouts, {
    String name = 'framework',
    bool useExistingCheckout = false,
450
    required String upstreamPath,
451 452 453 454
  }) {
    return FrameworkRepository(
      checkouts,
      name: name,
455 456 457 458
      fetchRemote: Remote(
        name: RemoteName.upstream,
        url: 'file://$upstreamPath/',
      ),
459 460 461 462 463 464 465 466 467
      localUpstream: false,
      useExistingCheckout: useExistingCheckout,
    );
  }

  final Checkouts checkouts;
  static const String defaultUpstream =
      'https://github.com/flutter/flutter.git';

468 469
  static const String defaultBranch = 'master';

470 471 472 473 474 475 476
  String get cacheDirectory => fileSystem.path.join(
        checkoutDirectory.path,
        'bin',
        'cache',
      );

  @override
477
  Repository cloneRepository(String? cloneName) {
478 479
    assert(localUpstream);
    cloneName ??= 'clone-of-$name';
480 481
    return FrameworkRepository(
      checkouts,
482
      name: cloneName,
483 484
      fetchRemote: Remote(
          name: RemoteName.upstream, url: 'file://${checkoutDirectory.path}/'),
485 486 487
      useExistingCheckout: useExistingCheckout,
    );
  }
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

  void _ensureToolReady() {
    final File toolsStamp =
        fileSystem.directory(cacheDirectory).childFile('flutter_tools.stamp');
    if (toolsStamp.existsSync()) {
      final String toolsStampHash = toolsStamp.readAsStringSync().trim();
      final String repoHeadHash = reverseParse('HEAD');
      if (toolsStampHash == repoHeadHash) {
        return;
      }
    }

    stdio.printTrace('Building tool...');
    // Build tool
    processManager.runSync(<String>[
      fileSystem.path.join(checkoutDirectory.path, 'bin', 'flutter'),
      'help',
    ]);
  }

  io.ProcessResult runFlutter(List<String> args) {
    _ensureToolReady();

    return processManager.runSync(<String>[
      fileSystem.path.join(checkoutDirectory.path, 'bin', 'flutter'),
      ...args,
    ]);
  }

  @override
518 519
  void checkout(String ref) {
    super.checkout(ref);
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    // The tool will overwrite old cached artifacts, but not delete unused
    // artifacts from a previous version. Thus, delete the entire cache and
    // re-populate.
    final Directory cache = fileSystem.directory(cacheDirectory);
    if (cache.existsSync()) {
      stdio.printTrace('Deleting cache...');
      cache.deleteSync(recursive: true);
    }
    _ensureToolReady();
  }

  Version flutterVersion() {
    // Check version
    final io.ProcessResult result =
        runFlutter(<String>['--version', '--machine']);
    final Map<String, dynamic> versionJson = jsonDecode(
536
      stdoutToString(result.stdout),
537 538 539
    ) as Map<String, dynamic>;
    return Version.fromString(versionJson['frameworkVersion'] as String);
  }
540 541
}

542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
/// A wrapper around the host repository that is executing the conductor.
///
/// [Repository] methods that mutate the underlying repository will throw a
/// [ConductorException].
class HostFrameworkRepository extends FrameworkRepository {
  HostFrameworkRepository({
    required Checkouts checkouts,
    String name = 'host-framework',
    bool useExistingCheckout = false,
    required String upstreamPath,
  }) : super(
    checkouts,
    name: name,
    fetchRemote: Remote(
      name: RemoteName.upstream,
      url: 'file://$upstreamPath/',
    ),
    localUpstream: false,
    useExistingCheckout: useExistingCheckout,
  ) {
    _checkoutDirectory = checkouts.fileSystem.directory(upstreamPath);
  }

  @override
  Directory get checkoutDirectory => _checkoutDirectory!;

  @override
  void newBranch(String branchName) {
    throw ConductorException('newBranch not implemented for the host repository');
  }

  @override
  void checkout(String ref) {
    throw ConductorException('checkout not implemented for the host repository');
  }

  @override
  String cherryPick(String commit) {
    throw ConductorException('cherryPick not implemented for the host repository');
  }

  @override
  String reset(String ref) {
    throw ConductorException('reset not implemented for the host repository');
  }

  @override
  void tag(String commit, String tagName, String remote) {
    throw ConductorException('tag not implemented for the host repository');
  }

  @override
  void updateChannel(
    String commit,
    String remote,
    String branch, {
    bool force = false,
  }) {
    throw ConductorException('updateChannel not implemented for the host repository');
  }

  @override
  String authorEmptyCommit([String message = 'An empty commit']) {
    throw ConductorException(
      'authorEmptyCommit not implemented for the host repository',
    );
  }
}

611 612 613 614 615 616 617 618 619
class EngineRepository extends Repository {
  EngineRepository(
    this.checkouts, {
    String name = 'engine',
    String initialRef = EngineRepository.defaultBranch,
    Remote fetchRemote = const Remote(
        name: RemoteName.upstream, url: EngineRepository.defaultUpstream),
    bool localUpstream = false,
    bool useExistingCheckout = false,
620
    Remote? pushRemote,
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
  }) : super(
          name: name,
          fetchRemote: fetchRemote,
          pushRemote: pushRemote,
          initialRef: initialRef,
          fileSystem: checkouts.fileSystem,
          localUpstream: localUpstream,
          parentDirectory: checkouts.directory,
          platform: checkouts.platform,
          processManager: checkouts.processManager,
          stdio: checkouts.stdio,
          useExistingCheckout: useExistingCheckout,
        );

  final Checkouts checkouts;

  static const String defaultUpstream = 'https://github.com/flutter/engine.git';
  static const String defaultBranch = 'master';

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
  /// Update the `dart_revision` entry in the DEPS file.
  void updateDartRevision(
    String newRevision, {
    @visibleForTesting File? depsFile,
  }) {
    assert(newRevision.length == 40);
    depsFile ??= checkoutDirectory.childFile('DEPS');
    final String fileContent = depsFile.readAsStringSync();
    final RegExp dartPattern = RegExp("[ ]+'dart_revision': '([a-z0-9]{40})',");
    final Iterable<RegExpMatch> allMatches = dartPattern.allMatches(fileContent);
    if (allMatches.length != 1) {
      throw ConductorException(
        'Unexpected content in the DEPS file at ${depsFile.path}\n'
        'Expected to find pattern ${dartPattern.pattern} 1 times, but got '
        '${allMatches.length}.'
      );
    }
    final String updatedFileContent = fileContent.replaceFirst(
      dartPattern,
      "  'dart_revision': '$newRevision',",
    );

    depsFile.writeAsStringSync(updatedFileContent);
  }

665
  @override
666
  Repository cloneRepository(String? cloneName) {
667 668 669 670 671 672 673 674 675 676 677 678
    assert(localUpstream);
    cloneName ??= 'clone-of-$name';
    return EngineRepository(
      checkouts,
      name: cloneName,
      fetchRemote: Remote(
          name: RemoteName.upstream, url: 'file://${checkoutDirectory.path}/'),
      useExistingCheckout: useExistingCheckout,
    );
  }
}

679 680 681 682 683 684 685 686
/// An enum of all the repositories that the Conductor supports.
enum RepositoryType {
  framework,
  engine,
}

class Checkouts {
  Checkouts({
687 688 689 690 691
    required this.fileSystem,
    required this.platform,
    required this.processManager,
    required this.stdio,
    required Directory parentDirectory,
692
    String directoryName = 'flutter_conductor_checkouts',
693
  })  : directory = parentDirectory.childDirectory(directoryName) {
694 695 696 697 698
    if (!directory.existsSync()) {
      directory.createSync(recursive: true);
    }
  }

699
  final Directory directory;
700
  final FileSystem fileSystem;
701
  final Platform platform;
702
  final ProcessManager processManager;
703
  final Stdio stdio;
704
}