我需要编写gradle脚本来在每次提交时自动对应用程序进行版本控制。我还需要将提交哈希作为参考添加到测试人员的应用程序中。
我很困惑自动版本控制通常如何工作。有人可以解释自动版本控制的过程吗?
我遇到了类似的问题,但是不想修改versionName以包括git哈希。我们希望将其保持为1.2.2,但是仍然可以在UI中显示git hash。
我修改了the other answer here中的代码,以使用buildConfigField任务生成可在Java代码中引用的BuildConfig.GitHash值。
将此添加到模块的build.gradle文件的android
部分上方:
def getGitHash = { ->
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-parse', '--short', 'HEAD'
standardOutput = stdout
}
return stdout.toString().trim()
}
然后将以下行添加到build.gradle的defaultConfig
部分的android
部分,即versionName
以下:
buildConfigField "String", "GitHash", "\"${getGitHash()}\""
这将在自动生成的BuildConfig.java文件中生成以下行:
// Fields from default config.
public static final String GitHash = "e61af97";
现在您可以使用BuildConfig.GitHash
在Java代码中获取git哈希。
一种理想的解决方案是从项目的git状态中获取版本。这样,版本控制就不会依赖于您记住增加变量或更改gradle或配置文件中的任何文本。另一个优点是版本名称和代码可追溯到一个特定的代码状态。
您可以在http://ryanharter.com/blog/2013/07/30/automatic-versioning-with-git-and-gradle/中找到一个说明性示例
想法是使用getVersionName函数获取git信息,并在gradle脚本中使用该函数:
/*
* Gets the version name from the latest Git tag
*/
def getVersionName = { ->
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'describe', '--tags'
standardOutput = stdout
}
return stdout.toString().trim()
}
当然,您需要有可用的命令行git(因为将执行命令git describe --tags
以生成信息)。
另一种方法(也基于从git获取版本信息)可能是将该逻辑外部化到gradle插件中,例如:-https://github.com/moallemi/gradle-advanced-build-version-https://github.com/infusionsoft/gradle-build-version-plugin-https://github.com/nemerosa/versioning
使用哪种取决于您要应用哪种版本控制策略。
我创建了Gradle插件来为您执行此操作。项目和完整说明位于https://github.com/lessthanoptimal/gversion-plugin
要使用它,请将以下内容添加到您的build.gradle文件中
plugins {
id "com.peterabeles.gversion" version "1.2.4"
}
gversion {
srcDir = "src/main/java/"
classPackage = "com.your.package"
className = "MyVersion" // optional. If not specified GVersion is used
dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" // optional. This is the default
timeZone = "UTC" // optional. UTC is default
}
现在,您只需要运行gradle任务'createVersionFile'来创建文件。您可能需要考虑将以下行添加到gradle项目project.compileJava.dependsOn(createVersionFile)
,这将导致Gradle每次构建项目时都会生成文件。有关Android的说明,请参见上面的网站。
这是文件的外观
/**
* Automatically generated file containing build version information.
*/
public class MyVersion {
public static final String MAVEN_GROUP = "com.your";
public static final String MAVEN_NAME = "project_name";
public static final String VERSION = "1.0-SNAPSHOT";
public static final int GIT_REVISION = 56;
public static final String GIT_SHA = "a0e41dd1a068d184009227083fa6ae276ef1846a";
public static final String BUILD_DATE = "2018-04-11T12:19:03Z";
public static final long BUILD_UNIX_TIME = 1523449143116L;
}
您可能还希望将版本文件添加到您的.gitignore中,因为它是自动生成的,并且您不想在git中使用它。
还值得研究grgit - Groovy/Gradle Git,它可以帮助简化Gradle脚本中信息的提取,包括Git提交哈希。
将以下代码添加到您的build.gradle
def gitCommitHash = 'git rev-parse --verify --short HEAD'.execute().text.trim()
defaultConfig{
... otherConfigs
buildConfigField("String", "GIT_HASH", "\"${gitCommitHash}\"")
}
现在您可以通过BuildConfig.GIT_HASH
获取git hash了>
玩得开心