Last active
August 27, 2019 14:58
-
-
Save gcdd1993/190201fca46110115e975b89622b6ace to your computer and use it in GitHub Desktop.
gradle 项目输出当前版本信息用于打包
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
buildscript { | |
repositories { | |
jcenter() | |
mavenCentral() | |
} | |
dependencies { | |
classpath 'org.eclipse.jgit:org.eclipse.jgit:4.1.1.201511131810-r' | |
} | |
} | |
import org.eclipse.jgit.api.Git | |
import org.eclipse.jgit.internal.storage.file.FileRepository | |
import java.util.regex.Matcher | |
def gitVersionName(project) { | |
File gitDir = new File(project.rootDir, '.git') | |
if (!gitDir.exists()) { | |
throw new IllegalArgumentException('Cannot find \'.git\' directory') | |
} | |
try { | |
Git git = Git.wrap(new FileRepository(gitDir)) | |
String version = git.describe().call() ?: 'unspecified' | |
boolean isClean = git.status().call().isClean() | |
return version + (isClean ? '' : '') | |
} catch (Throwable t) { | |
return 'unspecified' | |
} | |
} | |
def gitVersionCode(project) { | |
def r = /v(\d+)\.(\d+)\.(\d+)(-.*)?/ | |
String versionName = gitVersionName(project) | |
Matcher m = versionName =~ r | |
if (m.matches()) { | |
int major = m.group(1).toInteger() | |
int minor = m.group(2).toInteger() | |
int patch = m.group(3).toInteger() | |
return major * 1000000 + minor * 1000 + patch | |
} else { | |
throw new IllegalArgumentException('versionName: ' + versionName + ' cannot be convert to versioncode') | |
} | |
} | |
ext{ | |
gitVersionName = this.&gitVersionName | |
gitVersionCode = this.&gitVersionCode | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
apply from: 'gitversioning.gradle' | |
version = gitVersionName(project) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment