1+ import java.io.FileWriter
2+
13plugins {
24 id(" com.android.application" ) version " 8.1.3" apply false
35
@@ -14,12 +16,65 @@ allprojects {
1416 // noinspection JcenterRepositoryObsolete
1517 jcenter {
1618 content {
17- includeModule(" com.oasisfeng.nevo" ," sdk" )
19+ includeModule(" com.oasisfeng.nevo" , " sdk" )
1820 }
1921 }
2022 }
2123}
2224
25+ tasks.register(" appVersion" ) {
26+ description = " Calculate app version and save to version.properties"
27+
28+ // execute on configuration phase
29+ val name = getVersionName()
30+ val code = 20000 + getVersionCode()
31+ logger.lifecycle(" AppVersionName: {}\n AppVersionCode: {}" , name, code)
32+ FileWriter (File (rootProject.projectDir, " version.properties" )).use { fw ->
33+ fw.write(" name=$name \n code=$code \n " )
34+ fw.flush()
35+ }
36+ }
37+
2338tasks.register(" clean" , Delete ::class ) {
2439 delete(rootProject.buildDir)
2540}
41+
42+ fun String.runCommand (currentWorkingDir : File = file("./")): String {
43+ val byteOut = java.io.ByteArrayOutputStream ()
44+ project.exec {
45+ workingDir = currentWorkingDir
46+ commandLine = this @runCommand.split(" " )
47+ standardOutput = byteOut
48+ }
49+ return String (byteOut.toByteArray()).trim()
50+ }
51+
52+ fun getVersionCode (): Int {
53+ val cmd = " git rev-list HEAD --count"
54+ return try {
55+ cmd.runCommand().toInt()
56+ } catch (e: Exception ) {
57+ logger.error(" Failed to get version code with git, return 1 by default." , e)
58+ 1
59+ }
60+ }
61+
62+ fun getVersionName (): String {
63+ val cmd = " git describe --tags --long --abbrev=7 --dirty=_dev"
64+ try {
65+ val v = cmd.runCommand()
66+ val pattern = """ ^v(?<v>[\d|.]+)-\d+-g[A-Za-z0-9]{7}(?<s>_dev)?$""" .toRegex()
67+ val g = pattern.matchEntire(v)?.groups
68+ if (g == null || g[" v" ] == null ) {
69+ logger.error(
70+ " Failed to get version name with git.\n " +
71+ " Cannot match git tag describe, return <UNKNOWN> by default. raw=$v "
72+ )
73+ return " UNKNOWN"
74+ }
75+ return g[" v" ]!! .value + (g[" s" ]?.value ? : " " )
76+ } catch (e: Exception ) {
77+ logger.error(" Failed to get version name with git, return <UNKNOWN> by default." , e)
78+ return " UNKNOWN"
79+ }
80+ }
0 commit comments