更具体地说,我有一些构建配置:
signingConfigs {
debug {
keyAlias ''
keyPassword ''
storeFile file('')
}
release {
keyAlias ''
keyPassword ''
storeFile file('')
storePassword ''
}
}
....
defaultConfig {
applicationId ""
minSdkVersion 21
targetSdkVersion 23
versionCode code
}
我希望 gradle 在每次运行“release”时自动增加代码版本。
我目前拥有的:
def code = 1;
//Get all the gradle task names being run
List<String> runTasks = gradle.startParameter.getTaskNames();
for (String item : runTasks) {
//Get the version.properties file. Its our custom file for storing a code version, please don't remove it
def versionPropsFile = file('version.properties')
def Properties versionProps = new Properties()
//This will prevent the gradle from exploding when there's no file yet created
if (versionPropsFile.exists())
versionProps.load(new FileInputStream(versionPropsFile))
//It will insert the "0" version in case the file does not exist
code = (versionProps['VERSION_CODE'] ?: "0").toInteger()
if (item.contains("release")) {
// If we're building up on Jenkins, increment the version strings
code++
versionProps['VERSION_CODE'] = code.toString()
//It will overwrite the file even if it doesn't exist
versionProps.store(versionPropsFile.newWriter(), null)
}
}
问题:
我似乎无法进入 if (item.contains("release"))
。它总是错误的,但我肯定看到 gradle 运行这个任务。我该如何修复它或至少在控制台中输出 gradle 正在运行的所有任务(它们的名称)?
最佳答案
我对这个问题的实现:
我有一个包含版本号的版本文件。从这个文件我们得到版本。当构建包含任务“publishRelease”(它可以是任何其他任务)时,我们会增加版本文件中的版本。 我喜欢这个解决方案,因为它使 defaultConfig 保持干净的编码逻辑。
version.properties
VERSION_CODE=45
在android配置部分
defaultConfig {
applicationId "..."
minSdkVersion 16
targetSdkVersion 23
versionCode getVersion()
versionName "0.2." + versionCode
}
和 getVersion()
def getVersion() {
def versionPropertiesFile = file('version.properties')
def appVersion = -1;
if (versionPropertiesFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropertiesFile))
appVersion = versionProps['VERSION_CODE'].toInteger()
def runTasks = gradle.startParameter.taskNames
if ('publishRelease' in runTasks) {
print("Increase version to " + appVersion + '\n')
appVersion += 1
versionProps['VERSION_CODE'] = appVersion.toString()
versionProps.store(versionPropertiesFile.newWriter(), null)
}
} else {
throw new GradleException("Could not read version.properties!")
}
return appVersion;
}
关于android - 如何实现gradle代码版本自动递增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35408037/