1

I have a git repository which contains a sub-module and it is loaded to my local sandbox.

After updating the sub-module to the latest commit to which the remote repository is pointing too, I would like to find its latest commit SHA1 and the sub-module branch name.

While trying to fetch the branchName of the loaded sub-module the code always returns its SHA1 instead of the name.

// Method to find the localHeadCommit
public RevCommit fetchLocalHeadCommit(final String gitSubmoduleRootFolderPath) throws IOException {
try (Git gitSubmodule = Git.open(new File(resolveRootFolderPath(gitSubmoduleRootFolderPath)))) {
  Repository repository = gitSubmodule.getRepository();
  ObjectId localHeadObjId = repository.resolve("HEAD");
  try (RevWalk revWalk = new RevWalk(repository, 0)) {
    return revWalk.parseCommit(localHeadObjId);
  }
}

 // Method to find the submoduleBranchName
public String fetchBranchNameOfSubmodule(final String gitRootFolderPath) throws IOException {
 return fetchLocalHeadCommit(gitRootFolderPath).getName();
}


I expect the output of fetchBranchNameOfSubmodule() to be   
feature/SubmodulebrachName , but the actual output is 
4f8664429af63c0309c0f063436b911845e3d3a43

1) Do we have any other option to find the branchName of the locally loaded submodule ?

2) Also, How to find the branchName if multiple branches are pointing to the same commitId?

  • The goal of a submodule is to be on a specific commit, i.e., to *not* be on a branch. So submodules don't *have* branch names. Now, when you enter a submodule in order to *work on it*, you might want to *put* it onto a branch, so as to do work in it and make *new* commits; but otherwise it's at a *commit*. – torek Sep 17 '19 at 17:47

1 Answers1

-1

While trying to fetch the branch name of the loaded sub-module the code always returns its SHA1 instead of the name

When working with submodule, git checkout the SHA-1 and you are in a mode which is called detached HEAD

There are several ways to track which branch your submodule in pointing to right now, the easiest way is to create it with the given branch (tell the submodule to track the desired branch)

### Track specific branch
git submodule add -b <branch name> <url>

Also, How to find the branch name if multiple branches are pointing to the same commit?

Basically, you are in detached HEAD (im recommending to read this answer in order to understand what is detached HEAD: How to move HEAD back to a previous location? (Detached head) & Undo commits)

In detached HEAD it does not matter if the commit is from a branch or from tag since git only cares about the content.

It won't be much help but you can use the git contains <SHA-1> to get list of branches which includes this commit.

CodeWizard
  • 128,036
  • 21
  • 144
  • 167