How to create a BitBucket hook that reject pushes with bad file name?

856 Views Asked by At

I'm trying to make a BitBucket hook that would reject a push if it contained a file not matching a naming convention. So far, I'm able to create a PreRepositoryHook implementation that register the following callback.

public class MyPreRepositoryHook implements PreRepositoryHook<RepositoryHookRequest> {

public MyPreRepositoryHook () {
}

@Nonnull
@Override
public RepositoryHookResult preUpdate(@Nonnull PreRepositoryHookContext context,
                                      @Nonnull RepositoryHookRequest request) {

    // hook only wants commits added to the repository
    context.registerCommitCallback(
            new MyPreCommitCallback(),
            RepositoryHookCommitFilter.ADDED_TO_REPOSITORY);

    // return accepted() here, the callback gets a chance to reject the change when getResult() is called
    return RepositoryHookResult.accepted();
}

In MyPreCommitCallback:

    @Override
    public boolean onCommitAdded(@Nonnull CommitAddedDetails commitDetails) {

        Commit commit = commitDetails.getCommit();

        SimpleChangeset.Builder builder = new SimpleChangeset.Builder(commit);
        SimpleChangeset simpleChangeset = builder.build();

        Page<Change> changes = simpleChangeset.getChanges();
}

But I am unable to get the list of files since the call to simpleChangeset.getChanges always return null.

Any help in getting a list of file names would be appreciated. Thank you.

1

There are 1 best solutions below

1
On
@Component
public class AltresPreRepositoryHook implements PreRepositoryHook<RepositoryHookRequest> {

private final CommitService commitService;

@Autowired
public AltresPreRepositoryHook(@ComponentImport CommitService commitService) {
    this.commitService = commitService;
}




private static class AltresPreCommitCallback implements PreRepositoryHookCommitCallback {

private final RepositoryHookRequest request;
private final CommitService commitService;

private RepositoryHookResult result = RepositoryHookResult.accepted();

public AltresPreCommitCallback(RepositoryHookRequest request, CommitService commitService) {
    this.request = request;
    this.commitService = commitService;
}

@Nonnull
@Override
public RepositoryHookResult getResult() {
    return result;
}

@Override
public boolean onCommitAdded(@Nonnull CommitAddedDetails commitDetails) {

    Commit commit = commitDetails.getCommit();
    ChangesRequest.Builder builder = new ChangesRequest.Builder(commit.getRepository(), commit.getId());
    ChangesRequest changesRequest = builder.build();

    final ChangedPathsCollector changedPathsCollector = new ChangedPathsCollector();

    commitService.streamChanges(changesRequest, changedPathsCollector);

    Collection<String> changedPaths = changedPathsCollector.getChangedPaths();