Skip to main content
Book your demo
Example scripts
To homepage
Bitbucket
Data centre icon
Data Center

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

Features
Pre hooks
Created 2 year(s) ago, Updated 1 month(s) ago
App in script
ScriptRunner For Bitbucket
ScriptRunner For Bitbucket
by Adaptavist
Compatibility
compatibility bullet
Bitbucket (6.0 - 7.17)
compatibility bullet
ScriptRunner For Bitbucket (7.10.0)
Language |
groovy
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<Commit>

// filePaths to commit Id, if file was modified in multiple commits, take the last commit id
def filePaths = [:] as Map<String, String>
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')
Having an issue with this script?
Report it here