1 /* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.tradefed.util; 17 18 import com.android.tradefed.log.LogUtil.CLog; 19 20 import java.io.File; 21 import java.io.IOException; 22 23 /** Fetch the version of the running tradefed artifacts. */ 24 public class VersionParser { 25 26 public static final String DEFAULT_IMPLEMENTATION_VERSION = "default"; 27 private static final String VERSION_FILE = "version.txt"; 28 private static final String TF_MAIN_JAR = "/tradefed.jar"; 29 fetchVersion()30 public static String fetchVersion() { 31 return getPackageVersion(); 32 } 33 34 /** 35 * Version fetcher on the implementation version of the jar files from this class to ensure 36 * a match in the classloader. 37 */ getPackageVersion()38 private static String getPackageVersion() { 39 Package p = VersionParser.class.getPackage(); 40 if (p != null && !DEFAULT_IMPLEMENTATION_VERSION.equals(p.getImplementationVersion())) { 41 return p.getImplementationVersion(); 42 } 43 File dir = getTradefedJarDir(); 44 if (dir != null) { 45 File versionFile = new File(dir, VERSION_FILE); 46 if (versionFile.exists()) { 47 try { 48 String version = FileUtil.readStringFromFile(versionFile); 49 return version.trim(); 50 } catch (IOException e) { 51 // Failed to fetch version. 52 CLog.e(e); 53 } 54 } 55 CLog.e("Did not find Version file in directory: %s", dir.getAbsolutePath()); 56 } 57 return null; 58 } 59 getTradefedJarDir()60 private static File getTradefedJarDir() { 61 String classpath = System.getProperty("java.class.path"); 62 String[] segments = classpath.split(":"); 63 for (String segment : segments) { 64 if (segment.endsWith(TF_MAIN_JAR)) { 65 return new File(segment).getParentFile(); 66 } 67 } 68 return null; 69 } 70 } 71