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')