Skip to content

Commit 1bd46cf

Browse files
iProdigytipsy
authored andcommitted
Refactor CommitCountUtil#getCommitsForQuarters for clarity and perf (#64)
1 parent ad2e4cc commit 1bd46cf

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

src/main/kotlin/app/util/CommitCountUtil.kt

+16-9
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,33 @@ package app.util
33
import org.eclipse.egit.github.core.Repository
44
import org.eclipse.egit.github.core.RepositoryCommit
55
import org.eclipse.egit.github.core.User
6+
import java.time.Instant
67
import java.time.OffsetDateTime
78
import java.time.ZoneOffset
8-
import java.time.temporal.ChronoUnit.MONTHS
9+
import java.time.ZoneOffset.UTC
910
import java.time.temporal.IsoFields
11+
import java.time.temporal.IsoFields.QUARTER_YEARS
12+
import java.time.temporal.TemporalAdjusters
1013
import java.util.*
1114

1215
object CommitCountUtil {
1316

14-
fun getCommitsForQuarters(user: User, repoCommits: Map<Repository, List<RepositoryCommit>>): Map<String, Int> {
15-
val quarterBuckets = (0..MONTHS.between(asInstant(user.createdAt), asInstant(Date()).plusMonths(1))).associate { monthNr ->
16-
yearQuarterFromDate(asInstant(user.createdAt).plusMonths(monthNr)) to 0
17-
}.toSortedMap()
18-
repoCommits.flatMap { it.value }.forEach {
19-
quarterBuckets[yearQuarterFromCommit(it)] = (quarterBuckets[yearQuarterFromCommit(it)] ?: 0) + 1
20-
}
17+
fun getCommitsForQuarters(user: User, repoCommits: Map<Repository, List<RepositoryCommit>>): SortedMap<String, Int> {
18+
val creation = asInstant(user.createdAt).withDayOfMonth(1)
19+
val now = Instant.now().atOffset(UTC).with(TemporalAdjusters.firstDayOfNextMonth())
20+
val quarters = QUARTER_YEARS.between(creation, now)
21+
22+
val quarterBuckets = (0..quarters)
23+
.associate { yearQuarterFromDate(creation.plus(it, QUARTER_YEARS)) to 0 }
24+
.toSortedMap()
25+
26+
repoCommits.values.flatten().groupingBy { yearQuarterFromCommit(it) }.eachCountTo(quarterBuckets)
27+
2128
return quarterBuckets
2229
}
2330

2431
private fun asInstant(date: Date) = date.toInstant().atOffset(ZoneOffset.UTC)
25-
private fun yearQuarterFromCommit(it: RepositoryCommit) = yearQuarterFromDate(it.commit.committer.date.toInstant().atOffset(ZoneOffset.UTC))
32+
private fun yearQuarterFromCommit(it: RepositoryCommit) = yearQuarterFromDate(asInstant(it.commit.committer.date))
2633
private fun yearQuarterFromDate(date: OffsetDateTime) = "${date.year}-Q${date.get(IsoFields.QUARTER_OF_YEAR)}"
2734

2835
}

0 commit comments

Comments
 (0)