2

Does JGit include an implementation of git rev-parse --short? I could not find one in perusing the documentation.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
bmargulies
  • 97,814
  • 39
  • 186
  • 310

2 Answers2

2

There is no direct equivalent to git rev-parse in JGit.

However, JGit provides API that may help to achieve what rev-parse does.

  • ObjectId::isId() to determine if the given string represents a SHA-1
  • ObjectId::fromString() to create an ObjectId from a string

To shorten a given object id, use ObjectId::abbreviate()

The following example abbreviates the given SHA-1:

ObjectId objectId = ObjectId.fromString( "fb808b5b01cdfaedda0bd1d304c7115ce959b286" );
AbbreviatedObjectId abbreviatedId = objectId.abbreviate( 7 );  // returns fb808b5

Note that the methods outlined above operate independent of a repository and thus cannot detect ambiguous object ids or verify if a given id exists in a repository or if it has the expected type (things that git rev-parse --verify would do).

To verify an id with a repository Repository::resolve can be used. The method accepts expressions like fb808b5^{commit} and returns an ObjectId, or null if the string can't be resolved. an AmbiguousObjectException is thrown if the repository contains more than one match. See the JavaDoc for a list of supported expressions: http://download.eclipse.org/jgit/site/4.2.0-SNAPSHOT/apidocs/org/eclipse/jgit/lib/Repository.html#resolve(java.lang.String)

Be aware, that an IncorrectObjectTypeException is thrown if an object type is specified, but the revision that was found does not match the given type.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
2

Just to make a straightforward example for what @Rüdiger Herrmann mentioned above

// git rev-parse HEAD
git.getRepository().exactRef("refs/heads/master").getObjectId().name()

// git rev-parse --short HEAD
git.getRepository().exactRef("refs/heads/master").getObjectId().abbreviate(7).name()
Lawrence Ching
  • 423
  • 7
  • 16