You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Version.java 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. package org.eclipse.jgit.pgm;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.net.URL;
  14. import java.net.URLClassLoader;
  15. import java.text.MessageFormat;
  16. import java.util.jar.JarFile;
  17. import java.util.jar.Manifest;
  18. import org.eclipse.jgit.pgm.internal.CLIText;
  19. @Command(common = true, usage = "usage_DisplayTheVersionOfJgit")
  20. class Version extends TextBuiltin {
  21. /** {@inheritDoc} */
  22. @Override
  23. protected void run() {
  24. // read the Implementation-Version from Manifest
  25. String version = getImplementationVersion();
  26. // if Implementation-Version is not available then try reading
  27. // Bundle-Version
  28. if (version == null) {
  29. version = getBundleVersion();
  30. }
  31. // if both Implementation-Version and Bundle-Version are not available
  32. // then throw an exception
  33. if (version == null) {
  34. throw die(CLIText.get().cannotReadPackageInformation);
  35. }
  36. try {
  37. outw.println(
  38. MessageFormat.format(CLIText.get().jgitVersion, version));
  39. } catch (IOException e) {
  40. throw die(e.getMessage(), e);
  41. }
  42. }
  43. /** {@inheritDoc} */
  44. @Override
  45. protected final boolean requiresRepository() {
  46. return false;
  47. }
  48. private String getImplementationVersion() {
  49. Package pkg = getClass().getPackage();
  50. return (pkg == null) ? null : pkg.getImplementationVersion();
  51. }
  52. private String getBundleVersion() {
  53. ClassLoader cl = getClass().getClassLoader();
  54. if (cl instanceof URLClassLoader) {
  55. URL url = ((URLClassLoader) cl).findResource(JarFile.MANIFEST_NAME);
  56. if (url != null)
  57. return getBundleVersion(url);
  58. }
  59. return null;
  60. }
  61. private static String getBundleVersion(URL url) {
  62. try (InputStream is = url.openStream()) {
  63. Manifest manifest = new Manifest(is);
  64. return manifest.getMainAttributes().getValue("Bundle-Version"); //$NON-NLS-1$
  65. } catch (IOException e) {
  66. // do nothing - will return null
  67. }
  68. return null;
  69. }
  70. }