Determine if a branch is remote or local (using JGit)?

Is there any way to determine if a branch is a remote or local branch (or both) using JGit? I have:

Map<String, Ref> allRefs = git.getRepository().getAllRefs();
Collection<Ref> values = allRefs.values();
for (Ref ref : values) {
  refs.add(ref.getName());
}

which gives:

HEAD
refs/heads/tmp01
refs/heads/master
refs/heads/newFeatureBranch
refs/heads/sampleBranch
refs/remotes/origin/master
refs/remotes/origin/newFeatureBranch

So newFeatureBranch is both a local and remote branch. Currently I check if ref.getName() contains "remotes/origin". But is there a better way to determine if a branch is remote or local?

Answers


The term "local branches" usually refers to refs in refs/heads. The term "remote branches" usually refers to refs in refs/remotes.

To list only local branches you use: git branch or git.branchList().call()

To list only remote branches you use: git branch -r or git.branchList().setListMode(ListMode.REMOTE).call()

To list both local and remote branches use: git branch -a or git.branchList().setListMode(ListMode.All).call()

The corresponding code from ListBranchCommand.java reads:

if (listMode == null) {
        refList = repo.getRefDatabase().getRefs(Constants.R_HEADS);
} else if (listMode == ListMode.REMOTE) {
        refList = repo.getRefDatabase().getRefs(Constants.R_REMOTES);
} else {
        refList = new HashMap<String,Ref>(repo.getRefDatabase().getRefs(
                        Constants.R_HEADS));
        refList.putAll(repo.getRefDatabase().getRefs(
                        Constants.R_REMOTES));
}

In git all branches are local ones. They all live in the local repository in .git/refs and are all just a pointer to a local commit.

What you call a "remote branch" is just a local branch created by git fetch.

How those "remote branches" are called is determined by git config remote.origin.fetch, which will usually simply tell git fetch to create a ref with name refs/remotes/origin/*.

Hence checking for the prefix of the name of the ref is exactly the right way.


Need Your Help

Individual Worksheet Passwords

excel vba

I've used the 'protection worksheet' option in Excel but in addition, I 'd like to ask the user to input a password upon clicking on each sheet. There's a specific password per sheet. If you don't ...

Minima in a region of 2d matrix with its indices

matlab matrix minima

I have a set of 18 MATLAB vectors (raw readings of current values) data that varies with many minimas and maximas put into a 2d matrix of B which has a size of 18 by 16348.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.