现在很多公司都都过Jenkins来管理apk,代码提交后在jenkins上生成build
我们可以这样来取到jenkins的提交版本号
Jenkins在编译job的时候,有个内置的变量BUILD_NUMBER
groovy有一个非常有用的函数:
/** * Returns an unmodifiable map of all available environment variables. * * @return the map representing all environment variables. */ public static Map<String, String> getenv() { Map<String, String> map = new HashMap<String, String>(); for (String entry : Libcore.os.environ()) { int index = entry.indexOf('='); if (index != -1) { map.put(entry.substring(0, index), entry.substring(index + 1)); } } return new SystemEnvironment(map); }
如果我们的build.gradle运行在windows上
Map<String, String> map = System.getenv()我们把这个map的key全部打印出来是:
USERPROFILE,ProgramData,USERDNSDOMAIN,PATHEXT,windows_tracing_logfile,JAVA_HOME,ProgramFiles(x86),XNAGSShared,windows_tracing_flags,TEMP,SystemDrive,ProgramFiles,Path,HOMEDRIVE,PROCESSOR_REVISION,USERDOMAIN,ALLUSERSPROFILE,VBOX_INSTALL_PATH,ProgramW6432,PROCESSOR_IDENTIFIER,SESSIONNAME,TMP
这里有个Path,我们可以取到系统的Path,这样我们就可以判断运行环境是否是否完全:
如果我们要执行Git的一些命令,这就需要Path里有Git
我们可以这样来判断:
String str = map.get("Path") if(str != null) { //it's windows if(str.contains("Git")){ return true; } return false; }
如果build.gradle运行在linux上,我们就要看这个环境是否配置了jenkins,我们可以这样来判断
把Linux的环境变量都打印出来是这种形式:
JENKINS_HOME=/home/jenkins/.jenkinsJENKINS_BUILD_USER_LAST_NAME=GaoSHLVL=1JENKINS_BUILD_USER_ID=nick.gaoNODE_LABELS=CH-XMN-ANDROID CI01ANDROID i386 i386-unknown+check_lsb_release_installed i386-unknown+check_lsb_release_installed-unknown+check_lsb_release_installed unknown+check_lsb_rele
boolean isInJeknins() { Map<String, String> map = System.getenv() if(map == null) { return false } String str = map.get("Path") if(str != null) { //it's windows return false; } else{ str = "" Iterator it = map.iterator(); while(it.hasNext()) { str += it.next(); } if(str.contains("jenkins")){ return true }else{ return false; } } return false }
def getJenkinsBuild() { boolean flag = isInJeknins(); if(flag){ ext.env = System.getenv() ext.buildNumber = env.BUILD_NUMBER?.toInteger() return "$buildNumber" }else{ return 0 } }
原文地址:http://blog.csdn.net/baidu_nod/article/details/38147551