Versioning.kt 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package im.angry.openeuicc.build
  2. import com.android.build.gradle.internal.api.ApkVariantOutputImpl
  3. import com.android.build.gradle.internal.dsl.BaseAppModuleExtension
  4. import org.gradle.api.Plugin
  5. import org.gradle.api.Project
  6. import org.gradle.kotlin.dsl.configure
  7. import java.io.ByteArrayOutputStream
  8. val Project.gitVersionCode: Int
  9. get() =
  10. try {
  11. val stdout = ByteArrayOutputStream()
  12. exec {
  13. commandLine("git", "rev-list", "--first-parent", "--count", "HEAD")
  14. standardOutput = stdout
  15. }
  16. stdout.toString("utf-8").trim('\n').toInt()
  17. } catch (_: Exception) {
  18. 0
  19. }
  20. fun Project.getGitVersionName(vararg args: String): String =
  21. try {
  22. val stdout = ByteArrayOutputStream()
  23. exec {
  24. commandLine("git", "describe", "--always", "--tags", "--dirty", *args)
  25. standardOutput = stdout
  26. }
  27. stdout.toString("utf-8").trim('\n').removePrefix("unpriv-")
  28. } catch (_: Exception) {
  29. "Unknown"
  30. }
  31. class MyVersioningPlugin : Plugin<Project> {
  32. override fun apply(target: Project) {
  33. target.configure<BaseAppModuleExtension> {
  34. defaultConfig {
  35. versionCode = target.gitVersionCode
  36. versionName = target.getGitVersionName()
  37. }
  38. applicationVariants.all {
  39. if (name == "debug") {
  40. outputs.forEach {
  41. with(it as ApkVariantOutputImpl) {
  42. versionCodeOverride = (System.currentTimeMillis() / 1000).toInt()
  43. // always keep the format: <tag>-<commits>-g<hash>[-dirty]
  44. versionNameOverride = target.getGitVersionName("--long")
  45. }
  46. }
  47. }
  48. }
  49. }
  50. }
  51. }