Search in sources :

Example 66 with ObjectInserter

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

the class CreateMergePatchSet method applyImpl.

@Override
protected Response<ChangeInfo> applyImpl(BatchUpdate.Factory updateFactory, ChangeResource rsrc, MergePatchSetInput in) throws OrmException, IOException, InvalidChangeOperationException, RestApiException, UpdateException, PermissionBackendException {
    rsrc.permissions().database(db).check(ChangePermission.ADD_PATCH_SET);
    MergeInput merge = in.merge;
    if (merge == null || Strings.isNullOrEmpty(merge.source)) {
        throw new BadRequestException("merge.source must be non-empty");
    }
    ChangeControl ctl = rsrc.getControl();
    PatchSet ps = psUtil.current(db.get(), ctl.getNotes());
    ProjectControl projectControl = ctl.getProjectControl();
    Change change = ctl.getChange();
    Project.NameKey project = change.getProject();
    Branch.NameKey dest = change.getDest();
    try (Repository git = gitManager.openRepository(project);
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        RevWalk rw = new RevWalk(reader)) {
        RevCommit sourceCommit = MergeUtil.resolveCommit(git, rw, merge.source);
        if (!projectControl.canReadCommit(db.get(), git, sourceCommit)) {
            throw new ResourceNotFoundException("cannot find source commit: " + merge.source + " to merge.");
        }
        RevCommit currentPsCommit = rw.parseCommit(ObjectId.fromString(ps.getRevision().get()));
        Timestamp now = TimeUtil.nowTs();
        IdentifiedUser me = user.get().asIdentifiedUser();
        PersonIdent author = me.newCommitterIdent(now, serverTimeZone);
        RevCommit newCommit = createMergeCommit(in, projectControl, dest, git, oi, rw, currentPsCommit, sourceCommit, author, ObjectId.fromString(change.getKey().get().substring(1)));
        PatchSet.Id nextPsId = ChangeUtil.nextPatchSetId(ps.getId());
        PatchSetInserter psInserter = patchSetInserterFactory.create(ctl, nextPsId, newCommit);
        try (BatchUpdate bu = updateFactory.create(db.get(), project, me, now)) {
            bu.setRepository(git, rw, oi);
            bu.addOp(ctl.getId(), psInserter.setMessage("Uploaded patch set " + nextPsId.get() + ".").setDraft(ps.isDraft()).setNotify(NotifyHandling.NONE).setCheckAddPatchSetPermission(false));
            bu.execute();
        }
        ChangeJson json = jsonFactory.create(ListChangesOption.CURRENT_REVISION);
        return Response.ok(json.format(psInserter.getChange()));
    }
}
Also used : MergeInput(com.google.gerrit.extensions.common.MergeInput) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) RevWalk(org.eclipse.jgit.revwalk.RevWalk) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ProjectControl(com.google.gerrit.server.project.ProjectControl) Timestamp(java.sql.Timestamp) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) ChangeControl(com.google.gerrit.server.project.ChangeControl) Branch(com.google.gerrit.reviewdb.client.Branch) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 67 with ObjectInserter

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

the class GetBlame method apply.

@Override
public Response<List<BlameInfo>> apply(FileResource resource) throws RestApiException, OrmException, IOException, InvalidChangeOperationException {
    if (!allowBlame) {
        throw new BadRequestException("blame is disabled");
    }
    Project.NameKey project = resource.getRevision().getChange().getProject();
    try (Repository repository = repoManager.openRepository(project);
        ObjectInserter ins = repository.newObjectInserter();
        ObjectReader reader = ins.newReader();
        RevWalk revWalk = new RevWalk(reader)) {
        String refName = resource.getRevision().getEdit().isPresent() ? resource.getRevision().getEdit().get().getRefName() : resource.getRevision().getPatchSet().getRefName();
        Ref ref = repository.findRef(refName);
        if (ref == null) {
            throw new ResourceNotFoundException("unknown ref " + refName);
        }
        ObjectId objectId = ref.getObjectId();
        RevCommit revCommit = revWalk.parseCommit(objectId);
        RevCommit[] parents = revCommit.getParents();
        String path = resource.getPatchKey().getFileName();
        List<BlameInfo> result;
        if (!base) {
            result = blame(revCommit, path, repository, revWalk);
        } else if (parents.length == 0) {
            throw new ResourceNotFoundException("Initial commit doesn't have base");
        } else if (parents.length == 1) {
            result = blame(parents[0], path, repository, revWalk);
        } else if (parents.length == 2) {
            ObjectId automerge = autoMerger.merge(repository, revWalk, ins, revCommit, mergeStrategy);
            result = blame(automerge, path, repository, revWalk);
        } else {
            throw new ResourceNotFoundException("Cannot generate blame for merge commit with more than 2 parents");
        }
        Response<List<BlameInfo>> r = Response.ok(result);
        if (resource.isCacheable()) {
            r.caching(CacheControl.PRIVATE(7, TimeUnit.DAYS));
        }
        return r;
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BlameInfo(com.google.gerrit.extensions.common.BlameInfo) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ArrayList(java.util.ArrayList) List(java.util.List) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 68 with ObjectInserter

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

the class CommitMsgHookTest method file.

private DirCacheEntry file(final String name) throws IOException {
    try (ObjectInserter oi = repository.newObjectInserter()) {
        final DirCacheEntry e = new DirCacheEntry(name);
        e.setFileMode(FileMode.REGULAR_FILE);
        e.setObjectId(oi.insert(Constants.OBJ_BLOB, Constants.encode(name)));
        oi.flush();
        return e;
    }
}
Also used : DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter)

Example 69 with ObjectInserter

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

the class AccountsUpdate method createUserBranch.

private void createUserBranch(Account account) throws IOException {
    try (Repository repo = repoManager.openRepository(allUsersName);
        ObjectInserter oi = repo.newObjectInserter()) {
        String refName = RefNames.refsUsers(account.getId());
        if (repo.exactRef(refName) != null) {
            throw new IOException(String.format("User branch %s for newly created account %s already exists.", refName, account.getId().get()));
        }
        createUserBranch(repo, oi, committerIdent, authorIdent, account);
    }
}
Also used : Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) IOException(java.io.IOException)

Example 70 with ObjectInserter

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

the class ReceiveCommits method insertChangesAndPatchSets.

private void insertChangesAndPatchSets() {
    ReceiveCommand magicBranchCmd = magicBranch != null ? magicBranch.cmd : null;
    if (magicBranchCmd != null && magicBranchCmd.getResult() != NOT_ATTEMPTED) {
        logWarn(String.format("Skipping change updates on %s because ref update failed: %s %s", project.getName(), magicBranchCmd.getResult(), Strings.nullToEmpty(magicBranchCmd.getMessage())));
        return;
    }
    try (BatchUpdate bu = batchUpdateFactory.create(db, project.getNameKey(), user.materializedCopy(), TimeUtil.nowTs());
        ObjectInserter ins = repo.newObjectInserter();
        ObjectReader reader = ins.newReader();
        RevWalk rw = new RevWalk(reader)) {
        bu.setRepository(repo, rw, ins).updateChangesInParallel();
        bu.setRequestId(receiveId);
        bu.setRefLogMessage("push");
        logDebug("Adding {} replace requests", newChanges.size());
        for (ReplaceRequest replace : replaceByChange.values()) {
            replace.addOps(bu, replaceProgress);
        }
        logDebug("Adding {} create requests", newChanges.size());
        for (CreateRequest create : newChanges) {
            create.addOps(bu);
        }
        logDebug("Adding {} group update requests", newChanges.size());
        updateGroups.forEach(r -> r.addOps(bu));
        logDebug("Adding {} additional ref updates", actualCommands.size());
        actualCommands.forEach(c -> bu.addRepoOnlyOp(new UpdateOneRefOp(c)));
        logDebug("Executing batch");
        try {
            bu.execute();
        } catch (UpdateException e) {
            throw INSERT_EXCEPTION.apply(e);
        }
        if (magicBranchCmd != null) {
            magicBranchCmd.setResult(OK);
        }
        for (ReplaceRequest replace : replaceByChange.values()) {
            String rejectMessage = replace.getRejectMessage();
            if (rejectMessage == null) {
                if (replace.inputCommand.getResult() == NOT_ATTEMPTED) {
                    // Not necessarily the magic branch, so need to set OK on the original value.
                    replace.inputCommand.setResult(OK);
                }
            } else {
                logDebug("Rejecting due to message from ReplaceOp");
                reject(replace.inputCommand, rejectMessage);
            }
        }
    } catch (ResourceConflictException e) {
        addMessage(e.getMessage());
        reject(magicBranchCmd, "conflict");
    } catch (RestApiException | IOException err) {
        logError("Can't insert change/patch set for " + project.getName(), err);
        reject(magicBranchCmd, "internal server error: " + err.getMessage());
    }
    if (magicBranch != null && magicBranch.submit) {
        try {
            submit(newChanges, replaceByChange.values());
        } catch (ResourceConflictException e) {
            addMessage(e.getMessage());
            reject(magicBranchCmd, "conflict");
        } catch (RestApiException | OrmException e) {
            logError("Error submitting changes to " + project.getName(), e);
            reject(magicBranchCmd, "error during submit");
        }
    }
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) OrmException(com.google.gwtorm.server.OrmException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) UpdateException(com.google.gerrit.server.update.UpdateException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException)

Aggregations

ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)108 ObjectId (org.eclipse.jgit.lib.ObjectId)77 RevWalk (org.eclipse.jgit.revwalk.RevWalk)55 Repository (org.eclipse.jgit.lib.Repository)49 RevCommit (org.eclipse.jgit.revwalk.RevCommit)35 IOException (java.io.IOException)31 ObjectReader (org.eclipse.jgit.lib.ObjectReader)31 PersonIdent (org.eclipse.jgit.lib.PersonIdent)30 CommitBuilder (org.eclipse.jgit.lib.CommitBuilder)28 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)24 RefUpdate (org.eclipse.jgit.lib.RefUpdate)24 DirCache (org.eclipse.jgit.dircache.DirCache)15 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)14 Change (com.google.gerrit.entities.Change)13 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)13 Change (com.google.gerrit.reviewdb.client.Change)13 DirCacheEntry (org.eclipse.jgit.dircache.DirCacheEntry)13 Ref (org.eclipse.jgit.lib.Ref)13 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)12 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)10