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

项目: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);
}
项目:gitplex-mit    文件:GitUtils.java   
public static void deleteRef(RefUpdate refUpdate) {
    try {
        refUpdate.setForceUpdate(true);
        RefUpdate.Result result = refUpdate.delete();
        if (result == RefUpdate.Result.LOCK_FAILURE
                && refUpdate.getExpectedOldObjectId() != null
                && !refUpdate.getExpectedOldObjectId().equals(refUpdate.getOldObjectId())) {
            throw new ObsoleteCommitException(refUpdate.getOldObjectId());
        } else if (result != RefUpdate.Result.FAST_FORWARD && result != RefUpdate.Result.FORCED
                && result != RefUpdate.Result.NEW && result != RefUpdate.Result.NO_CHANGE) {
            throw new RefUpdateException(result);
        } 
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:gitplex-mit    文件:DefaultPullRequestManager.java   
@Transactional
@Override
public void open(PullRequest request) {
    request.setNumber(getNextNumber(request.getTargetProject()));
    dao.persist(request);

    RefUpdate refUpdate = GitUtils.getRefUpdate(request.getTargetProject().getRepository(), request.getBaseRef());
    refUpdate.setNewObjectId(ObjectId.fromString(request.getBaseCommitHash()));
    GitUtils.updateRef(refUpdate);

    refUpdate = GitUtils.getRefUpdate(request.getTargetProject().getRepository(), request.getHeadRef());
    refUpdate.setNewObjectId(ObjectId.fromString(request.getHeadCommitHash()));
    GitUtils.updateRef(refUpdate);

    for (PullRequestUpdate update: request.getUpdates()) {
        pullRequestUpdateManager.save(update, false);
    }

    for (ReviewInvitation invitation: request.getReviewInvitations())
        reviewInvitationManager.save(invitation);

    checkAsync(request);

    listenerRegistry.post(new PullRequestOpened(request));
}
项目:gitplex-mit    文件:DefaultPullRequestManager.java   
private void checkUpdate(PullRequest request) {
    if (!request.getHeadCommitHash().equals(request.getSource().getObjectName())) {
        ObjectId mergeBase = GitUtils.getMergeBase(
                request.getTargetProject().getRepository(), request.getTarget().getObjectId(), 
                request.getSourceProject().getRepository(), request.getSource().getObjectId(), 
                GitUtils.branch2ref(request.getSourceBranch()));
        if (mergeBase != null) {
            PullRequestUpdate update = new PullRequestUpdate();
            update.setRequest(request);
            update.setHeadCommitHash(request.getSource().getObjectName());
            update.setMergeBaseCommitHash(mergeBase.name());
            request.addUpdate(update);
            pullRequestUpdateManager.save(update, true);

            RefUpdate refUpdate = GitUtils.getRefUpdate(request.getTargetProject().getRepository(), 
                    request.getHeadRef());
            refUpdate.setNewObjectId(ObjectId.fromString(request.getHeadCommitHash()));
            GitUtils.updateRef(refUpdate);
        }
    }
}
项目:gmds    文件:Commands.java   
/**
 *
 * @param repo
 * @param objectId
 * @throws IOException
 */
public static void updateMasterRecord(Repository repo, ObjectId objectId) throws IOException {

    RefUpdate refUpdate = repo.updateRef(Constants.HEAD);
    refUpdate.setNewObjectId(objectId);
    final RefUpdate.Result result = refUpdate.forceUpdate();

    switch (result) {
        case NEW:
            System.out.println("New commit!\n");
            break;
        case FORCED:
            System.out.println("Forced change commit!\n");
            break;
        default: {
            System.out.println(result.name());
        }
    }
}
项目:che    文件:JGitConnection.java   
@Override
public void tagDelete(String name) throws GitException {
  try {
    Ref tagRef = repository.findRef(name);
    if (tagRef == null) {
      throw new GitException("Tag " + name + " not found. ");
    }

    RefUpdate updateRef = repository.updateRef(tagRef.getName());
    updateRef.setRefLogMessage("tag deleted", false);
    updateRef.setForceUpdate(true);
    Result deleteResult = updateRef.delete();
    if (deleteResult != Result.FORCED && deleteResult != Result.FAST_FORWARD) {
      throw new GitException(format(ERROR_TAG_DELETE, name, deleteResult));
    }
  } catch (IOException exception) {
    throw new GitException(exception.getMessage(), exception);
  }
}
项目:gerrit    文件:ChangeEditUtil.java   
private static void deleteRef(Repository repo, ChangeEdit edit) throws IOException {
  String refName = edit.getRefName();
  RefUpdate ru = repo.updateRef(refName, true);
  ru.setExpectedOldObjectId(edit.getEditCommit());
  ru.setForceUpdate(true);
  RefUpdate.Result result = ru.delete();
  switch (result) {
    case FORCED:
    case NEW:
    case NO_CHANGE:
      break;
    case FAST_FORWARD:
    case IO_FAILURE:
    case LOCK_FAILURE:
    case NOT_ATTEMPTED:
    case REJECTED:
    case REJECTED_CURRENT_BRANCH:
    case RENAMED:
    case REJECTED_MISSING_OBJECT:
    case REJECTED_OTHER_REASON:
    default:
      throw new IOException(String.format("Failed to delete ref %s: %s", refName, result));
  }
}
项目:gerrit    文件:ChangeEditModifier.java   
private void updateReference(
    Repository repository,
    String refName,
    ObjectId currentObjectId,
    ObjectId targetObjectId,
    Timestamp timestamp)
    throws IOException {
  RefUpdate ru = repository.updateRef(refName);
  ru.setExpectedOldObjectId(currentObjectId);
  ru.setNewObjectId(targetObjectId);
  ru.setRefLogIdent(getRefLogIdent(timestamp));
  ru.setRefLogMessage("inline edit (amend)", false);
  ru.setForceUpdate(true);
  try (RevWalk revWalk = new RevWalk(repository)) {
    RefUpdate.Result res = ru.update(revWalk);
    if (res != RefUpdate.Result.NEW && res != RefUpdate.Result.FORCED) {
      throw new IOException(
          "cannot update "
              + ru.getName()
              + " in "
              + repository.getDirectory()
              + ": "
              + ru.getResult());
    }
  }
}
项目:gerrit    文件:RepoSequence.java   
@Override
public RefUpdate.Result call() throws Exception {
  Ref ref = repo.exactRef(refName);
  afterReadRef.run();
  ObjectId oldId;
  if (ref == null) {
    oldId = ObjectId.zeroId();
  } else {
    oldId = ref.getObjectId();
    int next = parse(rw, oldId);
    if (next >= value) {
      // a concurrent write updated the ref already to this or a higher value
      return RefUpdate.Result.NO_CHANGE;
    }
  }
  return store(repo, rw, oldId, value);
}
项目:gerrit    文件:RepoSequence.java   
private RefUpdate.Result store(Repository repo, RevWalk rw, @Nullable ObjectId oldId, int val)
    throws IOException {
  ObjectId newId;
  try (ObjectInserter ins = repo.newObjectInserter()) {
    newId = ins.insert(OBJ_BLOB, Integer.toString(val).getBytes(UTF_8));
    ins.flush();
  }
  RefUpdate ru = repo.updateRef(refName);
  if (oldId != null) {
    ru.setExpectedOldObjectId(oldId);
  }
  ru.disableRefLog();
  ru.setNewObjectId(newId);
  ru.setForceUpdate(true); // Required for non-commitish updates.
  RefUpdate.Result result = ru.update(rw);
  if (refUpdated(result)) {
    gitRefUpdated.fire(projectName, ru, null);
  }
  return result;
}
项目:gerrit    文件:AccountsUpdate.java   
public static void deleteUserBranch(
    Repository repo,
    Project.NameKey project,
    GitReferenceUpdated gitRefUpdated,
    @Nullable IdentifiedUser user,
    PersonIdent refLogIdent,
    Account.Id accountId)
    throws IOException {
  String refName = RefNames.refsUsers(accountId);
  Ref ref = repo.exactRef(refName);
  if (ref == null) {
    return;
  }

  RefUpdate ru = repo.updateRef(refName);
  ru.setExpectedOldObjectId(ref.getObjectId());
  ru.setNewObjectId(ObjectId.zeroId());
  ru.setForceUpdate(true);
  ru.setRefLogIdent(refLogIdent);
  ru.setRefLogMessage("Delete Account", true);
  Result result = ru.delete();
  if (result != Result.FORCED) {
    throw new IOException(String.format("Failed to delete ref %s: %s", refName, result.name()));
  }
  gitRefUpdated.fire(project, ru, user != null ? user.getAccount() : null);
}
项目:gerrit    文件:Schema_146.java   
public void createUserBranch(
    Repository repo,
    ObjectInserter oi,
    ObjectId emptyTree,
    Account.Id accountId,
    Timestamp registeredOn)
    throws IOException {
  ObjectId id = createInitialEmptyCommit(oi, emptyTree, registeredOn);

  String refName = RefNames.refsUsers(accountId);
  RefUpdate ru = repo.updateRef(refName);
  ru.setExpectedOldObjectId(ObjectId.zeroId());
  ru.setNewObjectId(id);
  ru.setRefLogIdent(serverIdent);
  ru.setRefLogMessage(CREATE_ACCOUNT_MSG, false);
  Result result = ru.update();
  if (result != Result.NEW) {
    throw new IOException(String.format("Failed to update ref %s: %s", refName, result.name()));
  }
}
项目:gerrit    文件:AllProjectsCreator.java   
public void create() throws IOException, ConfigInvalidException {
  try (Repository git = mgr.openRepository(allProjectsName)) {
    initAllProjects(git);
  } catch (RepositoryNotFoundException notFound) {
    // A repository may be missing if this project existed only to store
    // inheritable permissions. For example 'All-Projects'.
    try (Repository git = mgr.createRepository(allProjectsName)) {
      initAllProjects(git);
      RefUpdate u = git.updateRef(Constants.HEAD);
      u.link(RefNames.REFS_CONFIG);
    } catch (RepositoryNotFoundException err) {
      String name = allProjectsName.get();
      throw new IOException("Cannot create repository " + name, err);
    }
  }
}
项目:gerrit    文件:ForcePushIT.java   
@Test
public void forcePushNotAllowed() throws Exception {
  ObjectId initial = repo().exactRef(HEAD).getLeaf().getObjectId();
  PushOneCommit push1 =
      pushFactory.create(db, admin.getIdent(), testRepo, "change1", "a.txt", "content");
  PushOneCommit.Result r1 = push1.to("refs/heads/master");
  r1.assertOkStatus();

  // Reset HEAD to initial so the new change is a non-fast forward
  RefUpdate ru = repo().updateRef(HEAD);
  ru.setNewObjectId(initial);
  assertThat(ru.forceUpdate()).isEqualTo(RefUpdate.Result.FORCED);

  PushOneCommit push2 =
      pushFactory.create(db, admin.getIdent(), testRepo, "change2", "b.txt", "content");
  push2.setForce(true);
  PushOneCommit.Result r2 = push2.to("refs/heads/master");
  r2.assertErrorStatus("non-fast forward");
}
项目:gerrit    文件:ForcePushIT.java   
@Test
public void forcePushAllowed() throws Exception {
  ObjectId initial = repo().exactRef(HEAD).getLeaf().getObjectId();
  grant(project, "refs/*", Permission.PUSH, true);
  PushOneCommit push1 =
      pushFactory.create(db, admin.getIdent(), testRepo, "change1", "a.txt", "content");
  PushOneCommit.Result r1 = push1.to("refs/heads/master");
  r1.assertOkStatus();

  // Reset HEAD to initial so the new change is a non-fast forward
  RefUpdate ru = repo().updateRef(HEAD);
  ru.setNewObjectId(initial);
  assertThat(ru.forceUpdate()).isEqualTo(RefUpdate.Result.FORCED);

  PushOneCommit push2 =
      pushFactory.create(db, admin.getIdent(), testRepo, "change2", "b.txt", "content");
  push2.setForce(true);
  PushOneCommit.Result r2 = push2.to("refs/heads/master");
  r2.assertOkStatus();
}
项目:gerrit    文件:GroupsIT.java   
private void createGroupBranch(Project.NameKey project, String ref) throws IOException {
  try (Repository r = repoManager.openRepository(project);
      ObjectInserter oi = r.newObjectInserter();
      RevWalk rw = new RevWalk(r)) {
    ObjectId emptyTree = oi.insert(Constants.OBJ_TREE, new byte[] {});
    PersonIdent ident = new PersonIdent(serverIdent.get(), TimeUtil.nowTs());

    CommitBuilder cb = new CommitBuilder();
    cb.setTreeId(emptyTree);
    cb.setCommitter(ident);
    cb.setAuthor(ident);
    cb.setMessage("Create group");
    ObjectId emptyCommit = oi.insert(cb);

    oi.flush();

    RefUpdate updateRef = r.updateRef(ref);
    updateRef.setExpectedOldObjectId(ObjectId.zeroId());
    updateRef.setNewObjectId(emptyCommit);
    assertThat(updateRef.update(rw)).isEqualTo(RefUpdate.Result.NEW);
  }
}
项目:gerrit    文件:ChangeRebuilderIT.java   
@Test
public void rebuildDeletesOldDraftRefs() throws Exception {
  PushOneCommit.Result r = createChange();
  Change.Id id = r.getPatchSetId().getParentKey();
  putDraft(user, id, 1, "comment", null);

  Account.Id otherAccountId = new Account.Id(user.getId().get() + 1234);
  String otherDraftRef = refsDraftComments(id, otherAccountId);

  try (Repository repo = repoManager.openRepository(allUsers);
      ObjectInserter ins = repo.newObjectInserter()) {
    ObjectId sha = ins.insert(OBJ_BLOB, "garbage data".getBytes(UTF_8));
    ins.flush();
    RefUpdate ru = repo.updateRef(otherDraftRef);
    ru.setExpectedOldObjectId(ObjectId.zeroId());
    ru.setNewObjectId(sha);
    assertThat(ru.update()).isEqualTo(RefUpdate.Result.NEW);
  }

  checker.rebuildAndCheckChanges(id);

  try (Repository repo = repoManager.openRepository(allUsers)) {
    assertThat(repo.exactRef(otherDraftRef)).isNull();
  }
}
项目:gerrit    文件:NoteDbOnlyIT.java   
@Override
public void afterUpdateRepos() throws Exception {
  // Reopen repo and update ref, to simulate a concurrent write in another
  // thread. Only do this the first time the listener is called.
  if (calledCount.getAndIncrement() > 0) {
    return;
  }
  try (Repository repo = repoManager.openRepository(project);
      RevWalk rw = new RevWalk(repo);
      ObjectInserter ins = repo.newObjectInserter()) {
    String master = "refs/heads/master";
    ObjectId oldId = repo.exactRef(master).getObjectId();
    ObjectId newId = newCommit(rw, ins, oldId, MSG_PREFIX + calledCount.get());
    ins.flush();
    RefUpdate ru = repo.updateRef(master);
    ru.setExpectedOldObjectId(oldId);
    ru.setNewObjectId(newId);
    assertThat(ru.update(rw)).isEqualTo(RefUpdate.Result.FAST_FORWARD);
  }
}
项目:gerrit    文件:AbstractQueryChangesTest.java   
@Test
public void reindexIfStale() throws Exception {
  Account.Id user = createAccount("user");
  Project.NameKey project = new Project.NameKey("repo");
  TestRepository<Repo> repo = createProject(project.get());
  Change change = insert(repo, newChange(repo));
  String changeId = change.getKey().get();
  ChangeNotes notes = notesFactory.create(db, change.getProject(), change.getId());
  PatchSet ps = psUtil.get(db, notes, change.currentPatchSetId());

  requestContext.setContext(newRequestContext(user));
  gApi.changes().id(changeId).edit().create();
  assertQuery("has:edit", change);
  assertThat(indexer.reindexIfStale(project, change.getId()).get()).isFalse();

  // Delete edit ref behind index's back.
  RefUpdate ru =
      repo.getRepository().updateRef(RefNames.refsEdit(user, change.getId(), ps.getId()));
  ru.setForceUpdate(true);
  assertThat(ru.delete()).isEqualTo(RefUpdate.Result.FORCED);

  // Index is stale.
  assertQuery("has:edit", change);
  assertThat(indexer.reindexIfStale(project, change.getId()).get()).isTrue();
  assertQuery("has:edit");
}
项目:gerrit    文件:RepoSequenceTest.java   
@Test
public void failAfterRetryerGivesUp() throws Exception {
  AtomicInteger bgCounter = new AtomicInteger(1234);
  RepoSequence s =
      newSequence(
          "id",
          1,
          10,
          () -> writeBlob("id", Integer.toString(bgCounter.getAndAdd(1000))),
          RetryerBuilder.<RefUpdate.Result>newBuilder()
              .withStopStrategy(StopStrategies.stopAfterAttempt(3))
              .build());
  exception.expect(OrmException.class);
  exception.expectMessage("failed to update refs/sequences/id: LOCK_FAILURE");
  s.next();
}
项目:gerrit    文件:RepoSequenceTest.java   
@Test
public void increaseToFailAfterRetryerGivesUp() throws Exception {
  AtomicInteger bgCounter = new AtomicInteger(1234);
  RepoSequence s =
      newSequence(
          "id",
          1,
          10,
          () -> writeBlob("id", Integer.toString(bgCounter.getAndAdd(1000))),
          RetryerBuilder.<RefUpdate.Result>newBuilder()
              .withStopStrategy(StopStrategies.stopAfterAttempt(3))
              .build());
  exception.expect(OrmException.class);
  exception.expectMessage("failed to update refs/sequences/id: LOCK_FAILURE");
  s.increaseTo(2);
}
项目:gerrit    文件:RepoSequenceTest.java   
private RepoSequence newSequence(
    String name,
    final int start,
    int batchSize,
    Runnable afterReadRef,
    Retryer<RefUpdate.Result> retryer) {
  return new RepoSequence(
      repoManager,
      GitReferenceUpdated.DISABLED,
      project,
      name,
      () -> start,
      batchSize,
      afterReadRef,
      retryer);
}
项目:gerrit    文件:CommitMsgHookTest.java   
private void setHEAD() throws Exception {
  try (ObjectInserter oi = repository.newObjectInserter()) {
    final CommitBuilder commit = new CommitBuilder();
    commit.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
    commit.setAuthor(author);
    commit.setCommitter(committer);
    commit.setMessage("test\n");
    ObjectId commitId = oi.insert(commit);

    final RefUpdate ref = repository.updateRef(Constants.HEAD);
    ref.setNewObjectId(commitId);
    Result result = ref.forceUpdate();
    assertWithMessage(Constants.HEAD + " did not change: " + ref.getResult())
        .that(result)
        .isAnyOf(Result.FAST_FORWARD, Result.FORCED, Result.NEW, Result.NO_CHANGE);
  }
}
项目:appformer    文件:SimpleRefUpdateCommand.java   
private void forceUpdate(final RefUpdate ru,
                         final ObjectId id) throws java.io.IOException, ConcurrentRefUpdateException {
    final RefUpdate.Result rc = ru.forceUpdate();
    switch (rc) {
        case NEW:
        case FORCED:
        case FAST_FORWARD:
            break;
        case REJECTED:
        case LOCK_FAILURE:
            throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD,
                                                   ru.getRef(),
                                                   rc);
        default:
            throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                                                                 Constants.HEAD,
                                                                 id.toString(),
                                                                 rc));
    }
}
项目:ninja_chic-    文件:TagViewer.java   
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.i(TAG, "onOptionsItemSelected " + item);
    switch (item.getItemId()) {
        case android.R.id.home:
            return homewardsWith(this, manageRepoIntent(repo()));
        case DELETE_ID:
            try {
                RefUpdate update = repo().updateRef(tagRef.getName());
                update.setForceUpdate(true);
                // update.setNewObjectId(head);
                // update.setForceUpdate(force || remote);
                Result result = update.delete();
                Toast.makeText(this, "Tag deletion : " + result.name(), Toast.LENGTH_SHORT).show();
                finish();
            } catch (IOException e) {
                Log.e(TAG, "Couldn't delete " + revTag.getName(), e);
                throw new RuntimeException(e);
            }
            return true;
    }
    return super.onOptionsItemSelected(item);
}
项目:gerrit-gitblit-plugin    文件:JGitUtils.java   
/**
 * Deletes the specified branch ref.
 * 
 * @param repository
 * @param branch
 * @return true if successful
 */
public static boolean deleteBranchRef(Repository repository, String branch) {
    String branchName = branch;
    if (!branchName.startsWith(Constants.R_HEADS)) {
        branchName = Constants.R_HEADS + branch;
    }

    try {
        RefUpdate refUpdate = repository.updateRef(branchName, false);
        refUpdate.setForceUpdate(true);
        RefUpdate.Result result = refUpdate.delete();
        switch (result) {
        case NEW:
        case FORCED:
        case NO_CHANGE:
        case FAST_FORWARD:
            return true;
        default:
            LOGGER.error(MessageFormat.format("{0} failed to delete to {1} returned result {2}", repository.getDirectory().getAbsolutePath(),
                    branchName, result));
        }
    } catch (Throwable t) {
        error(t, repository, "{0} failed to delete {1}", branchName);
    }
    return false;
}
项目:git-as-svn    文件:GitPushEmbedded.java   
@Override
public boolean push(@NotNull Repository repository, @NotNull ObjectId ReceiveId, @NotNull String branch, @NotNull User userInfo) throws SVNException, IOException {
  final RefUpdate refUpdate = repository.updateRef(branch);
  refUpdate.getOldObjectId();
  refUpdate.setNewObjectId(ReceiveId);
  runReceiveHook(repository, refUpdate, preReceive, userInfo);
  runUpdateHook(repository, refUpdate, update, userInfo);
  final RefUpdate.Result result = refUpdate.update();
  switch (result) {
    case REJECTED:
      return false;
    case NEW:
    case FAST_FORWARD:
      runReceiveHook(repository, refUpdate, postReceive, userInfo);
      return true;
    default:
      log.error("Unexpected push error: {}", result);
      throw new SVNException(SVNErrorMessage.create(SVNErrorCode.IO_WRITE_ERROR, result.name()));
  }
}
项目:gitblit    文件:JGitUtils.java   
/**
 * Deletes the specified branch ref.
 *  
 * @param repository
 * @param branch
 * @return true if successful
 */
public static boolean deleteBranchRef(Repository repository, String branch) {
    String branchName = branch;
    if (!branchName.startsWith(Constants.R_HEADS)) {
        branchName = Constants.R_HEADS + branch;
    }

    try {
        RefUpdate refUpdate = repository.updateRef(branchName, false);
        refUpdate.setForceUpdate(true);
        RefUpdate.Result result = refUpdate.delete();
        switch (result) {
        case NEW:
        case FORCED:
        case NO_CHANGE:
        case FAST_FORWARD:
            return true;                
        default:
            LOGGER.error(MessageFormat.format("{0} failed to delete to {1} returned result {2}",
                    repository.getDirectory().getAbsolutePath(), branchName, result));
        }
    } catch (Throwable t) {
        error(t, repository, "{0} failed to delete {1}", branchName);
    }
    return false;
}
项目:git-client-plugin    文件:JGitAPIImpl.java   
private void doCheckoutCleanBranch(String branch, String ref) throws GitException {
    try (Repository repo = getRepository()) {
        RefUpdate refUpdate = repo.updateRef(R_HEADS + branch);
        refUpdate.setNewObjectId(repo.resolve(ref));
        switch (refUpdate.forceUpdate()) {
        case NOT_ATTEMPTED:
        case LOCK_FAILURE:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case IO_FAILURE:
        case RENAMED:
            throw new GitException("Could not update " + branch + " to " + ref);
        }

        doCheckout(branch);
    } catch (IOException e) {
        throw new GitException("Could not checkout " + branch +  " with start point " + ref, e);
    }
}
项目:git-client-plugin    文件:JGitAPIImpl.java   
/** {@inheritDoc} */
   public void ref(String refName) throws GitException, InterruptedException {
refName = refName.replace(' ', '_');
try (Repository repo = getRepository()) {
    RefUpdate refUpdate = repo.updateRef(refName);
    refUpdate.setNewObjectId(repo.getRef(Constants.HEAD).getObjectId());
    switch (refUpdate.forceUpdate()) {
    case NOT_ATTEMPTED:
    case LOCK_FAILURE:
    case REJECTED:
    case REJECTED_CURRENT_BRANCH:
    case IO_FAILURE:
    case RENAMED:
    throw new GitException("Could not update " + refName + " to HEAD");
    }
} catch (IOException e) {
    throw new GitException("Could not update " + refName + " to HEAD", e);
}
   }
项目:git-client-plugin    文件:JGitAPIImpl.java   
/** {@inheritDoc} */
   public void deleteRef(String refName) throws GitException, InterruptedException {
refName = refName.replace(' ', '_');
try (Repository repo = getRepository()) {
    RefUpdate refUpdate = repo.updateRef(refName);
    // Required, even though this is a forced delete.
    refUpdate.setNewObjectId(repo.getRef(Constants.HEAD).getObjectId());
    refUpdate.setForceUpdate(true);
    switch (refUpdate.delete()) {
    case NOT_ATTEMPTED:
    case LOCK_FAILURE:
    case REJECTED:
    case REJECTED_CURRENT_BRANCH:
    case IO_FAILURE:
    case RENAMED:
    throw new GitException("Could not delete " + refName);
    }
} catch (IOException e) {
    throw new GitException("Could not delete " + refName, e);
}
   }
项目:git-client-plugin    文件:JGitAPIImpl.java   
/** {@inheritDoc} */
public void prune(RemoteConfig repository) throws GitException {
    try (Repository gitRepo = getRepository()) {
        String remote = repository.getName();
        String prefix = "refs/remotes/" + remote + "/";

        Set<String> branches = listRemoteBranches(remote);

        for (Ref r : new ArrayList<>(gitRepo.getAllRefs().values())) {
            if (r.getName().startsWith(prefix) && !branches.contains(r.getName())) {
                // delete this ref
                RefUpdate update = gitRepo.updateRef(r.getName());
                update.setRefLogMessage("remote branch pruned", false);
                update.setForceUpdate(true);
                Result res = update.delete();
            }
        }
    } catch (URISyntaxException | IOException e) {
        throw new GitException(e);
    }
}
项目:IRCBlit    文件:JGitUtils.java   
/**
 * Deletes the specified branch ref.
 *  
 * @param repository
 * @param branch
 * @return true if successful
 */
public static boolean deleteBranchRef(Repository repository, String branch) {
    String branchName = branch;
    if (!branchName.startsWith(Constants.R_HEADS)) {
        branchName = Constants.R_HEADS + branch;
    }

    try {
        RefUpdate refUpdate = repository.updateRef(branchName, false);
        refUpdate.setForceUpdate(true);
        RefUpdate.Result result = refUpdate.delete();
        switch (result) {
        case NEW:
        case FORCED:
        case NO_CHANGE:
        case FAST_FORWARD:
            return true;                
        default:
            LOGGER.error(MessageFormat.format("{0} failed to delete to {1} returned result {2}",
                    repository.getDirectory().getAbsolutePath(), branchName, result));
        }
    } catch (Throwable t) {
        error(t, repository, "{0} failed to delete {1}", branchName);
    }
    return false;
}
项目:github-backup-java    文件:CreateOrphanBranchCommand.java   
@Override
public Ref call() throws GitAPIException, RefNotFoundException,
    CheckoutConflictException, InvalidRefNameException,
    RefAlreadyExistsException
{
    this.checkCallable();
    try {
        this.processOptions();
        this.checkoutStartPoint();
        RefUpdate update = this.getRepository().updateRef(Constants.HEAD);
        Result r = update.link(this.getBranchName());
        if (EnumSet.of(Result.NEW, Result.FORCED).contains(r) == false) {
            throw new JGitInternalException(MessageFormat.format(
                JGitText.get().checkoutUnexpectedResult, r.name()));
        }
        this.setCallable(false);
        return this.getRepository().getRef(Constants.HEAD);
    }
    catch (IOException e) {
        throw new JGitInternalException(e.getMessage(), e);
    }
}
项目:incubator-netbeans    文件:GitTransportUpdate.java   
GitTransportUpdate (URIish uri, TrackingRefUpdate update) {
    this.localName = stripRefs(update.getLocalName());
    this.remoteName = stripRefs(update.getRemoteName());
    this.oldObjectId = update.getOldObjectId() == null || ObjectId.zeroId().equals(update.getOldObjectId()) ? null : update.getOldObjectId().getName();
    this.newObjectId = update.getNewObjectId() == null || ObjectId.zeroId().equals(update.getNewObjectId()) ? null : update.getNewObjectId().getName();
    this.result = GitRefUpdateResult.valueOf((update.getResult() == null 
            ? RefUpdate.Result.NOT_ATTEMPTED 
            : update.getResult()).name());
    this.uri = uri.toString();
    this.type = getType(update.getLocalName());
}