Search code examples
bitbucket-serveratlassian-plugin-sdk

how to get a list of commits from refChanges in Atlassian Stash Pre Receive Repository Hook


Im trying to write a stash plugin that will iterate through the commits in a change set pushed to stash in a Pre Receive Repository Hook.

The API passes a Collection of refChange in the onReceive method.

public boolean onReceive(RepositoryHookContext context, Collection<RefChange> refChanges, HookResponse hookResponse)

if I make 3 commits then push I get one RefChange which looks like this

refId = refs/heads/master
fromHash = ded3e4583653f14892cc3e8a898ba74ee75e1a58 // First Commit in change set
toHash = ae017dcdadf7ca69617fb05f6905cccfe2aa4229 // Most recent commit
type = "UPDATE"

Id like to get a collection of all the commits so that I can get all the commit messages.

I'm looking at com.atlassian.stash.commit.CommitService getCommit and getCommits. I think I need to getCommitsBetween but can't quite figure out how to crate the GetCommitsBetween parameter needed from the RefChange I have.

Am I even heading down the right path here?


Solution

  • Even though the CommitsBetweenRequest page on the Atlassian Stash API documentation is one of the few pages with an explanation, it took some trial and error to figure this out. GetCommitsBetween works but here's the trick...

    Set the commitsBetweenBuilder.exclude to the starting commit in the change set and commitsBetweenBuilder.include to the ending commit hash.

    CommitsBetweenRequest.Builder commitsBetweenBuilder = new CommitsBetweenRequest.Builder(context.getRepository() );
    commitsBetweenBuilder.exclude(refChange.getFromHash()); //Starting with
    commitsBetweenBuilder.include(refChange.getToHash()); // ending with
    
    PageRequest pageRequest = new PageRequestImpl(0,6);
    
    Page<Commit> commits = commitService.getCommitsBetween(commitsBetweenBuilder.build(), pageRequest);
    
    //TODO: handle Pages
    for (Commit commit : commits.getValues()) {
       hookResponse.out().println("Message = " + commit.getMessage() + "\n");
    }