Skip to content

Instantly share code, notes, and snippets.

@jivimberg
Last active April 24, 2018 22:46
Show Gist options
  • Save jivimberg/862c4ee1c72603a224d57b30eedf74fc to your computer and use it in GitHub Desktop.
Save jivimberg/862c4ee1c72603a224d57b30eedf74fc to your computer and use it in GitHub Desktop.
fun fetchMergeRequestsChannel(gitLabService: GitLabService, lastProductionSha: String): ReceiveChannel<MergeRequest> {
return produce {
var page = 1
while (true) {
gitLabService.delayedFetchMergeRequests(page++).forEach { send(it) }
}
}.takeWhile { it.commitSha != lastProductionSha }
}
fun main(args: Array<String>) {
val mrs = fetchMergeRequestsChannel(GitLabService(), "04d78f5c7cd51c52d0482d08224ff6a214da12c1")
runBlocking {
delay(10, TimeUnit.SECONDS)
mrs.consumeEach {
println("consuming $it")
}
}
}
fun fetchMergeRequests(gitLabService: GitLabService, lastProductionSha: String): List<MergeRequest> {
var page = 1
var mergeRequests = emptyList<MergeRequest>()
// Fetch pages until we have the one that contains the commit we are looking for
while (mergeRequests.none { it.commitSha == lastProductionSha }) {
mergeRequests += gitLabService.fetchMergeRequests(page++)
}
// Trim the Merge Requests that are already in production
val indexOfLastMergeRequestInProduction = mergeRequests.indexOfLast { it.commitSha == lastProductionSha }
return mergeRequests.subList(0, indexOfLastMergeRequestInProduction)
}
fun fetchMergeRequestsIterable(gitLabService: GitLabService, lastProductionSha: String): List<MergeRequest> {
val mrIterable = object : Iterable<List<MergeRequest>> {
override fun iterator(): Iterator<List<MergeRequest>> {
return object : Iterator<List<MergeRequest>> {
var page = 1
override fun hasNext() = true
override fun next(): List<MergeRequest> = gitLabService.fetchMergeRequests(page++)
}
}
}
val pages = mrIterable
.takeWhileInclusive { page -> page.none { it.commitSha == lastProductionSha } }
return pages
.flatten()
.takeWhile { it.commitSha != lastProductionSha }
}
fun <T> Iterable<T>.takeWhileInclusive(pred: (T) -> Boolean): List<T> {
var shouldContinue = true
return takeWhile {
val result = shouldContinue
shouldContinue = pred(it)
result
}
}
fun fetchMergeRequestsSequence(gitLabService: GitLabService, lastProductionSha: String): List<MergeRequest> {
val mrSequence = buildSequence {
var page = 1
while (true) yieldAll(gitLabService.fetchMergeRequests(page++))
}
return mrSequence
.takeWhile { it.commitSha != lastProductionSha }
.toList()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment