Search in sources :

Example 11 with IncorrectObjectTypeException

use of org.eclipse.jgit.errors.IncorrectObjectTypeException in project gitiles by GerritCodeReview.

the class ArchiveServlet method getTree.

private ObjectId getTree(GitilesView view, Repository repo, Revision rev) throws IOException {
    try (RevWalk rw = new RevWalk(repo)) {
        RevTree tree = rw.parseTree(rev.getId());
        if (Strings.isNullOrEmpty(view.getPathPart())) {
            return tree;
        }
        TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), view.getPathPart(), tree);
        if (tw == null || tw.getFileMode(0) != FileMode.TREE) {
            return ObjectId.zeroId();
        }
        return tw.getObjectId(0);
    } catch (IncorrectObjectTypeException e) {
        return ObjectId.zeroId();
    }
}
Also used : IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevTree(org.eclipse.jgit.revwalk.RevTree)

Example 12 with IncorrectObjectTypeException

use of org.eclipse.jgit.errors.IncorrectObjectTypeException in project gitblit by gitblit.

the class JGitUtils method searchRevlogs.

/**
	 * Search the commit history for a case-insensitive match to the value.
	 * Search results require a specified SearchType of AUTHOR, COMMITTER, or
	 * COMMIT. Results may be paginated using offset and maxCount. If the
	 * repository does not exist or is empty, an empty list is returned.
	 *
	 * @param repository
	 * @param objectId
	 *            if unspecified, HEAD is assumed.
	 * @param value
	 * @param type
	 *            AUTHOR, COMMITTER, COMMIT
	 * @param offset
	 * @param maxCount
	 *            if < 0, all matches are returned
	 * @return matching list of commits
	 */
public static List<RevCommit> searchRevlogs(Repository repository, String objectId, String value, final com.gitblit.Constants.SearchType type, int offset, int maxCount) {
    List<RevCommit> list = new ArrayList<RevCommit>();
    if (StringUtils.isEmpty(value)) {
        return list;
    }
    if (maxCount == 0) {
        return list;
    }
    if (!hasCommits(repository)) {
        return list;
    }
    final String lcValue = value.toLowerCase();
    try {
        // resolve branch
        ObjectId branchObject;
        if (StringUtils.isEmpty(objectId)) {
            branchObject = getDefaultBranch(repository);
        } else {
            branchObject = repository.resolve(objectId);
        }
        RevWalk rw = new RevWalk(repository);
        rw.setRevFilter(new RevFilter() {

            @Override
            public RevFilter clone() {
                // This is part of JGit design and unrelated to Cloneable.
                return this;
            }

            @Override
            public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException {
                boolean include = false;
                switch(type) {
                    case AUTHOR:
                        include = (commit.getAuthorIdent().getName().toLowerCase().indexOf(lcValue) > -1) || (commit.getAuthorIdent().getEmailAddress().toLowerCase().indexOf(lcValue) > -1);
                        break;
                    case COMMITTER:
                        include = (commit.getCommitterIdent().getName().toLowerCase().indexOf(lcValue) > -1) || (commit.getCommitterIdent().getEmailAddress().toLowerCase().indexOf(lcValue) > -1);
                        break;
                    case COMMIT:
                        include = commit.getFullMessage().toLowerCase().indexOf(lcValue) > -1;
                        break;
                }
                return include;
            }
        });
        rw.markStart(rw.parseCommit(branchObject));
        Iterable<RevCommit> revlog = rw;
        if (offset > 0) {
            int count = 0;
            for (RevCommit rev : revlog) {
                count++;
                if (count > offset) {
                    list.add(rev);
                    if (maxCount > 0 && list.size() == maxCount) {
                        break;
                    }
                }
            }
        } else {
            for (RevCommit rev : revlog) {
                list.add(rev);
                if (maxCount > 0 && list.size() == maxCount) {
                    break;
                }
            }
        }
        rw.dispose();
    } catch (Throwable t) {
        error(t, repository, "{0} failed to {1} search revlogs for {2}", type.name(), value);
    }
    return list;
}
Also used : AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) CommitTimeRevFilter(org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) StopWalkException(org.eclipse.jgit.errors.StopWalkException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 13 with IncorrectObjectTypeException

use of org.eclipse.jgit.errors.IncorrectObjectTypeException in project gerrit by GerritCodeReview.

the class ReceiveCommits method parseRewind.

private void parseRewind(ReceiveCommand cmd) throws PermissionBackendException {
    RevCommit newObject;
    try {
        newObject = rp.getRevWalk().parseCommit(cmd.getNewId());
    } catch (IncorrectObjectTypeException notCommit) {
        newObject = null;
    } catch (IOException err) {
        logError("Invalid object " + cmd.getNewId().name() + " for " + cmd.getRefName() + " forced update", err);
        reject(cmd, "invalid object");
        return;
    }
    logDebug("Rewinding {}", cmd);
    RefControl ctl = projectControl.controlForRef(cmd.getRefName());
    if (newObject != null) {
        validateNewCommits(ctl, cmd);
        if (cmd.getResult() != NOT_ATTEMPTED) {
            return;
        }
    }
    boolean ok;
    try {
        permissions.ref(cmd.getRefName()).check(RefPermission.FORCE_UPDATE);
        ok = true;
    } catch (AuthException err) {
        ok = false;
    }
    if (ok) {
        if (!validRefOperation(cmd)) {
            return;
        }
        actualCommands.add(cmd);
    } else {
        cmd.setResult(REJECTED_NONFASTFORWARD, " need '" + PermissionRule.FORCE_PUSH + "' privilege.");
    }
}
Also used : RefControl(com.google.gerrit.server.project.RefControl) AuthException(com.google.gerrit.extensions.restapi.AuthException) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) IOException(java.io.IOException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 14 with IncorrectObjectTypeException

use of org.eclipse.jgit.errors.IncorrectObjectTypeException in project gerrit by GerritCodeReview.

the class ReceiveCommits method parseMagicBranch.

private void parseMagicBranch(ReceiveCommand cmd) {
    // Permit exactly one new change request per push.
    if (magicBranch != null) {
        reject(cmd, "duplicate request");
        return;
    }
    logDebug("Found magic branch {}", cmd.getRefName());
    magicBranch = new MagicBranchInput(user, cmd, labelTypes, notesMigration);
    magicBranch.reviewer.addAll(reviewersFromCommandLine);
    magicBranch.cc.addAll(ccFromCommandLine);
    String ref;
    CmdLineParser clp = optionParserFactory.create(magicBranch);
    magicBranch.clp = clp;
    try {
        ref = magicBranch.parse(clp, repo, rp.getAdvertisedRefs().keySet(), pushOptions);
    } catch (CmdLineException e) {
        if (!clp.wasHelpRequestedByOption()) {
            logDebug("Invalid branch syntax");
            reject(cmd, e.getMessage());
            return;
        }
        // never happen
        ref = null;
    }
    if (clp.wasHelpRequestedByOption()) {
        StringWriter w = new StringWriter();
        w.write("\nHelp for refs/for/branch:\n\n");
        clp.printUsage(w, null);
        addMessage(w.toString());
        reject(cmd, "see help");
        return;
    }
    if (projectControl.getProjectState().isAllUsers() && RefNames.REFS_USERS_SELF.equals(ref)) {
        logDebug("Handling {}", RefNames.REFS_USERS_SELF);
        ref = RefNames.refsUsers(user.getAccountId());
    }
    if (!rp.getAdvertisedRefs().containsKey(ref) && !ref.equals(readHEAD(repo))) {
        logDebug("Ref {} not found", ref);
        if (ref.startsWith(Constants.R_HEADS)) {
            String n = ref.substring(Constants.R_HEADS.length());
            reject(cmd, "branch " + n + " not found");
        } else {
            reject(cmd, ref + " not found");
        }
        return;
    }
    magicBranch.dest = new Branch.NameKey(project.getNameKey(), ref);
    magicBranch.ctl = projectControl.controlForRef(ref);
    if (projectControl.getProject().getState() != com.google.gerrit.extensions.client.ProjectState.ACTIVE) {
        reject(cmd, "project is read only");
        return;
    }
    if (magicBranch.draft) {
        if (!receiveConfig.allowDrafts) {
            errors.put(Error.CODE_REVIEW, ref);
            reject(cmd, "draft workflow is disabled");
            return;
        } else if (projectControl.controlForRef(MagicBranch.NEW_DRAFT_CHANGE + ref).isBlocked(Permission.PUSH)) {
            errors.put(Error.CODE_REVIEW, ref);
            reject(cmd, "cannot upload drafts");
            return;
        }
    }
    if (!magicBranch.ctl.canUpload()) {
        errors.put(Error.CODE_REVIEW, ref);
        reject(cmd, "cannot upload review");
        return;
    }
    if (magicBranch.isPrivate && magicBranch.removePrivate) {
        reject(cmd, "the options 'private' and 'remove-private' are mutually exclusive");
        return;
    }
    if (magicBranch.workInProgress && magicBranch.ready) {
        reject(cmd, "the options 'wip' and 'ready' are mutually exclusive");
        return;
    }
    if (magicBranch.publishComments && magicBranch.noPublishComments) {
        reject(cmd, "the options 'publish-comments' and 'no-publish-comments' are mutually exclusive");
        return;
    }
    if (magicBranch.draft && magicBranch.submit) {
        reject(cmd, "cannot submit draft");
        return;
    }
    if (magicBranch.submit && !projectControl.controlForRef(MagicBranch.NEW_CHANGE + ref).canSubmit(true)) {
        reject(cmd, "submit not allowed");
        return;
    }
    RevWalk walk = rp.getRevWalk();
    RevCommit tip;
    try {
        tip = walk.parseCommit(magicBranch.cmd.getNewId());
        logDebug("Tip of push: {}", tip.name());
    } catch (IOException ex) {
        magicBranch.cmd.setResult(REJECTED_MISSING_OBJECT);
        logError("Invalid pack upload; one or more objects weren't sent", ex);
        return;
    }
    String destBranch = magicBranch.dest.get();
    try {
        if (magicBranch.merged) {
            if (magicBranch.draft) {
                reject(cmd, "cannot be draft & merged");
                return;
            }
            if (magicBranch.base != null) {
                reject(cmd, "cannot use merged with base");
                return;
            }
            RevCommit branchTip = readBranchTip(cmd, magicBranch.dest);
            if (branchTip == null) {
                // readBranchTip already rejected cmd.
                return;
            }
            if (!walk.isMergedInto(tip, branchTip)) {
                reject(cmd, "not merged into branch");
                return;
            }
        }
        // if %base or %merged was specified, ignore newChangeForAllNotInTarget.
        if (tip.getParentCount() > 1 || magicBranch.base != null || magicBranch.merged || tip.getParentCount() == 0) {
            logDebug("Forcing newChangeForAllNotInTarget = false");
            newChangeForAllNotInTarget = false;
        }
        if (magicBranch.base != null) {
            logDebug("Handling %base: {}", magicBranch.base);
            magicBranch.baseCommit = Lists.newArrayListWithCapacity(magicBranch.base.size());
            for (ObjectId id : magicBranch.base) {
                try {
                    magicBranch.baseCommit.add(walk.parseCommit(id));
                } catch (IncorrectObjectTypeException notCommit) {
                    reject(cmd, "base must be a commit");
                    return;
                } catch (MissingObjectException e) {
                    reject(cmd, "base not found");
                    return;
                } catch (IOException e) {
                    logWarn(String.format("Project %s cannot read %s", project.getName(), id.name()), e);
                    reject(cmd, "internal server error");
                    return;
                }
            }
        } else if (newChangeForAllNotInTarget) {
            RevCommit branchTip = readBranchTip(cmd, magicBranch.dest);
            if (branchTip == null) {
                // readBranchTip already rejected cmd.
                return;
            }
            magicBranch.baseCommit = Collections.singletonList(branchTip);
            logDebug("Set baseCommit = {}", magicBranch.baseCommit.get(0).name());
        }
    } catch (IOException ex) {
        logWarn(String.format("Error walking to %s in project %s", destBranch, project.getName()), ex);
        reject(cmd, "internal server error");
        return;
    }
    //
    try {
        Ref targetRef = rp.getAdvertisedRefs().get(magicBranch.ctl.getRefName());
        if (targetRef == null || targetRef.getObjectId() == null) {
            // The destination branch does not yet exist. Assume the
            // history being sent for review will start it and thus
            // is "connected" to the branch.
            logDebug("Branch is unborn");
            return;
        }
        RevCommit h = walk.parseCommit(targetRef.getObjectId());
        logDebug("Current branch tip: {}", h.name());
        RevFilter oldRevFilter = walk.getRevFilter();
        try {
            walk.reset();
            walk.setRevFilter(RevFilter.MERGE_BASE);
            walk.markStart(tip);
            walk.markStart(h);
            if (walk.next() == null) {
                reject(magicBranch.cmd, "no common ancestry");
            }
        } finally {
            walk.reset();
            walk.setRevFilter(oldRevFilter);
        }
    } catch (IOException e) {
        magicBranch.cmd.setResult(REJECTED_MISSING_OBJECT);
        logError("Invalid pack upload; one or more objects weren't sent", e);
    }
}
Also used : CmdLineParser(com.google.gerrit.util.cli.CmdLineParser) ObjectId(org.eclipse.jgit.lib.ObjectId) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) Ref(org.eclipse.jgit.lib.Ref) StringWriter(java.io.StringWriter) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) MagicBranch(com.google.gerrit.server.util.MagicBranch) Branch(com.google.gerrit.reviewdb.client.Branch) CmdLineException(org.kohsuke.args4j.CmdLineException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 15 with IncorrectObjectTypeException

use of org.eclipse.jgit.errors.IncorrectObjectTypeException in project gerrit by GerritCodeReview.

the class RefUtil method verifyConnected.

public static RevWalk verifyConnected(Repository repo, ObjectId revid) throws InvalidRevisionException {
    try {
        ObjectWalk rw = new ObjectWalk(repo);
        try {
            rw.markStart(rw.parseCommit(revid));
        } catch (IncorrectObjectTypeException err) {
            throw new InvalidRevisionException();
        }
        RefDatabase refDb = repo.getRefDatabase();
        Iterable<Ref> refs = Iterables.concat(refDb.getRefs(Constants.R_HEADS).values(), refDb.getRefs(Constants.R_TAGS).values());
        Ref rc = refDb.exactRef(RefNames.REFS_CONFIG);
        if (rc != null) {
            refs = Iterables.concat(refs, Collections.singleton(rc));
        }
        for (Ref r : refs) {
            try {
                rw.markUninteresting(rw.parseAny(r.getObjectId()));
            } catch (MissingObjectException err) {
                continue;
            }
        }
        rw.checkConnectivity();
        return rw;
    } catch (IncorrectObjectTypeException | MissingObjectException err) {
        throw new InvalidRevisionException();
    } catch (IOException err) {
        log.error("Repository \"" + repo.getDirectory() + "\" may be corrupt; suggest running git fsck", err);
        throw new InvalidRevisionException();
    }
}
Also used : ObjectWalk(org.eclipse.jgit.revwalk.ObjectWalk) Ref(org.eclipse.jgit.lib.Ref) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) IOException(java.io.IOException) RefDatabase(org.eclipse.jgit.lib.RefDatabase) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException)

Aggregations

IncorrectObjectTypeException (org.eclipse.jgit.errors.IncorrectObjectTypeException)23 MissingObjectException (org.eclipse.jgit.errors.MissingObjectException)13 RevWalk (org.eclipse.jgit.revwalk.RevWalk)13 IOException (java.io.IOException)10 Repository (org.eclipse.jgit.lib.Repository)10 ObjectId (org.eclipse.jgit.lib.ObjectId)9 RevCommit (org.eclipse.jgit.revwalk.RevCommit)9 Ref (org.eclipse.jgit.lib.Ref)4 RevTree (org.eclipse.jgit.revwalk.RevTree)4 Branch (com.google.gerrit.reviewdb.client.Branch)3 MoreObjects.firstNonNull (com.google.common.base.MoreObjects.firstNonNull)2 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)2 AuthException (com.google.gerrit.extensions.restapi.AuthException)2 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)2 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)2 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)2 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)2 Project (com.google.gerrit.reviewdb.client.Project)2 Map (java.util.Map)2 AnyObjectId (org.eclipse.jgit.lib.AnyObjectId)2