View Javadoc
1   /*
2    * Copyright (C) 2008, Google Inc. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.pgm;
12  
13  import java.io.IOException;
14  import java.io.InputStream;
15  import java.net.URL;
16  import java.net.URLClassLoader;
17  import java.text.MessageFormat;
18  import java.util.jar.JarFile;
19  import java.util.jar.Manifest;
20  
21  import org.eclipse.jgit.pgm.internal.CLIText;
22  
23  @Command(common = true, usage = "usage_DisplayTheVersionOfJgit")
24  class Version extends TextBuiltin {
25  	/** {@inheritDoc} */
26  	@Override
27  	protected void run() {
28  		// read the Implementation-Version from Manifest
29  		String version = getImplementationVersion();
30  
31  		// if Implementation-Version is not available then try reading
32  		// Bundle-Version
33  		if (version == null) {
34  			version = getBundleVersion();
35  		}
36  
37  		// if both Implementation-Version and Bundle-Version are not available
38  		// then throw an exception
39  		if (version == null) {
40  			throw die(CLIText.get().cannotReadPackageInformation);
41  		}
42  
43  		try {
44  			outw.println(
45  					MessageFormat.format(CLIText.get().jgitVersion, version));
46  		} catch (IOException e) {
47  			throw die(e.getMessage(), e);
48  		}
49  	}
50  
51  	/** {@inheritDoc} */
52  	@Override
53  	protected final boolean requiresRepository() {
54  		return false;
55  	}
56  
57  	private String getImplementationVersion() {
58  		Package pkg = getClass().getPackage();
59  		return (pkg == null) ? null : pkg.getImplementationVersion();
60  	}
61  
62  	private String getBundleVersion() {
63  		ClassLoader cl = getClass().getClassLoader();
64  		if (cl instanceof URLClassLoader) {
65  			URL url = ((URLClassLoader) cl).findResource(JarFile.MANIFEST_NAME);
66  			if (url != null)
67  				return getBundleVersion(url);
68  		}
69  		return null;
70  	}
71  
72  	private static String getBundleVersion(URL url) {
73  		try (InputStream is = url.openStream()) {
74  			Manifest manifest = new Manifest(is);
75  			return manifest.getMainAttributes().getValue("Bundle-Version"); //$NON-NLS-1$
76  		} catch (IOException e) {
77  			// do nothing - will return null
78  		}
79  		return null;
80  	}
81  }