1
2
3
4
5
6
7
8
9
10
11
12 package org.eclipse.jgit.lib;
13
14 import java.io.IOException;
15
16 import org.eclipse.jgit.revwalk.RevCommit;
17 import org.eclipse.jgit.revwalk.RevWalk;
18 import org.eclipse.jgit.revwalk.RevWalkUtils;
19 import org.eclipse.jgit.revwalk.filter.RevFilter;
20
21
22
23
24 public class BranchTrackingStatus {
25
26
27
28
29
30
31
32
33
34
35
36
37 public static BranchTrackingStatus of(Repository repository, String branchName)
38 throws IOException {
39
40 String shortBranchName = Repository.shortenRefName(branchName);
41 String fullBranchName = Constants.R_HEADS + shortBranchName;
42 BranchConfig branchConfig = new BranchConfig(repository.getConfig(),
43 shortBranchName);
44
45 String trackingBranch = branchConfig.getTrackingBranch();
46 if (trackingBranch == null)
47 return null;
48
49 Ref tracking = repository.exactRef(trackingBranch);
50 if (tracking == null)
51 return null;
52
53 Ref local = repository.exactRef(fullBranchName);
54 if (local == null)
55 return null;
56
57 try (RevWalk walk = new RevWalk(repository)) {
58
59 RevCommit localCommit = walk.parseCommit(local.getObjectId());
60 RevCommit trackingCommit = walk.parseCommit(tracking.getObjectId());
61
62 walk.setRevFilter(RevFilter.MERGE_BASE);
63 walk.markStart(localCommit);
64 walk.markStart(trackingCommit);
65 RevCommit mergeBase = walk.next();
66
67 walk.reset();
68 walk.setRevFilter(RevFilter.ALL);
69 int aheadCount = RevWalkUtils.count(walk, localCommit, mergeBase);
70 int behindCount = RevWalkUtils.count(walk, trackingCommit,
71 mergeBase);
72
73 return new BranchTrackingStatus(trackingBranch, aheadCount,
74 behindCount);
75 }
76 }
77
78 private final String remoteTrackingBranch;
79
80 private final int aheadCount;
81
82 private final int behindCount;
83
84 private BranchTrackingStatus(String remoteTrackingBranch, int aheadCount,
85 int behindCount) {
86 this.remoteTrackingBranch = remoteTrackingBranch;
87 this.aheadCount = aheadCount;
88 this.behindCount = behindCount;
89 }
90
91
92
93
94
95
96 public String getRemoteTrackingBranch() {
97 return remoteTrackingBranch;
98 }
99
100
101
102
103
104
105
106
107 public int getAheadCount() {
108 return aheadCount;
109 }
110
111
112
113
114
115
116
117
118 public int getBehindCount() {
119 return behindCount;
120 }
121 }