sourcegit/src/Commands/QueryBranches.cs

81 lines
2.9 KiB
C#
Raw Normal View History

using System;
2021-04-29 05:05:55 -07:00
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace SourceGit.Commands {
public class QueryBranches : Command {
2021-04-29 05:05:55 -07:00
private static readonly string PREFIX_LOCAL = "refs/heads/";
private static readonly string PREFIX_REMOTE = "refs/remotes/";
private static readonly Regex REG_AHEAD_BEHIND = new Regex(@"^(\d+)\s(\d+)$");
2021-04-29 05:05:55 -07:00
public QueryBranches(string repo) {
WorkingDirectory = repo;
Context = repo;
Args = "branch -l --all -v --format=\"%(refname)$%(objectname)$%(HEAD)$%(upstream)$(upstream:trackshort)\"";
2021-04-29 05:05:55 -07:00
}
public List<Models.Branch> Result() {
Exec();
return _branches;
2021-04-29 05:05:55 -07:00
}
protected override void OnReadline(string line) {
var parts = line.Split('$');
if (parts.Length != 5) return;
2021-04-29 05:05:55 -07:00
var branch = new Models.Branch();
var refName = parts[0];
2021-04-29 05:05:55 -07:00
if (refName.EndsWith("/HEAD")) return;
if (refName.StartsWith(PREFIX_LOCAL, StringComparison.Ordinal)) {
branch.Name = refName.Substring(PREFIX_LOCAL.Length);
branch.IsLocal = true;
} else if (refName.StartsWith(PREFIX_REMOTE, StringComparison.Ordinal)) {
var name = refName.Substring(PREFIX_REMOTE.Length);
var shortNameIdx = name.IndexOf('/');
if (shortNameIdx < 0) return;
branch.Remote = name.Substring(0, shortNameIdx);
2021-04-29 05:05:55 -07:00
branch.Name = name.Substring(branch.Remote.Length + 1);
branch.IsLocal = false;
} else {
branch.Name = refName;
branch.IsLocal = true;
}
branch.FullName = refName;
branch.Head = parts[1];
branch.IsCurrent = parts[2] == "*";
branch.Upstream = parts[3];
if (!string.IsNullOrEmpty(parts[4]) && !parts[4].Equals("=")) {
branch.UpstreamTrackStatus = ParseTrackStatus(branch.FullName, branch.Upstream);
}
2021-04-29 05:05:55 -07:00
_branches.Add(branch);
2021-04-29 05:05:55 -07:00
}
private string ParseTrackStatus(string local, string upstream) {
var cmd = new Command();
cmd.WorkingDirectory = WorkingDirectory;
cmd.Context = Context;
cmd.Args = $"rev-list --left-right --count {local}...{upstream}";
2021-04-29 05:05:55 -07:00
var rs = cmd.ReadToEnd();
if (!rs.IsSuccess) return string.Empty;
2021-04-29 05:05:55 -07:00
var match = REG_AHEAD_BEHIND.Match(rs.StdOut);
if (!match.Success) return string.Empty;
2021-04-29 05:05:55 -07:00
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}↓";
2021-04-29 05:05:55 -07:00
return track.Trim();
}
private List<Models.Branch> _branches = new List<Models.Branch>();
2021-04-29 05:05:55 -07:00
}
}