List commits associated with a given tag with JGit

前端 未结 2 983
无人及你
无人及你 2021-01-19 02:33

I need to create a history file that details all tags and for each tag, all its commits.

I\'ve tried to call getTags() on the repository object and use

2条回答
  •  长发绾君心
    2021-01-19 02:59

    To get a list of tags you can either use Repository#getTags() or the ListTagCommand.

    There are annotated and unannotated tags in Git. While unannotated tags directly point to the commit they were placed on, an annotated tag points to a git object that holds - among other meta data like a message - the commit-id.

    The learning test below ilustrates this:

    public class TagLearningTest {
    
      @Rule
      public final TemporaryFolder tempFolder = new TemporaryFolder();
    
      private Git git;
    
      @Test
      public void testUnannotatedTag() throws Exception {
        RevCommit commit = git.commit().setMessage( "Tag Me!" ).call();
    
        Ref tagRef = git.tag().setAnnotated( false ).setName( "Unannotated_Tag" ).call();
    
        assertEquals( commit.getId(), tagRef.getObjectId() );
        assertNull( git.getRepository().peel( tagRef ).getPeeledObjectId() );
      }
    
      @Test
      public void testAnnotatedTag() throws Exception {
        RevCommit commit = git.commit().setMessage( "Tag Me!" ).call();
    
        Ref tagRef = git.tag().setAnnotated( true ).setName( "Annotated_Tag" ).call();
    
        assertEquals( commit, git.getRepository().peel( tagRef ).getPeeledObjectId() );
        ObjectReader objectReader = git.getRepository().newObjectReader();
        ObjectLoader objectLoader = objectReader.open( tagRef.getObjectId() );
        RevTag tag = RevTag.parse( objectLoader.getBytes() );
        objectReader.release();
        assertEquals( commit.getId(), tag.getObject() );
      }
    
      @Before
      public void setUp() throws GitAPIException {
        git = Git.init().setDirectory( tempFolder.getRoot() ).call();
      }
    }
    

    In JGit, an annotated tag is represented by a RevTag that is stored under the id to which the tag ref points to.

    To tell one form the other, you can peel the ref and then test if its getPeeledObjectId() returns non-null.

    Ref peeledRef = git.getRepository().peel( tagRef );
    boolean annotatedTag = peeledRef.getPeeledObjectId() != null;
    

    The peeled object id is the one that points to the commit on which the annotated tag was created.

提交回复
热议问题