JGit列出远程标签并按创建日期排序

Reb*_*bse 5 git jgit

我需要列出远程Git存储库的标签,并通过JGit 3.2.0 API按创建日期对它们进行排序。

找不到使用lsremote的方法,所以我只能按名称排序:

System.out.println("Listing remote repository " + REMOTE_URL);
Collection<Ref> tags = Git.lsRemoteRepository()
    .setTags(true)
    .setRemote(REMOTE_URL)
    .call();

ArrayList<Ref> taglist = new ArrayList<>(tags);
Collections.sort(taglist, new Comparator<Ref>()
{
  public int compare(Ref o1, Ref o2) {
   return o1.getName().compareTo(o2.getName());
 }
});

for (Ref ref : taglist) {
  System.out.println("Ref: " + ref.getName());
  System.out.println("ObjectId : " + ref.getObjectId());
  System.out.println("Ref short: " + Repository.shortenRefName(ref.getName()));
  }
}
Run Code Online (Sandbox Code Playgroud)

如何按创建日期对标签进行排序?

克隆存储库后,它可以与本地存储库一起使用:

// open a cloned repository
FileRepositoryBuilder builder = new FileRepositoryBuilder();
Repository repository = builder.setGitDir(new File(localPath + "/.git"))
  .readEnvironment()
  .findGitDir()
  .build();

final RevWalk walk = new RevWalk(repository);
List<Ref> call = new Git(repository).tagList().call();
RevTag rt;

Collections.sort(call, new Comparator<Ref>()
{
  public int compare(Ref o1, Ref o2)
  {
    java.util.Date d1 = null;
    java.util.Date d2 = null;
    try
    {
      d1 = walk.parseTag(o1.getObjectId()).getTaggerIdent().getWhen();
      d2 = walk.parseTag(o2.getObjectId()).getTaggerIdent().getWhen();

    } catch (IOException e)
    {
      e.printStackTrace();
    }
    return d1.compareTo(d2);
  }
});
Run Code Online (Sandbox Code Playgroud)

还有其他方法无需先克隆存储库吗?

Mag*_*äck 3

不,不可能。ls-remote 接口不公开标签的创建时间。您必须克隆 Git(或者至少获取其所有标签,这在大多数情况下几乎等同于克隆 git)。