JGit and finding the Head

后端 未结 4 1907
名媛妹妹
名媛妹妹 2021-01-01 10:23

I\'m trying to get my hands on the HEAD commit with JGit:

val builder = new FileRepositoryBuilder()
val repo = builder.setGitDir(new File(\"/www/test-repo\")         


        
相关标签:
4条回答
  • 2021-01-01 10:57

    You can also use val git: Git = Git.open( new File( "/www/test-repo" ) ). JGit will then scan the given folder for the git meta directory (usually .git). If it fails to find this folder, an IOException will be thrown.

    0 讨论(0)
  • 2021-01-01 11:06

    You need to point to the Git metadata directory (probably /www/test-repo/.git) when you call setGitDir, not to the working directory (/www/test-repo).

    I have to admit I'm not sure what findGitDir is supposed to do, but I've run into this problem before and specifying the .git directory worked.

    0 讨论(0)
  • 2021-01-01 11:10

    For the completeness sake, here is a fully working example how to get the hash for the HEAD commit:

    public String getHeadName(Repository repo) {
      String result = null;
      try {
        ObjectId id = repo.resolve(Constants.HEAD);
        result = id.getName();
      } catch (IOException e) {
        e.printStackTrace();
      }
      return result;
    }
    
    0 讨论(0)
  • 2021-01-01 11:13

    For me (using 4.5.0.201609210915-r) the solution was to use just RepositoryBuilder instead of FileRepositoryBuilder. Until I made this change all methods were returning null.

    rb = new org.eclipse.jgit.lib.RepositoryBuilder()
        .readEnvironment()
        .findGitDir()
        .build();
    
    headRef = rb.getRef(rb.getFullBranch());
    headHash = headRef.getObjectId().name();
    
    0 讨论(0)
提交回复
热议问题