Versioning.kt 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 (e: Exception) {
  18. 0
  19. }
  20. val Project.gitVersionName: String
  21. get() =
  22. try {
  23. val stdout = ByteArrayOutputStream()
  24. exec {
  25. commandLine("git", "describe", "--always", "--tags", "--dirty")
  26. standardOutput = stdout
  27. }
  28. stdout.toString("utf-8").trim('\n')
  29. } catch (e: Exception) {
  30. "Unknown"
  31. }
  32. class MyVersioningPlugin: Plugin<Project> {
  33. override fun apply(target: Project) {
  34. target.configure<BaseAppModuleExtension> {
  35. defaultConfig {
  36. versionCode = target.gitVersionCode
  37. versionName = target.gitVersionName
  38. }
  39. applicationVariants.all {
  40. if (name == "debug") {
  41. outputs.forEach {
  42. (it as ApkVariantOutputImpl).versionCodeOverride =
  43. (System.currentTimeMillis() / 1000).toInt()
  44. }
  45. }
  46. }
  47. }
  48. }
  49. }