Java 类org.eclipse.jgit.lib.Ref 实例源码

项目:Stringlate    文件:GitWrapper.java   
public static ArrayList<String> getBranches(final File repo) {
    try {
        final List<Ref> refs = Git.open(repo)
                .branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call();

        final ArrayList<String> result = new ArrayList<>();
        for (Ref ref : refs)
            result.add(ref.getName());

        return result;
    } catch (GitAPIException | IOException e) {
        e.printStackTrace();
    }

    return new ArrayList<>();
}
项目:incubator-netbeans    文件:PullCommand.java   
private String findRemoteBranchName () throws GitException {
    Ref ref = null;
    try {
        ref = getRepository().getRef(branchToMerge);
    } catch (IOException ex) {
        throw new GitException(ex);
    }
    if (ref != null) {
        for (String s : refSpecs) {
            RefSpec spec = new RefSpec(s);
            if (spec.matchDestination(ref)) {
                spec = spec.expandFromDestination(ref);
                String refName = spec.getSource();
                if (refName.startsWith(Constants.R_HEADS)) {
                    return refName.substring(Constants.R_HEADS.length());
                }
            }
        }
    }
    return branchToMerge;
}
项目:incubator-netbeans    文件:DeleteTagCommand.java   
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    Ref currentRef = repository.getTags().get(tagName);
    if (currentRef == null) {
        throw new GitException.MissingObjectException(tagName, GitObjectType.TAG);
    }
    String fullName = currentRef.getName();
    try {
        RefUpdate update = repository.updateRef(fullName);
        update.setRefLogMessage("tag deleted", false);
        update.setForceUpdate(true);
        Result deleteResult = update.delete();

        switch (deleteResult) {
            case IO_FAILURE:
            case LOCK_FAILURE:
            case REJECTED:
                throw new GitException.RefUpdateException("Cannot delete tag " + tagName, GitRefUpdateResult.valueOf(deleteResult.name()));
        }
    } catch (IOException ex) {
        throw new GitException(ex);
    }

}
项目:centraldogma    文件:GitRepository.java   
@VisibleForTesting
static void doRefUpdate(org.eclipse.jgit.lib.Repository jGitRepository, RevWalk revWalk,
                        String ref, ObjectId commitId) throws IOException {

    if (ref.startsWith(Constants.R_TAGS)) {
        final Ref oldRef = jGitRepository.exactRef(ref);
        if (oldRef != null) {
            throw new StorageException("tag ref exists already: " + ref);
        }
    }

    final RefUpdate refUpdate = jGitRepository.updateRef(ref);
    refUpdate.setNewObjectId(commitId);

    final Result res = refUpdate.update(revWalk);
    switch (res) {
        case NEW:
        case FAST_FORWARD:
            // Expected
            break;
        default:
            throw new StorageException("unexpected refUpdate state: " + res);
    }
}
项目:centraldogma    文件:GitRepositoryTest.java   
private static void testDoUpdateRef(String ref, ObjectId commitId, boolean tagExists) throws Exception {
    final org.eclipse.jgit.lib.Repository jGitRepo = mock(org.eclipse.jgit.lib.Repository.class);
    final RevWalk revWalk = mock(RevWalk.class);
    final RefUpdate refUpdate = mock(RefUpdate.class);

    when(jGitRepo.exactRef(ref)).thenReturn(tagExists ? mock(Ref.class) : null);
    when(jGitRepo.updateRef(ref)).thenReturn(refUpdate);

    when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.NEW);
    GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId);

    when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.FAST_FORWARD);
    GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId);

    when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.LOCK_FAILURE);
    assertThatThrownBy(() -> GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId))
            .isInstanceOf(StorageException.class);
}
项目:spring-cloud-release-tools    文件:GitRepo.java   
private Ref checkoutBranch(File projectDir, String branch)
        throws GitAPIException {
    Git git = this.gitFactory.open(projectDir);
    CheckoutCommand command = git.checkout().setName(branch);
    try {
        if (shouldTrack(git, branch)) {
            trackBranch(command, branch);
        }
        return command.call();
    }
    catch (GitAPIException e) {
        deleteBaseDirIfExists();
        throw e;
    } finally {
        git.close();
    }
}
项目:gitplex-mit    文件:RevisionSelector.java   
public RevisionSelector(String id, IModel<Project> projectModel, @Nullable String revision, boolean canCreateRef) {
    super(id);

    Preconditions.checkArgument(revision!=null || !canCreateRef);

    this.projectModel = projectModel;
    this.revision = revision;       
    if (canCreateRef) {
        Project project = projectModel.getObject();
        canCreateBranch = SecurityUtils.canWrite(project);                      
        canCreateTag = SecurityUtils.canCreateTag(project, Constants.R_TAGS);                       
    } else {
        canCreateBranch = false;
        canCreateTag = false;
    }
    if (revision != null) {
        Ref ref = projectModel.getObject().getRef(revision);
        branchesActive = ref == null || GitUtils.ref2tag(ref.getName()) == null;
    } else {
        branchesActive = true;
    }

    refs = findRefs();
}
项目:gitplex-mit    文件:Project.java   
@Nullable
public String getDefaultBranch() {
    if (defaultBranchOptional == null) {
        try {
            Ref headRef = getRepository().findRef("HEAD");
            if (headRef != null 
                    && headRef.isSymbolic() 
                    && headRef.getTarget().getName().startsWith(Constants.R_HEADS) 
                    && headRef.getObjectId() != null) {
                defaultBranchOptional = Optional.of(Repository.shortenRefName(headRef.getTarget().getName()));
            } else {
                defaultBranchOptional = Optional.absent();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return defaultBranchOptional.orNull();
}
项目:gitplex-mit    文件:Project.java   
public RevCommit getLastCommit() {
    if (lastCommitOptional == null) {
        RevCommit lastCommit = null;
        try {
            for (Ref ref: getRepository().getRefDatabase().getRefs(Constants.R_HEADS).values()) {
                RevCommit commit = getRevCommit(ref.getObjectId(), false);
                if (commit != null) {
                    if (lastCommit != null) {
                        if (commit.getCommitTime() > lastCommit.getCommitTime())
                            lastCommit = commit;
                    } else {
                        lastCommit = commit;
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        lastCommitOptional = Optional.fromNullable(lastCommit);
    }
    return lastCommitOptional.orNull();
}
项目:flow-platform    文件:JGitBasedClient.java   
@Override
public List<String> tags() throws GitException {
    try {
        Collection<Ref> refs = buildCommand(Git.lsRemoteRepository()
            .setTags(true)
            .setTimeout(GIT_TRANS_TIMEOUT)
            .setRemote(gitUrl)).call();


        List<Ref> listRefs = Lists.newArrayList(refs);
        listRefs.sort(JGitUtil.REF_COMPARATOR);

        return JGitUtil.simpleRef(refs);
    } catch (GitAPIException e) {
        throw new GitException("Fail to list tags from remote repo", ExceptionUtil.findRootCause(e));
    }
}
项目:flow-platform    文件:GitServiceTest.java   
@Test
public void should_list_existing_repo_from_git_workspace() throws Throwable {
    // given: copy exit git to workspace
    ClassLoader classLoader = TestBase.class.getClassLoader();
    URL resource = classLoader.getResource("hello.git");
    File path = new File(resource.getFile());
    FileUtils.copyDirectoryToDirectory(path, gitWorkspace.toFile());

    // when: load repos from git workspace
    List<Repository> repos = gitService.repos();
    Assert.assertEquals(1, repos.size());

    // then:
    Repository helloRepo = repos.get(0);
    Map<String, Ref> tags = helloRepo.getTags();
    Assert.assertEquals(1, tags.size());
    Assert.assertTrue(tags.keySet().contains("v1.0"));
    Assert.assertEquals("hello.git", helloRepo.getDirectory().getName());

    for (Repository repo : repos) {
        repo.close();
    }
}
项目:buckaroo    文件:GitTasks.java   
public static Single<ImmutableMap<String, GitCommitHash>> fetchTags(final String gitURL) {

        Preconditions.checkNotNull(gitURL);

        return Single.fromCallable(() -> {

            // The repository is not actually used, JGit just seems to require it.
            final Repository repository = FileRepositoryBuilder.create(Paths.get("").toFile());
            final Collection<Ref> refs = new LsRemoteCommand(repository)
                .setRemote(gitURL)
                .setTags(true)
                .call();

            final String prefix = "refs/tags/";

            return refs.stream()
                .filter(x -> x.getTarget().getName().startsWith(prefix))
                .collect(ImmutableMap.toImmutableMap(
                    x -> x.getTarget().getName().substring(prefix.length()),
                    x -> GitCommitHash.of((x.getPeeledObjectId() == null ? x.getObjectId() : x.getPeeledObjectId()).getName())));
        });
    }
项目:cdversion-maven-extension    文件:GitRevisionGeneratorTest.java   
@Test
public void testInit_nullHeadRefObjectId()
        throws RevisionGeneratorException,
        IOException {

    Repository repo = mock(Repository.class);
    Ref headRef = mock(Ref.class);

    when(git.getRepository()).thenReturn(repo);
    when(repo.isBare()).thenReturn(Boolean.FALSE);
    when(repo.getRef(eq("HEAD"))).thenReturn(headRef);
    when(headRef.getObjectId()).thenReturn(null);

    item.init(git, logger);

    Assert.assertEquals("GetRevision", "SNAPSHOT", item.getRevision());
    Assert.assertEquals("IsDirty", false, item.isDirty());

    verify(git).getRepository();
    verify(repo).isBare();
    verify(repo).getRef(eq("HEAD"));
    verify(logger).warn(eq("The Git repository is initialised, but no commits have been done: Setting revision to SNAPSHOT"));
    verifyNoMoreInteractions(git);
    verifyNoMoreInteractions(repo);
    verifyNoMoreInteractions(logger);
}
项目:RefDiff    文件:GitHelper.java   
public RevWalk fetchAndCreateNewRevsWalk(Repository repository, String branch) throws Exception {
    List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>();
    for (Ref ref : repository.getAllRefs().values()) {
        String refName = ref.getName();
        if (refName.startsWith(REMOTE_REFS_PREFIX)) {
            currentRemoteRefs.add(ref.getObjectId());
        }
    }

    List<TrackingRefUpdate> newRemoteRefs = this.fetch(repository);

    RevWalk walk = new RevWalk(repository);
    for (TrackingRefUpdate newRef : newRemoteRefs) {
        if (branch == null || newRef.getLocalName().endsWith("/" + branch)) {
            walk.markStart(walk.parseCommit(newRef.getNewObjectId()));
        }
    }
    for (ObjectId oldRef : currentRemoteRefs) {
        walk.markUninteresting(walk.parseCommit(oldRef));
    }
    walk.setRevFilter(commitsFilter);
    return walk;
}
项目:RefDiff    文件:GitHelper.java   
public RevWalk createAllRevsWalk(Repository repository, String branch) throws Exception {
    List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>();
    for (Ref ref : repository.getAllRefs().values()) {
        String refName = ref.getName();
        if (refName.startsWith(REMOTE_REFS_PREFIX)) {
            if (branch == null || refName.endsWith("/" + branch)) {
                currentRemoteRefs.add(ref.getObjectId());
            }
        }
    }

    RevWalk walk = new RevWalk(repository);
    for (ObjectId newRef : currentRemoteRefs) {
        walk.markStart(walk.parseCommit(newRef));
    }
    walk.setRevFilter(commitsFilter);
    return walk;
}
项目:RefDiff    文件:GitServiceImpl.java   
public RevWalk fetchAndCreateNewRevsWalk(Repository repository, String branch) throws Exception {
    List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>(); 
    for (Ref ref : repository.getAllRefs().values()) {
        String refName = ref.getName();
        if (refName.startsWith(REMOTE_REFS_PREFIX)) {
            currentRemoteRefs.add(ref.getObjectId());
        }
    }

    List<TrackingRefUpdate> newRemoteRefs = this.fetch(repository);

    RevWalk walk = new RevWalk(repository);
    for (TrackingRefUpdate newRef : newRemoteRefs) {
        if (branch == null || newRef.getLocalName().endsWith("/" + branch)) {
            walk.markStart(walk.parseCommit(newRef.getNewObjectId()));
        }
    }
    for (ObjectId oldRef : currentRemoteRefs) {
        walk.markUninteresting(walk.parseCommit(oldRef));
    }
    walk.setRevFilter(commitsFilter);
    return walk;
}
项目:RefDiff    文件:GitServiceImpl.java   
public RevWalk createAllRevsWalk(Repository repository, String branch) throws Exception {
    List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>(); 
    for (Ref ref : repository.getAllRefs().values()) {
        String refName = ref.getName();
        if (refName.startsWith(REMOTE_REFS_PREFIX)) {
            if (branch == null || refName.endsWith("/" + branch)) {
                currentRemoteRefs.add(ref.getObjectId());
            }
        }
    }

    RevWalk walk = new RevWalk(repository);
    for (ObjectId newRef : currentRemoteRefs) {
        walk.markStart(walk.parseCommit(newRef));
    }
    walk.setRevFilter(commitsFilter);
    return walk;
}
项目:gmds    文件:RefList.java   
public static void main(String[] args) throws IOException, GitAPIException {

    Repository repo = new FileRepository(Consts.META_REPO_PATH + ".git");

    // get a list of all known heads, tags, remotes, ...
    Collection<Ref> allRefs = repo.getAllRefs().values();

    // a RevWalk allows to walk over commits based on some filtering that is defined
    try (RevWalk revWalk = new RevWalk(repo)) {
        for (Ref ref : allRefs) {
            revWalk.markStart(revWalk.parseCommit(ref.getObjectId()));
        }
        System.out.println("Walking all commits starting with " + allRefs.size() + " refs: " + allRefs);
        int count = 0;
        for (RevCommit commit : revWalk) {
            System.out.println("Commit: " + commit);
            count++;
        }
        System.out.println("Had " + count + " commits");
    }
}
项目:gmds    文件:Branches.java   
public static void main(String[] args) throws IOException, GitAPIException {
        Repository repo = Commands.getRepo(Consts.META_REPO_PATH);

        Git git = new Git(repo);

        // Create a new branch
        git.branchCreate().setName("newBranch").call();
// Checkout the new branch
        git.checkout().setName("newBranch").call();
        // List the existing branches
        List<Ref> listRefsBranches = git.branchList().setListMode(ListMode.ALL).call();
        listRefsBranches.forEach((refBranch) -> {
            System.out.println("Branch : " + refBranch.getName());
        });
// Go back on "master" branch and remove the created one
        git.checkout().setName("master");
        git.branchDelete().setBranchNames("newBranch");
    }
项目:fabric8-forge    文件:RepositoryResource.java   
protected ObjectId getBranchObjectId(Git git) {
    Ref branchRef = null;
    try {
        String branchRevName = "refs/heads/" + branch;
        List<Ref> branches = git.branchList().call();
        for (Ref ref : branches) {
            String revName = ref.getName();
            if (Objects.equals(branchRevName, revName)) {
                branchRef = ref;
                break;
            }
        }
    } catch (GitAPIException e) {
        LOG.warn("Failed to find branches " + e, e);
    }

    ObjectId branchObjectId = null;
    if (branchRef != null) {
        branchObjectId = branchRef.getObjectId();
    }
    return branchObjectId;
}
项目:fabric8-forge    文件:RepositoryResource.java   
protected void checkoutBranch(Git git, GitContext context) throws GitAPIException {
    String current = currentBranch(git);
    if (Objects.equals(current, branch)) {
        return;
    }
    System.out.println("Checking out branch: " + branch);
    // lets check if the branch exists
    CheckoutCommand command = git.checkout().setName(branch);
    boolean exists = localBranchExists(git, branch);
    if (!exists) {
        command = command.setCreateBranch(true).setForce(true).
                setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).
                setStartPoint(getRemote() + "/" + branch);
    }
    Ref ref = command.call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Checked out branch " + branch + " with results " + ref.getName());
    }
    configureBranch(git, branch);
}
项目:srcdeps-core    文件:JGitScm.java   
/**
 * Walks back through the history of the {@code advertisedRefs} and tries to find the given {@code commitSha1}.
 *
 * @param repository
 *            the current {@link Repository} to search in
 * @param advertisedRefs
 *            the list of refs that were fetched and whose histories should be searched through
 * @param commitSha1
 *            the commit to find
 * @param url
 *            the URL that was used to fetch
 * @throws ScmException
 *             if the given {@code commitSha1} could not be found in the history of any of the
 *             {@code advertisedRefs}
 */
private void assertRevisionFetched(Repository repository, Collection<Ref> advertisedRefs, String commitSha1,
        String url) throws ScmException {
    ObjectId needle = ObjectId.fromString(commitSha1);
    try {
        for (Ref ref : advertisedRefs) {

            try (RevWalk walk = new RevWalk(repository)) {
                walk.markStart(walk.parseCommit(ref.getTarget().getObjectId()));
                walk.setRetainBody(false);

                for (RevCommit commit : walk) {
                    if (commit.getId().equals(needle)) {
                        return;
                    }
                }
            }

        }
    } catch (IOException e) {
        new ScmException(String.format("Could not fetch ref [%s] from [%s]", commitSha1, url), e);
    }
    throw new ScmException(String.format("Could not fetch ref [%s] from [%s]", commitSha1, url));
}
项目:mdw    文件:VersionControlGit.java   
/**
 * Storing revisions in Git Notes causes object hash computation, which is expensive.
 */
public AssetRevision getRevisionGitNotes(File file) throws IOException {
    AssetRevision rev = file2rev.get(file);
    if (rev == null) {
        ObjectId workingId = getObjectId(file);

        try (RevWalk walk = new RevWalk(localRepo)) {
            Ref ref = localRepo.findRef(NOTES_REF);
            if (ref != null) {
                RevCommit notesCommit = walk.parseCommit(ref.getObjectId());
                NoteMap notes = NoteMap.read(walk.getObjectReader(), notesCommit);
                Note note = notes.getNote(workingId);
                if (note != null) {
                    ObjectLoader loader = localRepo.open(note.getData());
                    String noteStr = new String(loader.getBytes()).trim();
                    rev = parseAssetRevision(noteStr);
                    file2rev.put(file, rev);
                    return rev;
                }
            }
        }
    }

    return rev;
}
项目:release-maven-plugin-parent    文件:GitProposedTagsBuilder.java   
private void validateTagNoAlreadyInRemoteRepo() throws SCMException {
    final List<String> tagNamesToSearchFor = new ArrayList<>();
    for (final ProposedTag annotatedTag : proposedTags.values()) {
        tagNamesToSearchFor.add(annotatedTag.name());
    }

    final List<String> matchingRemoteTags = new ArrayList<>();
    final Collection<Ref> remoteTags = repo.allRemoteTags();
    for (final Ref remoteTag : remoteTags) {
        for (final String proposedTag : tagNamesToSearchFor) {
            if (remoteTag.getName().equals("refs/tags/" + proposedTag)) {
                matchingRemoteTags.add(proposedTag);
            }
        }
    }

    if (!matchingRemoteTags.isEmpty()) {
        final SCMException exception = new SCMException(
                "Cannot release because there is already a tag with the same build number on the remote Git repo.");
        for (final String matchingRemoteTag : matchingRemoteTags) {
            exception.add(" * There is already a tag named %s in the remote repo.", matchingRemoteTag);
        }
        throw exception.add("Please try releasing again with a new build number.");
    }
}
项目:release-maven-plugin-parent    文件:GitRepository.java   
@Override
public List<ProposedTag> tagsForVersion(final String module, final String versionWithoutBuildNumber)
        throws SCMException {
    final List<ProposedTag> results = new ArrayList<>();
    List<Ref> tags;
    try {
        tags = getGit().tagList().call();
    } catch (final GitAPIException e) {
        throw new SCMException(e, "Error while getting a list of tags in the local repo");
    }
    Collections.reverse(tags);
    final String tagWithoutBuildNumber = module + "-" + versionWithoutBuildNumber;
    for (final Ref tag : tags) {
        if (isPotentiallySameVersionIgnoringBuildNumber(tagWithoutBuildNumber, tag.getName())) {
            results.add(fromRef(tag));
        }
    }
    return results;

}
项目:release-maven-plugin-parent    文件:GitRepository.java   
@Override
public ProposedTag fromRef(final Ref gitTag) throws SCMException {
    notNull(gitTag, "gitTag");

    final RevWalk walk = new RevWalk(getGit().getRepository());
    final ObjectId tagId = gitTag.getObjectId();
    JSONObject message;
    try {
        final RevTag tag = walk.parseTag(tagId);
        message = (JSONObject) JSONValue.parse(tag.getFullMessage());
    } catch (final IOException e) {
        throw new SCMException(e, "Error while looking up tag because RevTag could not be parsed! Object-id was %s",
                tagId);
    } finally {
        walk.dispose();
    }
    if (message == null) {
        message = new JSONObject();
        message.put(VERSION, "0");
        message.put(BUILD_NUMBER, "0");
    }
    return new GitProposedTag(getGit(), log, gitTag, stripRefPrefix(gitTag.getName()), message,
            config.getRemoteUrlOrNull());
}
项目:release-maven-plugin-parent    文件:AnnotatedTagTest.java   
@Test
public void aTagCanBeCreatedFromAGitTag() throws Exception {
    final TestProject project = TestProject.singleModuleProject();
    when(gitFactory.newGit()).thenReturn(project.local);
    final GitRepository repo = new GitRepository(log, config);
    final ProposedTagsBuilder builder = repo.newProposedTagsBuilder();
    final Version ver = mock(Version.class);
    when(ver.getBusinessVersion()).thenReturn("the-version");
    when(ver.getBuildNumber()).thenReturn(2134l);
    builder.add("my-name", ver);
    final ProposedTag tag = builder.build().getTag("my-name", ver);
    tag.saveAtHEAD();

    final Ref ref = project.local.tagList().call().get(0);
    final ProposedTag inflatedTag = repo.fromRef(ref);
    assertThat(inflatedTag.name(), equalTo("my-name"));
    assertThat(inflatedTag.getBusinessVersion(), equalTo("the-version"));
    assertThat(inflatedTag.getBuildNumber(), equalTo(2134L));
}
项目:release-maven-plugin-parent    文件:GitMatchers.java   
public static Matcher<Git> hasTag(final String tag) {
    return new TypeSafeDiagnosingMatcher<Git>() {
        @Override
        protected boolean matchesSafely(final Git repo, final Description mismatchDescription) {
            try {
                mismatchDescription.appendValueList("a git repo with tags: ", ", ", "",
                        repo.getRepository().getTags().keySet());
                for (final Ref ref : repo.tagList().call()) {
                    final String currentTag = ref.getName().replace(REFS_TAGS, "");
                    if (tag.equals(currentTag)) {
                        return true;
                    }
                }
                return false;
            } catch (final GitAPIException e) {
                throw new RuntimeException("Couldn't access repo", e);
            }
        }

        @Override
        public void describeTo(final Description description) {
            description.appendText("a git repo with the tag " + tag);
        }
    };
}
项目:gerrit    文件:TagSet.java   
private void addRef(TagWalk rw, Ref ref) {
  try {
    TagCommit commit = (TagCommit) rw.parseCommit(ref.getObjectId());
    rw.markStart(commit);

    int flag = refs.size();
    commit.refFlags.set(flag);
    refs.put(ref.getName(), new CachedRef(ref, flag));
  } catch (IncorrectObjectTypeException notCommit) {
    // No need to spam the logs.
    // Quite many refs will point to non-commits.
    // For instance, refs from refs/cache-automerge
    // will often end up here.
  } catch (IOException e) {
    log.warn("Error on " + ref.getName() + " of " + projectName, e);
  }
}
项目:gerrit    文件:ReceiveCommits.java   
private void initChangeRefMaps() {
  if (refsByChange == null) {
    int estRefsPerChange = 4;
    refsById = MultimapBuilder.hashKeys().arrayListValues().build();
    refsByChange =
        MultimapBuilder.hashKeys(allRefs().size() / estRefsPerChange)
            .arrayListValues(estRefsPerChange)
            .build();
    for (Ref ref : allRefs().values()) {
      ObjectId obj = ref.getObjectId();
      if (obj != null) {
        PatchSet.Id psId = PatchSet.Id.fromRef(ref.getName());
        if (psId != null) {
          refsById.put(obj, ref);
          refsByChange.put(psId.getParentKey(), ref);
        }
      }
    }
  }
}
项目:reckon    文件:GitInventorySupplier.java   
private Set<TaggedVersion> getTaggedVersions(RevWalk walk) throws IOException {
  Set<TaggedVersion> versions = new HashSet<>();

  for (Ref ref : repo.getRefDatabase().getRefs(Constants.R_TAGS).values()) {
    Ref tag = repo.peel(ref);
    // only annotated tags return a peeled object id
    ObjectId objectId =
        tag.getPeeledObjectId() == null ? tag.getObjectId() : tag.getPeeledObjectId();
    RevCommit commit = walk.parseCommit(objectId);
    tagParser
        .apply(tag)
        .ifPresent(
            version -> {
              versions.add(new TaggedVersion(version, commit));
            });
  }
  return versions;
}
项目:appformer    文件:RefTreeUpdateCommand.java   
private void symRef(final Git git,
                    final String name,
                    final String dst)
        throws java.io.IOException {
    commit(git.getRepository(),
           null,
           (reader, tree) -> {
               Ref old = tree.exactRef(reader,
                                       name);
               Ref newx = tree.exactRef(reader,
                                        dst);
               final Command n;
               if (newx != null) {
                   n = new Command(old,
                                   new SymbolicRef(name,
                                                   newx));
               } else {
                   n = new Command(old,
                                   new SymbolicRef(name,
                                                   new ObjectIdRef.Unpeeled(Ref.Storage.NEW,
                                                                            dst,
                                                                            null)));
               }
               return tree.apply(Collections.singleton(n));
           });
}
项目:editor-de-servicos    文件:RepositorioGit.java   
private void checkoutNovoBranch(String novoBranch, String pontoDeInicio) throws GitAPIException, IOException {
    try {
        Ref result = git.branchCreate()
                .setName(novoBranch)
                .setStartPoint(pontoDeInicio)
                .setUpstreamMode(NOTRACK)
                .call();

        Marker info = append("git.branch", git.getRepository().getBranch())
                .and(append("git.state", git.getRepository().getRepositoryState().toString()))
                .and(append("branch.name", novoBranch))
                .and(append("branch.start", R_HEADS + MASTER))
                .and(append("branch.result", result.getName()));

        log.info(info, "git branch {}", novoBranch);

        branchAtual = novoBranch;

    } catch (Exception e) {
        branchAtual = null;
        throw e;
    }
}
项目:plugins_replication    文件:PushOne.java   
private List<RemoteRefUpdate> doPushDelta(Map<String, Ref> local) throws IOException {
  List<RemoteRefUpdate> cmds = new ArrayList<>();
  boolean noPerms = !pool.isReplicatePermissions();
  for (String src : delta) {
    RefSpec spec = matchSrc(src);
    if (spec != null) {
      // If the ref still exists locally, send it, otherwise delete it.
      Ref srcRef = local.get(src);

      // Second try to ensure that the ref is truly not found locally
      if (srcRef == null) {
        srcRef = git.exactRef(src);
      }

      if (srcRef != null && canPushRef(src, noPerms)) {
        push(cmds, spec, srcRef);
      } else if (config.isMirror()) {
        delete(cmds, spec);
      }
    }
  }
  return cmds;
}
项目:gerrit    文件:SubmitOnPushIT.java   
private void assertTag(Project.NameKey project, String branch, PushOneCommit.Tag tag)
    throws Exception {
  try (Repository repo = repoManager.openRepository(project)) {
    Ref tagRef = repo.findRef(tag.name);
    assertThat(tagRef).isNotNull();
    ObjectId taggedCommit = null;
    if (tag instanceof PushOneCommit.AnnotatedTag) {
      PushOneCommit.AnnotatedTag annotatedTag = (PushOneCommit.AnnotatedTag) tag;
      try (RevWalk rw = new RevWalk(repo)) {
        RevObject object = rw.parseAny(tagRef.getObjectId());
        assertThat(object).isInstanceOf(RevTag.class);
        RevTag tagObject = (RevTag) object;
        assertThat(tagObject.getFullMessage()).isEqualTo(annotatedTag.message);
        assertThat(tagObject.getTaggerIdent()).isEqualTo(annotatedTag.tagger);
        taggedCommit = tagObject.getObject();
      }
    } else {
      taggedCommit = tagRef.getObjectId();
    }
    ObjectId headCommit = repo.exactRef(branch).getObjectId();
    assertThat(taggedCommit).isNotNull();
    assertThat(taggedCommit).isEqualTo(headCommit);
  }
}
项目:che    文件:JGitConnection.java   
@Override
public Branch branchCreate(String name, String startPoint) throws GitException {
  CreateBranchCommand createBranchCommand = getGit().branchCreate().setName(name);
  if (startPoint != null) {
    createBranchCommand.setStartPoint(startPoint);
  }
  try {
    Ref brRef = createBranchCommand.call();
    String refName = brRef.getName();
    String displayName = Repository.shortenRefName(refName);
    return newDto(Branch.class)
        .withName(refName)
        .withDisplayName(displayName)
        .withActive(false)
        .withRemote(false);
  } catch (GitAPIException exception) {
    throw new GitException(exception.getMessage(), exception);
  }
}
项目:verigreen    文件:JGitOperator.java   
boolean isRefBehind( Ref behind, Ref tracking ) throws IOException {
  RevWalk walk = new RevWalk( _git.getRepository() );
  try {
    RevCommit behindCommit = walk.parseCommit( behind.getObjectId() );
    RevCommit trackingCommit = walk.parseCommit( tracking.getObjectId() );
    walk.setRevFilter( RevFilter.MERGE_BASE );
    walk.markStart( behindCommit );
    walk.markStart( trackingCommit );
    RevCommit mergeBase = walk.next();
    walk.reset();
    walk.setRevFilter( RevFilter.ALL );
    int aheadCount = RevWalkUtils.count( walk, behindCommit, mergeBase );
    int behindCount = RevWalkUtils.count( walk, trackingCommit, mergeBase );

    return behindCount > aheadCount ? true:false;
  } catch (Throwable e) {
         throw new RuntimeException(String.format(
                 "Failed to check if [%s] behind [%s]",
                 behind,
                 tracking), e);
     } 
  finally {
    walk.dispose();
  }
}
项目:gerrit-tools    文件:MergeStableIntoCurrentBranchCommand.java   
private boolean canMerge(final Repository repository) {
    String message = null;
    Exception ex = null;
    try {
        Ref head = repository.getRef(Constants.HEAD);
        if (head == null || !head.isSymbolic())
            message = UIText.MergeAction_HeadIsNoBranch;
        else if (!repository.getRepositoryState().equals(
                RepositoryState.SAFE))
            message = NLS.bind(UIText.MergeAction_WrongRepositoryState,
                    repository.getRepositoryState());
        else if (!head.getLeaf().getName().startsWith("refs/heads/features"))    { //$NON-NLS-1$
            message = "Current branch is not a feature branch.";
        }
    } catch (IOException e) {
        message = e.getMessage();
        ex = e;
    }

    if (message != null)
        org.eclipse.egit.ui.Activator.handleError(message, ex, true);
    return (message == null);
}
项目:gerrit    文件:MergeOp.java   
private Set<RevCommit> getAlreadyAccepted(OpenRepo or, CodeReviewCommit branchTip)
    throws IntegrationException {
  Set<RevCommit> alreadyAccepted = new HashSet<>();

  if (branchTip != null) {
    alreadyAccepted.add(branchTip);
  }

  try {
    for (Ref r : or.repo.getRefDatabase().getRefs(Constants.R_HEADS).values()) {
      try {
        CodeReviewCommit aac = or.rw.parseCommit(r.getObjectId());
        if (!commitStatus.commits.values().contains(aac)) {
          alreadyAccepted.add(aac);
        }
      } catch (IncorrectObjectTypeException iote) {
        // Not a commit? Skip over it.
      }
    }
  } catch (IOException e) {
    throw new IntegrationException("Failed to determine already accepted commits.", e);
  }

  logDebug("Found {} existing heads", alreadyAccepted.size());
  return alreadyAccepted;
}
项目:gerrit    文件:CommentsUtil.java   
public List<Comment> byPatchSet(ReviewDb db, ChangeNotes notes, PatchSet.Id psId)
    throws OrmException {
  if (!migration.readChanges()) {
    return sort(toComments(serverId, db.patchComments().byPatchSet(psId).toList()));
  }
  List<Comment> comments = new ArrayList<>();
  comments.addAll(publishedByPatchSet(db, notes, psId));

  for (Ref ref : getDraftRefs(notes.getChangeId())) {
    Account.Id account = Account.Id.fromRefSuffix(ref.getName());
    if (account != null) {
      comments.addAll(draftByPatchSetAuthor(db, psId, account, notes));
    }
  }
  return sort(comments);
}