Is there a JGit method equivalent to git rev-parse --short?

家住魔仙堡 提交于 2019-12-22 15:25:23

问题


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


回答1:


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.




回答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()


来源:https://stackoverflow.com/questions/39356463/is-there-a-jgit-method-equivalent-to-git-rev-parse-short

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!