You can now vote for scripts to help people know if they're useful or not. Login or create an account to vote!

1

Block commits for files containing content that doesn't match regex

Overview

This pre hook script blocks commits for files containing content that doesn't match the regex condition.

Good to Know

  • This script must be configured as a 'pre hook'.
  • It prevents commits for files containing content that doesn't match the regex expression.

Requirements

  • Bitbucket Bitbucket (6.0 - 7.17)
  • ScriptRunner for Bitbucket ScriptRunner for Bitbucket (6.18.0)
    
import com.atlassian.bitbucket.commit.Commit import com.atlassian.bitbucket.commit.CommitService import com.atlassian.bitbucket.content.Change import com.atlassian.bitbucket.content.ChangesRequest import com.atlassian.bitbucket.content.ContentService import com.atlassian.bitbucket.hook.repository.RepositoryHookResult import com.atlassian.sal.api.component.ComponentLocator import com.onresolve.scriptrunner.parameters.annotation.ShortTextInput import java.util.regex.Pattern @ShortTextInput(label = 'regex', description = 'Regex expression used to verify file content') String regexValue def pattern = Pattern.compile(regexValue) def commitService = ComponentLocator.getComponent(CommitService) def contentService = ComponentLocator.getComponent(ContentService) def commits = refChanges.getCommits(repository) as List // filePaths to commit Id, if file was modified in multiple commits, take the last commit id def filePaths = [:] as Map commits.reverseEach { commit -> def changesRequest = new ChangesRequest.Builder(repository, commit.id).build() commitService.streamChanges(changesRequest) { Change change -> if (change.path.extension == 'java') { filePaths[change.path.toString()] = commit.id } true } } def result = filePaths.keySet().collect { filePath -> def fileStream = new ByteArrayOutputStream() contentService.streamFile(repository, filePaths[filePath], filePath) { fileStream } fileStream.toString() }.every { pattern.matcher(it).count > 0 } result ? RepositoryHookResult.accepted() : RepositoryHookResult.rejected('Push blocked', 'Java files should match regex')
Discovered an issue? Report it here

Suggested for you