Search in sources :

Example 21 with RevWalk

use of org.eclipse.jgit.revwalk.RevWalk 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 22 with RevWalk

use of org.eclipse.jgit.revwalk.RevWalk in project gerrit by GerritCodeReview.

the class RefControl method isMergedIntoBranchOrTag.

private boolean isMergedIntoBranchOrTag(ReviewDb db, Repository repo, RevCommit commit) {
    try (RevWalk rw = new RevWalk(repo)) {
        List<Ref> refs = new ArrayList<>(repo.getRefDatabase().getRefs(Constants.R_HEADS).values());
        refs.addAll(repo.getRefDatabase().getRefs(Constants.R_TAGS).values());
        return projectControl.isMergedIntoVisibleRef(repo, db, rw, commit, refs);
    } catch (IOException e) {
        String msg = String.format("Cannot verify permissions to commit object %s in repository %s", commit.name(), projectControl.getProject().getNameKey());
        log.error(msg, e);
    }
    return false;
}
Also used : ForRef(com.google.gerrit.server.permissions.PermissionBackend.ForRef) Ref(org.eclipse.jgit.lib.Ref) ArrayList(java.util.ArrayList) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk)

Example 23 with RevWalk

use of org.eclipse.jgit.revwalk.RevWalk 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 24 with RevWalk

use of org.eclipse.jgit.revwalk.RevWalk in project gerrit by GerritCodeReview.

the class ChangeRebuilderImpl method getHashtagsEvents.

private List<HashtagsEvent> getHashtagsEvents(Change change, NoteDbUpdateManager manager) throws IOException {
    String refName = changeMetaRef(change.getId());
    Optional<ObjectId> old = manager.getChangeRepo().getObjectId(refName);
    if (!old.isPresent()) {
        return Collections.emptyList();
    }
    RevWalk rw = manager.getChangeRepo().rw;
    List<HashtagsEvent> events = new ArrayList<>();
    rw.reset();
    rw.markStart(rw.parseCommit(old.get()));
    for (RevCommit commit : rw) {
        Account.Id authorId;
        try {
            authorId = changeNoteUtil.parseIdent(commit.getAuthorIdent(), change.getId());
        } catch (ConfigInvalidException e) {
            // Corrupt data, no valid hashtags in this commit.
            continue;
        }
        PatchSet.Id psId = parsePatchSetId(change, commit);
        Set<String> hashtags = parseHashtags(commit);
        if (authorId == null || psId == null || hashtags == null) {
            continue;
        }
        Timestamp commitTime = new Timestamp(commit.getCommitterIdent().getWhen().getTime());
        events.add(new HashtagsEvent(psId, authorId, commitTime, hashtags, change.getCreatedOn()));
    }
    return events;
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Timestamp(java.sql.Timestamp) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 25 with RevWalk

use of org.eclipse.jgit.revwalk.RevWalk 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

RevWalk (org.eclipse.jgit.revwalk.RevWalk)487 RevCommit (org.eclipse.jgit.revwalk.RevCommit)292 Repository (org.eclipse.jgit.lib.Repository)205 ObjectId (org.eclipse.jgit.lib.ObjectId)199 IOException (java.io.IOException)160 Ref (org.eclipse.jgit.lib.Ref)124 Test (org.junit.Test)76 ObjectReader (org.eclipse.jgit.lib.ObjectReader)69 ArrayList (java.util.ArrayList)61 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)55 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)47 File (java.io.File)39 RevTree (org.eclipse.jgit.revwalk.RevTree)39 TestRepository (org.eclipse.jgit.junit.TestRepository)35 Git (org.eclipse.jgit.api.Git)32 PersonIdent (org.eclipse.jgit.lib.PersonIdent)32 RevObject (org.eclipse.jgit.revwalk.RevObject)32 InMemoryRepository (org.eclipse.jgit.internal.storage.dfs.InMemoryRepository)31 HashMap (java.util.HashMap)30 Map (java.util.Map)27