git.dart 2.31 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:io';

import 'package:process/process.dart';

import './globals.dart';

/// A wrapper around git process calls that can be mocked for unit testing.
class Git {
  Git(this.processManager) : assert(processManager != null);

  final ProcessManager processManager;

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

  int run(
    List<String> args,
    String explanation, {
    bool allowNonZeroExitCode = false,
34
    required String workingDirectory,
35 36 37 38 39 40 41 42 43 44 45 46
  }) {
    final ProcessResult result = _run(args, workingDirectory);
    if (result.exitCode != 0 && !allowNonZeroExitCode) {
      _reportFailureAndExit(args, workingDirectory, result, explanation);
    }
    return result.exitCode;
  }

  ProcessResult _run(List<String> args, String workingDirectory) {
    return processManager.runSync(
      <String>['git', ...args],
      workingDirectory: workingDirectory,
47
      environment: <String, String>{'GIT_TRACE': '1'},
48 49 50
    );
  }

51
  Never _reportFailureAndExit(
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
    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');
70
    throw GitException(message.toString());
71 72
  }
}
73 74 75 76 77 78 79 80 81

class GitException implements Exception {
  GitException(this.message);

  final String message;

  @override
  String toString() => 'Exception: $message';
}