git.dart 3.97 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 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.

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 {
13
  const Git(this.processManager);
14 15 16

  final ProcessManager processManager;

17
  Future<String> getOutput(
18 19
    List<String> args,
    String explanation, {
20
    required String workingDirectory,
21
    bool allowFailures = false,
22 23
  }) async {
    final ProcessResult result = await _run(args, workingDirectory);
24 25 26 27 28 29
    if (result.exitCode == 0) {
      return stdoutToString(result.stdout);
    }
    _reportFailureAndExit(args, workingDirectory, result, explanation);
  }

30
  Future<int> run(
31 32 33
    List<String> args,
    String explanation, {
    bool allowNonZeroExitCode = false,
34
    required String workingDirectory,
35
  }) async {
36 37 38 39 40 41
    late final ProcessResult result;
    try {
      result = await _run(args, workingDirectory);
    } on ProcessException {
      _reportFailureAndExit(args, workingDirectory, result, explanation);
    }
42 43 44 45 46 47
    if (result.exitCode != 0 && !allowNonZeroExitCode) {
      _reportFailureAndExit(args, workingDirectory, result, explanation);
    }
    return result.exitCode;
  }

48 49
  Future<ProcessResult> _run(List<String> args, String workingDirectory) async {
    return processManager.run(
50 51
      <String>['git', ...args],
      workingDirectory: workingDirectory,
52
      environment: <String, String>{'GIT_TRACE': '1'},
53 54 55
    );
  }

56
  Never _reportFailureAndExit(
57 58 59 60 61 62 63 64 65 66 67 68 69 70
    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.');
    }
71
    if ((result.stdout as String).isNotEmpty) {
72
      message.writeln('stdout from git:\n${result.stdout}\n');
73 74
    }
    if ((result.stderr as String).isNotEmpty) {
75
      message.writeln('stderr from git:\n${result.stderr}\n');
76
    }
77
    throw GitException(message.toString(), args);
78 79
  }
}
80

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
enum GitExceptionType {
  /// Git push failed because the remote branch contained commits the local did
  /// not.
  ///
  /// Either the local branch was wrong, and needs a rebase before pushing
  /// again, or the remote branch needs to be overwritten with a force push.
  ///
  /// Example output:
  ///
  /// ```
  /// To github.com:user/engine.git
  ///
  ///  ! [rejected]            HEAD -> cherrypicks-flutter-2.8-candidate.3 (non-fast-forward)
  /// error: failed to push some refs to 'github.com:user/engine.git'
  /// hint: Updates were rejected because the tip of your current branch is behind
  /// hint: its remote counterpart. Integrate the remote changes (e.g.
  /// hint: 'git pull ...') before pushing again.
  /// hint: See the 'Note about fast-forwards' in 'git push --help' for details.
  /// ```
  PushRejected,
}

/// An exception created because a git subprocess failed.
///
/// Known git failures will be assigned a [GitExceptionType] in the [type]
/// field. If this field is null it means and unknown git failure.
107
class GitException implements Exception {
108 109 110 111 112 113 114 115 116 117 118 119 120
  GitException(this.message, this.args) {
    if (_pushRejectedPattern.hasMatch(message)) {
      type = GitExceptionType.PushRejected;
    } else {
      // because type is late final, it must be explicitly set before it is
      // accessed.
      type = null;
    }
  }

  static final RegExp _pushRejectedPattern = RegExp(
    r'Updates were rejected because the tip of your current branch is behind',
  );
121 122

  final String message;
123 124
  final List<String> args;
  late final GitExceptionType? type;
125 126

  @override
127
  String toString() => 'Exception on command "${args.join(' ')}": $message';
128
}