Get file content in pre commit hook

Hello,

I am trying to write a hook that will validate the contents of a file and deny a push if the content is not correct. I have so far written the following piece of code:

@Nonnull
@Override
public RepositoryHookResult preUpdate(@Nonnull PreRepositoryHookContext context, @Nonnull RepositoryPushHookRequest request) {
  final Repository repo = request.getRepository();
  final Map<String, ByteArrayOutputStream> fileStreams = new HashMap<>();

  request.getRefChanges().stream().forEach(refChange -> {
    ChangesRequest changesReq = new ChangesRequest.Builder(repo, refChange.getToHash()).sinceId(refChange.getFromHash()).build();

    commitService.streamChanges(changesReq, change ->{
      String fileName = change.getPath().toString();

      contentService.streamFile(repo, refChange.getToHash(), fileName, s -> {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        fileStreams.put(fileName, baos);
        return baos;
      });

      return true;
    });
  });

  fileStreams.entrySet().stream().forEach(entry -> {
    new String(entry.getValue().toByteArray())); //This is the String I need
  });

  return RepositoryHookResult.accepted();
}

When changing the refChange.getToHash() to refChange.getRef().getDisplayId() in the contentService I will get the content but only from before the push. I need the content when the commits that are being pushed have been added but I still want to be able to reject a push. I have also tried a few other Id’s in the contentService with no success.

Thanks,
Niels

Hi @n.kooij,

May I ask why you need the commits after they’ve been added? Maybe I’m misunderstanding your request, but it is not possible to reject a push after the push has already succeeded.

Additionally, is it required to stream through all of the ref changes? Why is taking the file content from the latest commit not good enough?

Regards,
Kristy

Hello,

Taking the content of the last commit is fine too. I haven’t been able to find out how to do that. I need to validate the content and reject the push if the content is not valid.

Regards,
Niels

I have found the solution in the following reply by Juan Palacios: https://community.atlassian.com/t5/Bitbucket-questions/Reading-the-contents-of-a-file-in-a-pre-commit-hook-filter/qaq-p/662321