buildSrc/src/main/kotlin/RepositoryChangeset.kt
changeset 1 831cffa9c991
child 10 9aad34f43f71
equal deleted inserted replaced
0:fef46dce2812 1:831cffa9c991
       
     1 package com.geekorum.build
       
     2 
       
     3 import org.gradle.api.Project
       
     4 import java.io.File
       
     5 import java.io.IOException
       
     6 import java.util.concurrent.TimeUnit
       
     7 
       
     8 internal fun Project.getGitSha1(): String? = runCommand("git rev-parse HEAD", workingDir = projectDir)?.trim()
       
     9 
       
    10 internal fun Project.getHgSha1(): String? = runCommand("hg id --debug -i -r .", workingDir = projectDir)?.trim()
       
    11 
       
    12 internal fun Project.getHgLocalRevisionNumber(): String? = runCommand("hg id -n -r .", workingDir = projectDir)?.trim()
       
    13 
       
    14 fun Project.getChangeSet(): String {
       
    15     val git = rootProject.file(".git")
       
    16     val hg = rootProject.file(".hg")
       
    17     return when {
       
    18         git.exists() -> "git:${getGitSha1()}"
       
    19         hg.exists() -> "hg:${getHgSha1()}"
       
    20         else -> "unknown"
       
    21     }
       
    22 }
       
    23 
       
    24 /**
       
    25  * Compute a version code following this format : MmmPBBB
       
    26  * M is major, mm is minor, P is patch
       
    27  * BBB is build version number from hg
       
    28  */
       
    29 fun Project.computeChangesetVersionCode(major: Int = 0, minor: Int = 0, patch: Int = 0): Int {
       
    30     val base = (major * 1000000) + (minor * 10000) + (patch * 1000)
       
    31     return base + (getHgLocalRevisionNumber()?.trim()?.toIntOrNull() ?: 0)
       
    32 }
       
    33 
       
    34 private fun Project.runCommand(
       
    35     command: String,
       
    36     workingDir: File = File("."),
       
    37     timeoutAmount: Long = 60,
       
    38     timeoutUnit: TimeUnit = TimeUnit.MINUTES
       
    39 ): String? {
       
    40     return try {
       
    41         ProcessBuilder(*command.split("\\s".toRegex()).toTypedArray())
       
    42             .directory(workingDir)
       
    43             .redirectOutput(ProcessBuilder.Redirect.PIPE)
       
    44             .redirectError(ProcessBuilder.Redirect.PIPE)
       
    45             .start().apply {
       
    46                 waitFor(timeoutAmount, timeoutUnit)
       
    47             }.inputStream.bufferedReader().readText()
       
    48     } catch (e: IOException) {
       
    49         logger.info("Unable to run command", e)
       
    50         null
       
    51     }
       
    52 }