Search in sources :

Example 6 with RefUpdate

use of org.eclipse.jgit.lib.RefUpdate in project gerrit by GerritCodeReview.

the class CreateBranch method apply.

@Override
public BranchInfo apply(ProjectResource rsrc, BranchInput input) throws BadRequestException, AuthException, ResourceConflictException, IOException {
    if (input == null) {
        input = new BranchInput();
    }
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision == null) {
        input.revision = Constants.HEAD;
    }
    while (ref.startsWith("/")) {
        ref = ref.substring(1);
    }
    ref = RefNames.fullName(ref);
    if (!Repository.isValidRefName(ref)) {
        throw new BadRequestException("invalid branch name \"" + ref + "\"");
    }
    if (MagicBranch.isMagicBranch(ref)) {
        throw new BadRequestException("not allowed to create branches under \"" + MagicBranch.getMagicRefNamePrefix(ref) + "\"");
    }
    final Branch.NameKey name = new Branch.NameKey(rsrc.getNameKey(), ref);
    final RefControl refControl = rsrc.getControl().controlForRef(name);
    try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
        ObjectId revid = RefUtil.parseBaseRevision(repo, rsrc.getNameKey(), input.revision);
        RevWalk rw = RefUtil.verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);
        if (ref.startsWith(Constants.R_HEADS)) {
            //
            try {
                object = rw.parseCommit(object);
            } catch (IncorrectObjectTypeException notCommit) {
                throw new BadRequestException("\"" + input.revision + "\" not a commit");
            }
        }
        if (!refControl.canCreate(db.get(), repo, object)) {
            throw new AuthException("Cannot create \"" + ref + "\"");
        }
        try {
            final RefUpdate u = repo.updateRef(ref);
            u.setExpectedOldObjectId(ObjectId.zeroId());
            u.setNewObjectId(object.copy());
            u.setRefLogIdent(identifiedUser.get().newRefLogIdent());
            u.setRefLogMessage("created via REST from " + input.revision, false);
            refCreationValidator.validateRefOperation(rsrc.getName(), identifiedUser.get(), u);
            final RefUpdate.Result result = u.update(rw);
            switch(result) {
                case FAST_FORWARD:
                case NEW:
                case NO_CHANGE:
                    referenceUpdated.fire(name.getParentKey(), u, ReceiveCommand.Type.CREATE, identifiedUser.get().getAccount());
                    break;
                case LOCK_FAILURE:
                    if (repo.getRefDatabase().exactRef(ref) != null) {
                        throw new ResourceConflictException("branch \"" + ref + "\" already exists");
                    }
                    String refPrefix = RefUtil.getRefPrefix(ref);
                    while (!Constants.R_HEADS.equals(refPrefix)) {
                        if (repo.getRefDatabase().exactRef(refPrefix) != null) {
                            throw new ResourceConflictException("Cannot create branch \"" + ref + "\" since it conflicts with branch \"" + refPrefix + "\".");
                        }
                        refPrefix = RefUtil.getRefPrefix(refPrefix);
                    }
                //$FALL-THROUGH$
                case FORCED:
                case IO_FAILURE:
                case NOT_ATTEMPTED:
                case REJECTED:
                case REJECTED_CURRENT_BRANCH:
                case RENAMED:
                default:
                    {
                        throw new IOException(result.name());
                    }
            }
            BranchInfo info = new BranchInfo();
            info.ref = ref;
            info.revision = revid.getName();
            info.canDelete = permissionBackend.user(identifiedUser).ref(name).testOrFalse(RefPermission.DELETE) ? true : null;
            return info;
        } catch (IOException err) {
            log.error("Cannot create branch \"" + name + "\"", err);
            throw err;
        }
    } catch (RefUtil.InvalidRevisionException e) {
        throw new BadRequestException("invalid revision \"" + input.revision + "\"");
    }
}
Also used : BranchInfo(com.google.gerrit.extensions.api.projects.BranchInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) RevObject(org.eclipse.jgit.revwalk.RevObject) AuthException(com.google.gerrit.extensions.restapi.AuthException) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MagicBranch(com.google.gerrit.server.util.MagicBranch) Branch(com.google.gerrit.reviewdb.client.Branch) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) BranchInput(com.google.gerrit.extensions.api.projects.BranchInput) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 7 with RefUpdate

use of org.eclipse.jgit.lib.RefUpdate in project gerrit by GerritCodeReview.

the class CreateProject method createEmptyCommits.

private void createEmptyCommits(Repository repo, Project.NameKey project, List<String> refs) throws IOException {
    try (ObjectInserter oi = repo.newObjectInserter()) {
        CommitBuilder cb = new CommitBuilder();
        cb.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
        cb.setAuthor(metaDataUpdateFactory.getUserPersonIdent());
        cb.setCommitter(serverIdent);
        cb.setMessage("Initial empty repository\n");
        ObjectId id = oi.insert(cb);
        oi.flush();
        for (String ref : refs) {
            RefUpdate ru = repo.updateRef(ref);
            ru.setNewObjectId(id);
            Result result = ru.update();
            switch(result) {
                case NEW:
                    referenceUpdated.fire(project, ru, ReceiveCommand.Type.CREATE, identifiedUser.get().getAccount());
                    break;
                case FAST_FORWARD:
                case FORCED:
                case IO_FAILURE:
                case LOCK_FAILURE:
                case NOT_ATTEMPTED:
                case NO_CHANGE:
                case REJECTED:
                case REJECTED_CURRENT_BRANCH:
                case RENAMED:
                default:
                    {
                        throw new IOException(String.format("Failed to create ref \"%s\": %s", ref, result.name()));
                    }
            }
        }
    } catch (IOException e) {
        log.error("Cannot create empty commit for " + project.get(), e);
        throw e;
    }
}
Also used : ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ObjectId(org.eclipse.jgit.lib.ObjectId) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) IOException(java.io.IOException) RefUpdate(org.eclipse.jgit.lib.RefUpdate) Result(org.eclipse.jgit.lib.RefUpdate.Result)

Example 8 with RefUpdate

use of org.eclipse.jgit.lib.RefUpdate in project gerrit by GerritCodeReview.

the class CommitMsgHookTest method setHEAD.

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();
        assert_().withFailureMessage(Constants.HEAD + " did not change: " + ref.getResult()).that(result).isAnyOf(Result.FAST_FORWARD, Result.FORCED, Result.NEW, Result.NO_CHANGE);
    }
}
Also used : ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ObjectId(org.eclipse.jgit.lib.ObjectId) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) RefUpdate(org.eclipse.jgit.lib.RefUpdate) Result(org.eclipse.jgit.lib.RefUpdate.Result)

Example 9 with RefUpdate

use of org.eclipse.jgit.lib.RefUpdate in project gerrit by GerritCodeReview.

the class ChangeEditModifier method updateReference.

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("update failed: " + ru);
        }
    }
}
Also used : IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RefUpdate(org.eclipse.jgit.lib.RefUpdate) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate)

Example 10 with RefUpdate

use of org.eclipse.jgit.lib.RefUpdate in project gerrit by GerritCodeReview.

the class AutoMerger method commit.

private RevCommit commit(Repository repo, RevWalk rw, @Nullable InMemoryInserter tmpIns, ObjectInserter ins, String refName, ObjectId tree, RevCommit merge) throws IOException {
    rw.parseHeaders(merge);
    // For maximum stability, choose a single ident using the committer time of
    // the input commit, using the server name and timezone.
    PersonIdent ident = new PersonIdent(gerritIdent, merge.getCommitterIdent().getWhen(), gerritIdent.getTimeZone());
    CommitBuilder cb = new CommitBuilder();
    cb.setAuthor(ident);
    cb.setCommitter(ident);
    cb.setTreeId(tree);
    cb.setMessage("Auto-merge of " + merge.name() + '\n');
    for (RevCommit p : merge.getParents()) {
        cb.addParentId(p);
    }
    if (!save) {
        checkArgument(tmpIns != null);
        try (ObjectReader tmpReader = tmpIns.newReader();
            RevWalk tmpRw = new RevWalk(tmpReader)) {
            return tmpRw.parseCommit(tmpIns.insert(cb));
        }
    }
    checkArgument(tmpIns == null);
    checkArgument(!(ins instanceof InMemoryInserter));
    ObjectId commitId = ins.insert(cb);
    ins.flush();
    RefUpdate ru = repo.updateRef(refName);
    ru.setNewObjectId(commitId);
    ru.disableRefLog();
    ru.forceUpdate();
    return rw.parseCommit(commitId);
}
Also used : PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) ObjectId(org.eclipse.jgit.lib.ObjectId) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) ObjectReader(org.eclipse.jgit.lib.ObjectReader) InMemoryInserter(com.google.gerrit.server.git.InMemoryInserter) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Aggregations

RefUpdate (org.eclipse.jgit.lib.RefUpdate)110 Repository (org.eclipse.jgit.lib.Repository)51 ObjectId (org.eclipse.jgit.lib.ObjectId)45 IOException (java.io.IOException)34 Test (org.junit.Test)32 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)27 TestRepository (org.eclipse.jgit.junit.TestRepository)26 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)24 RevWalk (org.eclipse.jgit.revwalk.RevWalk)23 Result (org.eclipse.jgit.lib.RefUpdate.Result)22 RevCommit (org.eclipse.jgit.revwalk.RevCommit)20 CommitBuilder (org.eclipse.jgit.lib.CommitBuilder)18 Ref (org.eclipse.jgit.lib.Ref)17 RemoteRefUpdate (org.eclipse.jgit.transport.RemoteRefUpdate)17 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)15 BatchRefUpdate (org.eclipse.jgit.lib.BatchRefUpdate)14 InMemoryRepository (org.eclipse.jgit.internal.storage.dfs.InMemoryRepository)12 LockFailureException (com.google.gerrit.git.LockFailureException)10 PersonIdent (org.eclipse.jgit.lib.PersonIdent)9 DirCache (org.eclipse.jgit.dircache.DirCache)8