Example usage for org.eclipse.jgit.lib Constants R_HEADS

List of usage examples for org.eclipse.jgit.lib Constants R_HEADS

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants R_HEADS.

Prototype

String R_HEADS

To view the source code for org.eclipse.jgit.lib Constants R_HEADS.

Click Source Link

Document

Prefix for branch refs

Usage

From source file:com.google.gerrit.httpd.rpc.project.AddRefRight.java

License:Apache License

@Override
public ProjectDetail call() throws NoSuchProjectException, OrmException, NoSuchGroupException,
        InvalidNameException, NoSuchRefException {
    final ProjectControl projectControl = projectControlFactory.controlFor(projectName);

    final ApprovalType at = approvalTypes.getApprovalType(categoryId);
    if (at == null || at.getValue(min) == null || at.getValue(max) == null) {
        throw new IllegalArgumentException("Invalid category " + categoryId + " or range " + min + ".." + max);
    }/* w  w  w .j a  v a2  s.  c  o  m*/

    String refPattern = this.refPattern;
    if (refPattern == null || refPattern.isEmpty()) {
        if (categoryId.equals(ApprovalCategory.SUBMIT) || categoryId.equals(ApprovalCategory.PUSH_HEAD)) {
            // Explicitly related to a branch head.
            refPattern = Constants.R_HEADS + "*";

        } else if (!at.getCategory().isAction()) {
            // Non actions are approval votes on a change, assume these apply
            // to branch heads only.
            refPattern = Constants.R_HEADS + "*";

        } else if (categoryId.equals(ApprovalCategory.PUSH_TAG)) {
            // Explicitly related to the tag namespace.
            refPattern = Constants.R_TAGS + "*";

        } else if (categoryId.equals(ApprovalCategory.READ) || categoryId.equals(ApprovalCategory.OWN)) {
            // Currently these are project-wide rights, so apply that way.
            refPattern = RefRight.ALL;

        } else {
            // Assume project wide for the default.
            refPattern = RefRight.ALL;
        }
    }

    boolean exclusive = refPattern.startsWith("-");
    if (exclusive) {
        refPattern = refPattern.substring(1);
    }

    while (refPattern.startsWith("/")) {
        refPattern = refPattern.substring(1);
    }

    if (refPattern.startsWith(RefRight.REGEX_PREFIX)) {
        String example = RefControl.shortestExample(refPattern);

        if (!example.startsWith(Constants.R_REFS)) {
            refPattern = RefRight.REGEX_PREFIX + Constants.R_HEADS
                    + refPattern.substring(RefRight.REGEX_PREFIX.length());
            example = RefControl.shortestExample(refPattern);
        }

        if (!Repository.isValidRefName(example)) {
            throw new InvalidNameException();
        }

    } else {
        if (!refPattern.startsWith(Constants.R_REFS)) {
            refPattern = Constants.R_HEADS + refPattern;
        }

        if (refPattern.endsWith("/*")) {
            final String prefix = refPattern.substring(0, refPattern.length() - 2);
            if (!"refs".equals(prefix) && !Repository.isValidRefName(prefix)) {
                throw new InvalidNameException();
            }
        } else {
            if (!Repository.isValidRefName(refPattern)) {
                throw new InvalidNameException();
            }
        }
    }

    if (!projectControl.controlForRef(refPattern).isOwner()) {
        throw new NoSuchRefException(refPattern);
    }

    if (exclusive) {
        refPattern = "-" + refPattern;
    }

    final AccountGroup group = groupCache.get(groupName);
    if (group == null) {
        throw new NoSuchGroupException(groupName);
    }
    final RefRight.Key key = new RefRight.Key(projectName, new RefRight.RefPattern(refPattern), categoryId,
            group.getId());
    RefRight rr = db.refRights().get(key);
    if (rr == null) {
        rr = new RefRight(key);
        rr.setMinValue(min);
        rr.setMaxValue(max);
        db.refRights().insert(Collections.singleton(rr));
    } else {
        rr.setMinValue(min);
        rr.setMaxValue(max);
        db.refRights().update(Collections.singleton(rr));
    }
    projectCache.evictAll();
    return projectDetailFactory.create(projectName).call();
}

From source file:com.google.gerrit.httpd.rpc.project.ListBranches.java

License:Apache License

@Override
public ListBranchesResult call() throws NoSuchProjectException {
    final ProjectControl pctl = projectControlFactory.validateFor( //
            projectName, //
            ProjectControl.OWNER | ProjectControl.VISIBLE);

    final List<Branch> branches = new ArrayList<Branch>();
    Branch headBranch = null;/*from   w w w  .j  av  a2 s . c o  m*/
    final Set<String> targets = new HashSet<String>();

    final Repository db;
    try {
        db = repoManager.openRepository(projectName);
    } catch (RepositoryNotFoundException noGitRepository) {
        return new ListBranchesResult(branches, false, true);
    }
    try {
        final Map<String, Ref> all = db.getAllRefs();

        if (!all.containsKey(Constants.HEAD)) {
            // The branch pointed to by HEAD doesn't exist yet, so getAllRefs
            // filtered it out. If we ask for it individually we can find the
            // underlying target and put it into the map anyway.
            //
            try {
                Ref head = db.getRef(Constants.HEAD);
                if (head != null) {
                    all.put(Constants.HEAD, head);
                }
            } catch (IOException e) {
                // Ignore the failure reading HEAD.
            }
        }

        for (final Ref ref : all.values()) {
            if (ref.isSymbolic()) {
                targets.add(ref.getTarget().getName());
            }
        }

        for (final Ref ref : all.values()) {
            if (ref.isSymbolic()) {
                // A symbolic reference to another branch, instead of
                // showing the resolved value, show the name it references.
                //
                String target = ref.getTarget().getName();
                RefControl targetRefControl = pctl.controlForRef(target);
                if (!targetRefControl.isVisible()) {
                    continue;
                }
                if (target.startsWith(Constants.R_HEADS)) {
                    target = target.substring(Constants.R_HEADS.length());
                }

                Branch b = createBranch(ref.getName());
                b.setRevision(new RevId(target));

                if (Constants.HEAD.equals(ref.getName())) {
                    b.setCanDelete(false);
                    headBranch = b;
                } else {
                    b.setCanDelete(targetRefControl.canDelete());
                    branches.add(b);
                }
                continue;
            }

            RefControl refControl = pctl.controlForRef(ref.getName());

            if (ref.getName().startsWith(Constants.R_HEADS) && refControl.isVisible()) {
                final Branch b = createBranch(ref.getName());
                if (ref.getObjectId() != null) {
                    b.setRevision(new RevId(ref.getObjectId().name()));
                }

                b.setCanDelete(!targets.contains(ref.getName()) && refControl.canDelete());

                branches.add(b);
            }
        }
    } finally {
        db.close();
    }
    Collections.sort(branches, new Comparator<Branch>() {
        @Override
        public int compare(final Branch a, final Branch b) {
            return a.getName().compareTo(b.getName());
        }
    });
    if (headBranch != null) {
        branches.add(0, headBranch);
    }
    return new ListBranchesResult(branches, pctl.canAddRefs(), false);
}

From source file:com.google.gerrit.server.change.ChangeTriplet.java

License:Apache License

/**
 * Parse a triplet out of a string.//from   w w w .ja v  a 2s .com
 *
 * @param triplet string of the form "project~branch~id".
 * @return the triplet if the input string has the proper format, or absent if
 *     not.
 */
public static Optional<ChangeTriplet> parse(String triplet) {
    int t2 = triplet.lastIndexOf('~');
    int t1 = triplet.lastIndexOf('~', t2 - 1);
    if (t1 < 0 || t2 < 0) {
        return Optional.absent();
    }

    String project = Url.decode(triplet.substring(0, t1));
    String branch = Url.decode(triplet.substring(t1 + 1, t2));
    String changeId = Url.decode(triplet.substring(t2 + 1));

    if (!branch.startsWith(Constants.R_REFS)) {
        branch = Constants.R_HEADS + branch;
    }

    ChangeTriplet result = new AutoValue_ChangeTriplet(new Branch.NameKey(new Project.NameKey(project), branch),
            new Change.Key(changeId));
    return Optional.of(result);
}

From source file:com.google.gerrit.server.change.IncludedInResolver.java

License:Apache License

private IncludedInDetail resolve() throws IOException {
    RefDatabase refDb = repo.getRefDatabase();
    Collection<Ref> tags = refDb.getRefs(Constants.R_TAGS).values();
    Collection<Ref> branches = refDb.getRefs(Constants.R_HEADS).values();
    List<Ref> allTagsAndBranches = Lists.newArrayListWithCapacity(tags.size() + branches.size());
    allTagsAndBranches.addAll(tags);//from  w w  w  . j a  v  a 2s .c  o m
    allTagsAndBranches.addAll(branches);
    parseCommits(allTagsAndBranches);
    Set<String> allMatchingTagsAndBranches = includedIn(tipsByCommitTime, 0);

    IncludedInDetail detail = new IncludedInDetail();
    detail.setBranches(getMatchingRefNames(allMatchingTagsAndBranches, branches));
    detail.setTags(getMatchingRefNames(allMatchingTagsAndBranches, tags));

    return detail;
}

From source file:com.google.gerrit.server.change.MergeabilityChecker.java

License:Apache License

@Override
public void onGitReferenceUpdated(GitReferenceUpdatedListener.Event event) {
    String ref = event.getRefName();
    if (ref.startsWith(Constants.R_HEADS) || ref.equals(RefNames.REFS_CONFIG)) {
        Branch.NameKey branch = new Branch.NameKey(new Project.NameKey(event.getProjectName()), ref);
        newCheck().addBranch(branch).runAsync();
    }//from  w w w .j  a  va2s  . c om
    if (ref.equals(RefNames.REFS_CONFIG)) {
        Project.NameKey p = new Project.NameKey(event.getProjectName());
        try {
            ProjectConfig oldCfg = parseConfig(p, event.getOldObjectId());
            ProjectConfig newCfg = parseConfig(p, event.getNewObjectId());
            if (recheckMerges(oldCfg, newCfg)) {
                newCheck().addProject(p).force().runAsync();
            }
        } catch (ConfigInvalidException | IOException e) {
            String msg = "Failed to update mergeability flags for project " + p.get() + " on update of "
                    + RefNames.REFS_CONFIG;
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    }
}

From source file:com.google.gerrit.server.change.Mergeable.java

License:Apache License

@Override
public MergeableInfo apply(RevisionResource resource)
        throws AuthException, ResourceConflictException, BadRequestException, OrmException, IOException {
    Change change = resource.getChange();
    PatchSet ps = resource.getPatchSet();
    MergeableInfo result = new MergeableInfo();

    if (!change.getStatus().isOpen()) {
        throw new ResourceConflictException("change is " + Submit.status(change));
    } else if (!ps.getId().equals(change.currentPatchSetId())) {
        // Only the current revision is mergeable. Others always fail.
        return result;
    }/*ww  w  .  j  ava 2  s .c  om*/

    ChangeData cd = changeDataFactory.create(db.get(), resource.getControl());
    SubmitTypeRecord rec = new SubmitRuleEvaluator(cd).setPatchSet(ps).getSubmitType();
    if (rec.status != SubmitTypeRecord.Status.OK) {
        throw new OrmException("Submit type rule failed: " + rec);
    }
    result.submitType = rec.type;

    try (Repository git = gitManager.openRepository(change.getProject())) {
        ObjectId commit = toId(ps);
        if (commit == null) {
            result.mergeable = false;
            return result;
        }

        Ref ref = git.getRefDatabase().exactRef(change.getDest().get());
        ProjectState projectState = projectCache.get(change.getProject());
        String strategy = mergeUtilFactory.create(projectState).mergeStrategyName();
        Boolean old = cache.getIfPresent(commit, ref, result.submitType, strategy);

        if (old == null) {
            result.mergeable = refresh(change, commit, ref, result.submitType, strategy, git, old);
        } else {
            result.mergeable = old;
        }

        if (otherBranches) {
            result.mergeableInto = new ArrayList<>();
            BranchOrderSection branchOrder = projectState.getBranchOrderSection();
            if (branchOrder != null) {
                int prefixLen = Constants.R_HEADS.length();
                String[] names = branchOrder.getMoreStable(ref.getName());
                Map<String, Ref> refs = git.getRefDatabase().exactRef(names);
                for (String n : names) {
                    Ref other = refs.get(n);
                    if (other == null) {
                        continue;
                    }
                    if (cache.get(commit, other, SubmitType.CHERRY_PICK, strategy, change.getDest(), git,
                            db.get())) {
                        result.mergeableInto.add(other.getName().substring(prefixLen));
                    }
                }
            }
        }
    }
    return result;
}

From source file:com.google.gerrit.server.git.BranchOrderSection.java

License:Apache License

private static String fullName(String branch) {
    if (branch.startsWith(Constants.R_HEADS)) {
        return branch;
    } else {//from  w  ww  . j  a  va 2  s .c om
        return Constants.R_HEADS + branch;
    }
}

From source file:com.google.gerrit.server.git.MergedByPushOp.java

License:Apache License

@Override
public boolean updateChange(ChangeContext ctx) throws OrmException, IOException {
    change = ctx.getChange();//from w ww  .  jav a  2 s .  com
    correctBranch = refName.equals(change.getDest().get());
    if (!correctBranch) {
        return false;
    }

    if (patchSetProvider != null) {
        // Caller might have also arranged for construction of a new patch set
        // that is not present in the old notes so we can't use PatchSetUtil.
        patchSet = patchSetProvider.get();
    } else {
        patchSet = checkNotNull(psUtil.get(ctx.getDb(), ctx.getNotes(), psId), "patch set %s not found", psId);
    }
    info = getPatchSetInfo(ctx);

    ChangeUpdate update = ctx.getUpdate(psId);
    if (change.getStatus().isOpen()) {
        change.setCurrentPatchSet(info);
        change.setStatus(Change.Status.MERGED);

        // we cannot reconstruct the submit records for when this change was
        // submitted, this is why we must fix the status
        update.fixStatus(Change.Status.MERGED);
    }

    StringBuilder msgBuf = new StringBuilder();
    msgBuf.append("Change has been successfully pushed");
    if (!refName.equals(change.getDest().get())) {
        msgBuf.append(" into ");
        if (refName.startsWith(Constants.R_HEADS)) {
            msgBuf.append("branch ");
            msgBuf.append(Repository.shortenRefName(refName));
        } else {
            msgBuf.append(refName);
        }
    }
    msgBuf.append(".");
    ChangeMessage msg = new ChangeMessage(
            new ChangeMessage.Key(change.getId(), ChangeUtil.messageUUID(ctx.getDb())), ctx.getAccountId(),
            ctx.getWhen(), psId);
    msg.setMessage(msgBuf.toString());
    cmUtil.addChangeMessage(ctx.getDb(), update, msg);

    PatchSetApproval submitter = new PatchSetApproval(
            new PatchSetApproval.Key(change.currentPatchSetId(), ctx.getAccountId(), LabelId.legacySubmit()),
            (short) 1, ctx.getWhen());
    update.putApproval(submitter.getLabel(), submitter.getValue());
    ctx.getDb().patchSetApprovals().upsert(Collections.singleton(submitter));

    return true;
}

From source file:com.google.gerrit.server.git.MergeOp.java

License:Apache License

private Set<RevCommit> getAlreadyAccepted(CodeReviewCommit branchTip) throws MergeException {
    Set<RevCommit> alreadyAccepted = new HashSet<>();

    if (branchTip != null) {
        alreadyAccepted.add(branchTip);/*from www. j  a v  a 2  s.  c  om*/
    }

    try {
        for (Ref r : repo.getRefDatabase().getRefs(Constants.R_HEADS).values()) {
            try {
                alreadyAccepted.add(rw.parseCommit(r.getObjectId()));
            } catch (IncorrectObjectTypeException iote) {
                // Not a commit? Skip over it.
            }
        }
    } catch (IOException e) {
        throw new MergeException("Failed to determine already accepted commits.", e);
    }

    logDebug("Found {} existing heads", alreadyAccepted.size());
    return alreadyAccepted;
}

From source file:com.google.gerrit.server.git.ReceiveCommits.java

License:Apache License

private void parseMagicBranch(final ReceiveCommand cmd) {
    // Permit exactly one new change request per push.
    if (magicBranch != null) {
        reject(cmd, "duplicate request");
        return;/*from   w ww.j a va  2  s. co m*/
    }

    magicBranch = new MagicBranchInput(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());
    } catch (CmdLineException e) {
        if (!clp.wasHelpRequestedByOption()) {
            reject(cmd, e.getMessage());
            return;
        }
        ref = null; // never happen
    }
    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 (!rp.getAdvertisedRefs().containsKey(ref) && !ref.equals(readHEAD(repo))) {
        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 (!magicBranch.ctl.canWrite()) {
        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("refs/drafts/" + 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.draft && magicBranch.submit) {
        reject(cmd, "cannot submit draft");
        return;
    }

    if (magicBranch.submit && !projectControl.controlForRef(MagicBranch.NEW_CHANGE + ref).canSubmit()) {
        reject(cmd, "submit not allowed");
        return;
    }

    RevWalk walk = rp.getRevWalk();
    RevCommit tip;
    try {
        tip = walk.parseCommit(magicBranch.cmd.getNewId());
    } catch (IOException ex) {
        magicBranch.cmd.setResult(REJECTED_MISSING_OBJECT);
        log.error("Invalid pack upload; one or more objects weren't sent", ex);
        return;
    }

    // If tip is a merge commit, or the root commit or
    // if %base was specified, ignore newChangeForAllNotInTarget
    if (tip.getParentCount() > 1 || magicBranch.base != null || tip.getParentCount() == 0) {
        newChangeForAllNotInTarget = false;
    }

    if (magicBranch.base != null) {
        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) {
                log.warn(String.format("Project %s cannot read %s", project.getName(), id.name()), e);
                reject(cmd, "internal server error");
                return;
            }
        }
    } else if (newChangeForAllNotInTarget) {
        String destBranch = magicBranch.dest.get();
        try {
            Ref r = repo.getRefDatabase().exactRef(destBranch);
            if (r == null) {
                reject(cmd, destBranch + " not found");
                return;
            }

            ObjectId baseHead = r.getObjectId();
            magicBranch.baseCommit = Collections.singletonList(walk.parseCommit(baseHead));
        } catch (IOException ex) {
            log.warn(String.format("Project %s cannot read %s", project.getName(), destBranch), ex);
            reject(cmd, "internal server error");
            return;
        }
    }

    // Validate that the new commits are connected with the target
    // branch.  If they aren't, we want to abort. We do this check by
    // looking to see if we can compute a merge base between the new
    // commits and the target branch head.
    //
    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.
            return;
        }
        final RevCommit h = walk.parseCommit(targetRef.getObjectId());
        final 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);
        log.error("Invalid pack upload; one or more objects weren't sent", e);
    }
}