refactor: use rev-list --left-right --count to query track status with upstream (when using some linux with other locales instead of English, upstream:track will output status with localized word instead of 'ahead'/'behind')

This commit is contained in:
leo 2024-03-08 16:32:44 +08:00
parent 0d1c61bcb5
commit f7e8cf1311

View file

@ -6,13 +6,12 @@ namespace SourceGit.Commands {
public class QueryBranches : Command { public class QueryBranches : Command {
private static readonly string PREFIX_LOCAL = "refs/heads/"; private static readonly string PREFIX_LOCAL = "refs/heads/";
private static readonly string PREFIX_REMOTE = "refs/remotes/"; private static readonly string PREFIX_REMOTE = "refs/remotes/";
private static readonly Regex REG_AHEAD = new Regex(@"ahead (\d+)"); private static readonly Regex REG_AHEAD_BEHIND = new Regex(@"^(\d+)\s(\d+)$");
private static readonly Regex REG_BEHIND = new Regex(@"behind (\d+)");
public QueryBranches(string repo) { public QueryBranches(string repo) {
WorkingDirectory = repo; WorkingDirectory = repo;
Context = repo; Context = repo;
Args = "branch -l --all -v --format=\"%(refname)$%(objectname)$%(HEAD)$%(upstream)$%(upstream:track)\""; Args = "branch -l --all -v --format=\"%(refname)$%(objectname)$%(HEAD)$%(upstream)$(upstream:trackshort)\"";
} }
public List<Models.Branch> Result() { public List<Models.Branch> Result() {
@ -48,26 +47,31 @@ namespace SourceGit.Commands {
branch.Head = parts[1]; branch.Head = parts[1];
branch.IsCurrent = parts[2] == "*"; branch.IsCurrent = parts[2] == "*";
branch.Upstream = parts[3]; branch.Upstream = parts[3];
branch.UpstreamTrackStatus = ParseTrackStatus(parts[4]);
if (!string.IsNullOrEmpty(parts[4]) && !parts[4].Equals("=")) {
branch.UpstreamTrackStatus = ParseTrackStatus(branch.FullName, branch.Upstream);
}
_branches.Add(branch); _branches.Add(branch);
} }
private string ParseTrackStatus(string data) { private string ParseTrackStatus(string local, string upstream) {
if (string.IsNullOrEmpty(data)) return string.Empty; var cmd = new Command();
cmd.WorkingDirectory = WorkingDirectory;
cmd.Context = Context;
cmd.Args = $"rev-list --left-right --count {local}...{upstream}";
string track = string.Empty; var rs = cmd.ReadToEnd();
if (!rs.IsSuccess) return string.Empty;
var ahead = REG_AHEAD.Match(data); var match = REG_AHEAD_BEHIND.Match(rs.StdOut);
if (ahead.Success) { if (!match.Success) return string.Empty;
track += ahead.Groups[1].Value + "↑ ";
}
var behind = REG_BEHIND.Match(data);
if (behind.Success) {
track += behind.Groups[1].Value + "↓";
}
var ahead = int.Parse(match.Groups[1].Value);
var behind = int.Parse(match.Groups[2].Value);
var track = "";
if (ahead > 0) track += $"{ahead}↑";
if (behind > 0) track += $" {behind}↓";
return track.Trim(); return track.Trim();
} }