branches method

Future<List<GitBranch>> branches({
  1. bool all = false,
  2. String? workDir,
})

Lists branches. Set all to include remote-tracking branches.

Implementation

Future<List<GitBranch>> branches({bool all = false, String? workDir}) async {
  final args = <String>[
    'branch',
    '--format=%(HEAD)%(refname:short)|%(upstream:short)|%(upstream:track,nobracket)',
    if (all) '-a',
  ];

  final result = await _runGit(args, workDir: workDir ?? defaultWorkDir);
  final output = (result.stdout as String).trim();
  if (output.isEmpty) return [];

  final branchList = <GitBranch>[];

  for (final line in LineSplitter.split(output)) {
    final isCurrent = line.startsWith('*');
    final cleaned = isCurrent ? line.substring(1) : line;
    final parts = cleaned.split('|');

    final name = parts[0].trim();
    final upstreamName = parts.length > 1 && parts[1].isNotEmpty
        ? parts[1].trim()
        : null;
    final trackInfo = parts.length > 2 ? parts[2].trim() : '';

    int ahead = 0;
    int behind = 0;
    final aheadMatch = RegExp(r'ahead (\d+)').firstMatch(trackInfo);
    final behindMatch = RegExp(r'behind (\d+)').firstMatch(trackInfo);
    if (aheadMatch != null) ahead = int.parse(aheadMatch.group(1)!);
    if (behindMatch != null) behind = int.parse(behindMatch.group(1)!);

    branchList.add(
      GitBranch(
        name: name,
        isRemote: name.startsWith('remotes/') || name.contains('/'),
        isCurrent: isCurrent,
        upstream: upstreamName,
        ahead: ahead,
        behind: behind,
      ),
    );
  }

  return branchList;
}