status method

Future<GitStatusResult> status({
  1. String? path,
})

Returns the current repository status including branch tracking info, file changes, and stash count.

Implementation

Future<GitStatusResult> status({String? path}) async {
  final workDir = path ?? defaultWorkDir;

  // Porcelain v2 gives machine-readable output.
  final result = await _runGit([
    'status',
    '--porcelain=v2',
    '--branch',
    '--untracked-files=normal',
  ], workDir: workDir);

  String? branch;
  String? upstream;
  int ahead = 0;
  int behind = 0;
  final changes = <GitFileChange>[];

  for (final line in LineSplitter.split(result.stdout as String)) {
    if (line.startsWith('# branch.head ')) {
      branch = line.substring('# branch.head '.length);
    } else if (line.startsWith('# branch.upstream ')) {
      upstream = line.substring('# branch.upstream '.length);
    } else if (line.startsWith('# branch.ab ')) {
      final parts = line.substring('# branch.ab '.length).split(' ');
      if (parts.length >= 2) {
        ahead = int.tryParse(parts[0].replaceFirst('+', '')) ?? 0;
        behind = int.tryParse(parts[1].replaceFirst('-', '')) ?? 0;
      }
    } else if (line.startsWith('1 ') || line.startsWith('2 ')) {
      changes.add(_parseStatusLine(line));
    } else if (line.startsWith('? ')) {
      final filePath = line.substring(2);
      changes.add(
        GitFileChange(
          path: filePath,
          status: GitFileStatus.untracked,
          staged: false,
        ),
      );
    }
  }

  // Detect special repo states.
  final repoStatus = await _detectRepoStatus(workDir);

  // Stash count.
  int stashCount = 0;
  try {
    final stashResult = await _runGit(['stash', 'list'], workDir: workDir);
    final stashOutput = (stashResult.stdout as String).trim();
    if (stashOutput.isNotEmpty) {
      stashCount = LineSplitter.split(stashOutput).length;
    }
  } catch (_) {
    // Stash list may fail in bare repos.
  }

  return GitStatusResult(
    repoStatus: repoStatus,
    branch: branch,
    upstream: upstream,
    ahead: ahead,
    behind: behind,
    changes: changes,
    stashCount: stashCount,
  );
}