Many companies now use Jenkins to manage the APK. After the code is submitted, the build is generated on Jenkins.
We can obtain the submitted version number of Jenkins in this way.
Jenkins has a built-in variable build_number during job compilation.
Groovy has a very useful function:
/** * 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); }
You can get all the environment variables:
If our build. gradle runs on Windows
Map <string, string> map = system. getenv:
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
Here is a path. We can obtain the path of the system so that we can determine whether the running environment is complete:
If you want to execute some git commands, you need git in the path.
We can judge as follows:
String str = map.get("Path") if(str != null) { //it's windows if(str.contains("Git")){ return true; } return false; }
If build. gradle runs on Linux, check whether Jenkins is configured in the environment.
Print all the Linux environment variables in this form:
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}
If the Jenkins environment is available, we can obtain the build version number as follows:
def getJenkinsBuild() { boolean flag = isInJeknins(); if(flag){ ext.env = System.getenv() ext.buildNumber = env.BUILD_NUMBER?.toInteger() return "$buildNumber" }else{ return 0 }}
Jenkins build obtained through gradle