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

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

Introduction

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

Prototype

String R_REFS

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

Click Source Link

Document

Prefix for any ref

Usage

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Sets the local branch ref to point to the specified commit id.
 *
 * @param repository//from   ww  w  . j ava  2 s  .  c  o m
 * @param branch
 * @param commitId
 * @return true if successful
 */
public static boolean setBranchRef(Repository repository, String branch, String commitId) {
    String branchName = branch;
    if (!branchName.startsWith(Constants.R_REFS)) {
        branchName = Constants.R_HEADS + branch;
    }

    try {
        RefUpdate refUpdate = repository.updateRef(branchName, false);
        refUpdate.setNewObjectId(ObjectId.fromString(commitId));
        RefUpdate.Result result = refUpdate.forceUpdate();

        switch (result) {
        case NEW:
        case FORCED:
        case NO_CHANGE:
        case FAST_FORWARD:
            return true;
        default:
            LOGGER.error(MessageFormat.format("{0} {1} update to {2} returned result {3}",
                    repository.getDirectory().getAbsolutePath(), branchName, commitId, result));
        }
    } catch (Throwable t) {
        error(t, repository, "{0} failed to set {1} to {2}", branchName, commitId);
    }
    return false;
}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Tries to merge a commit into a branch.  If there are conflicts, the merge
 * will fail.//from   w  w  w.ja  va  2s.  c o  m
 *
 * @param repository
 * @param src
 * @param toBranch
 * @param mergeType
 *            Defines the integration strategy to use for merging.
 * @param committer
 * @param message
 * @return the merge result
 */
public static MergeResult merge(Repository repository, String src, String toBranch, MergeType mergeType,
        PersonIdent committer, String message) {

    if (!toBranch.startsWith(Constants.R_REFS)) {
        // branch ref doesn't start with ref, assume this is a branch head
        toBranch = Constants.R_HEADS + toBranch;
    }

    IntegrationStrategy strategy = IntegrationStrategyFactory.create(mergeType, repository, src, toBranch);
    MergeResult mergeResult = strategy.merge(committer, message);

    if (mergeResult.status != MergeStatus.MERGED) {
        return mergeResult;
    }

    try {
        // Update the integration branch ref
        RefUpdate mergeRefUpdate = repository.updateRef(toBranch);
        mergeRefUpdate.setNewObjectId(strategy.getMergeCommit());
        mergeRefUpdate.setRefLogMessage(strategy.getRefLogMessage(), false);
        mergeRefUpdate.setExpectedOldObjectId(strategy.branchTip);
        RefUpdate.Result rc = mergeRefUpdate.update();
        switch (rc) {
        case FAST_FORWARD:
            // successful, clean merge
            break;
        default:
            mergeResult = new MergeResult(MergeStatus.FAILED, null);
            throw new GitBlitException(MessageFormat.format("Unexpected result \"{0}\" when {1} in {2}",
                    rc.name(), strategy.getOperationMessage(), repository.getDirectory()));
        }
    } catch (IOException e) {
        LOGGER.error("Failed to merge", e);
    }

    return mergeResult;
}

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

License:Apache License

@Override
public ListBranchesResult call() throws NoSuchProjectException, InvalidNameException, InvalidRevisionException,
        IOException, BranchCreationNotAllowedException {
    final ProjectControl projectControl = projectControlFactory.controlFor(projectName);

    String refname = branchName;/*ww w .j a v  a2  s .  c  o m*/
    while (refname.startsWith("/")) {
        refname = refname.substring(1);
    }
    if (!refname.startsWith(Constants.R_REFS)) {
        refname = Constants.R_HEADS + refname;
    }
    if (!Repository.isValidRefName(refname)) {
        throw new InvalidNameException();
    }
    if (refname.startsWith(ReceiveCommits.NEW_CHANGE)) {
        throw new BranchCreationNotAllowedException(ReceiveCommits.NEW_CHANGE);
    }

    final Branch.NameKey name = new Branch.NameKey(projectName, refname);
    final RefControl refControl = projectControl.controlForRef(name);
    final Repository repo = repoManager.openRepository(projectName);
    try {
        final ObjectId revid = parseStartingRevision(repo);
        final RevWalk rw = verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);

        if (refname.startsWith(Constants.R_HEADS)) {
            // Ensure that what we start the branch from is a commit. If we
            // were given a tag, deference to the commit instead.
            //
            try {
                object = rw.parseCommit(object);
            } catch (IncorrectObjectTypeException notCommit) {
                throw new IllegalStateException(startingRevision + " not a commit");
            }
        }

        if (!refControl.canCreate(rw, object)) {
            throw new IllegalStateException("Cannot create " + refname);
        }

        try {
            final RefUpdate u = repo.updateRef(refname);
            u.setExpectedOldObjectId(ObjectId.zeroId());
            u.setNewObjectId(object.copy());
            u.setRefLogIdent(identifiedUser.newRefLogIdent());
            u.setRefLogMessage("created via web from " + startingRevision, false);
            final RefUpdate.Result result = u.update(rw);
            switch (result) {
            case FAST_FORWARD:
            case NEW:
            case NO_CHANGE:
                replication.scheduleUpdate(name.getParentKey(), refname);
                hooks.doRefUpdatedHook(name, u, identifiedUser.getAccount());
                break;
            default: {
                throw new IOException(result.name());
            }
            }
        } catch (IOException err) {
            log.error("Cannot create branch " + name, err);
            throw err;
        }
    } finally {
        repo.close();
    }

    return listBranchesFactory.create(projectName).call();
}

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);
    }/*from w  w  w  . ja v  a  2s  .com*/

    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.server.change.ChangeTriplet.java

License:Apache License

/**
 * Parse a triplet out of a string./*from  w  w  w. j av a2  s. c o  m*/
 *
 * @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.gitiles.DescribeServlet.java

License:Open Source License

private NameRevCommand nameRevCommand(ObjectId id, HttpServletRequest req, HttpServletResponse res)
        throws IOException {
    Repository repo = ServletUtils.getRepository(req);
    GitilesView view = ViewFilter.getView(req);
    NameRevCommand cmd = new Git(repo).nameRev();
    boolean all = getBooleanParam(view, ALL_PARAM);
    boolean tags = getBooleanParam(view, TAGS_PARAM);
    if (all && tags) {
        renderTextError(req, res, SC_BAD_REQUEST, "Cannot specify both \"all\" and \"tags\"");
        return null;
    }//w  ww  .  j  a  v a  2 s.com
    if (all) {
        cmd.addPrefix(Constants.R_REFS);
    } else if (tags) {
        cmd.addPrefix(Constants.R_TAGS);
    } else {
        cmd.addAnnotatedTags();
    }
    cmd.add(id);
    return cmd;
}

From source file:com.google.gitiles.RefServlet.java

License:Open Source License

private static Map<String, Ref> getRefs(RefDatabase refdb, String path) throws IOException {
    path = GitilesView.maybeTrimLeadingAndTrailingSlash(path);
    if (path.isEmpty()) {
        return refdb.getRefs(RefDatabase.ALL);
    }/*from   w w w .  j  a va 2  s  . co  m*/
    path = Constants.R_REFS + path;
    Ref singleRef = refdb.getRef(path);
    if (singleRef != null) {
        return ImmutableMap.of(singleRef.getName(), singleRef);
    }
    return refdb.getRefs(path + '/');
}

From source file:com.googlesource.gerrit.plugins.xdocs.XDocServlet.java

License:Apache License

private String getRevision(String revision, ProjectControl projectControl)
        throws ResourceNotFoundException, AuthException, IOException {
    if (revision == null) {
        return null;
    }/*from ww  w  .j  a v  a 2 s .com*/

    if (ObjectId.isId(revision)) {
        return revision;
    }

    if (Constants.HEAD.equals(revision)) {
        return getHead.get().apply(new ProjectResource(projectControl));
    } else {
        String rev = revision;
        if (!rev.startsWith(Constants.R_REFS)) {
            rev = Constants.R_HEADS + rev;
        }
        if (!projectControl.controlForRef(rev).isVisible()) {
            throw new ResourceNotFoundException();
        }
        return rev;
    }
}

From source file:de.br0tbox.gitfx.ui.sync.SynchronizationTask.java

License:Apache License

private void refreshBranches() throws IOException {
    final List<String> remoteList = new ArrayList<>();
    final List<String> tagsList = new ArrayList<>();
    final List<String> localList = new ArrayList<>();
    final Repository repository = projectModel.getFxProject().getGit().getRepository();
    final Map<String, Ref> remotes = repository.getRefDatabase().getRefs(Constants.R_REMOTES);
    final Iterator<String> remotesIterator = remotes.keySet().iterator();
    while (remotesIterator.hasNext()) {
        final String remotekey = remotesIterator.next();
        final Ref remote = remotes.get(remotekey);
        remoteList.add(remote.getName());
    }//from ww w .  j  a v  a2 s  .  co  m
    final Map<String, Ref> tags = repository.getRefDatabase().getRefs(Constants.R_TAGS);
    final Iterator<String> tagsIterator = tags.keySet().iterator();
    while (tagsIterator.hasNext()) {
        final String tagkey = tagsIterator.next();
        final Ref tag = tags.get(tagkey);
        tagsList.add(tag.getName());
    }
    final Map<String, Ref> all = repository.getRefDatabase().getRefs(Constants.R_REFS);
    final Iterator<String> allIterator = all.keySet().iterator();
    while (allIterator.hasNext()) {
        final String allKey = allIterator.next();
        final Ref allRef = all.get(allKey);
        if (allRef != null) {
            final String name = allRef.getName();
            if (!remoteList.contains(name) && !tagsList.contains(name)) {
                localList.add(name);
            }
        }
    }
    Platform.runLater(new Runnable() {

        @Override
        public void run() {
            projectModel.getLocalBranchesProperty().clear();
            projectModel.getLocalBranchesProperty().addAll(localList);
            projectModel.getRemoteBranchesProperty().clear();
            projectModel.getRemoteBranchesProperty().addAll(remoteList);
            projectModel.getTagsProperty().clear();
            projectModel.getTagsProperty().addAll(tagsList);
        }
    });
}

From source file:jenkins.plugins.git.MergeWithGitSCMExtension.java

License:Open Source License

@Override
public Revision decorateRevisionToBuild(GitSCM scm, Run<?, ?> build, GitClient git, TaskListener listener,
        Revision marked, Revision rev) throws IOException, InterruptedException, GitException {
    ObjectId baseObjectId;//from  w w w .ja  va 2s .c om
    if (StringUtils.isBlank(baseHash)) {
        try {
            baseObjectId = git.revParse(Constants.R_REFS + baseName);
        } catch (GitException e) {
            listener.getLogger().printf("Unable to determine head revision of %s prior to merge with PR%n",
                    baseName);
            throw e;
        }
    } else {
        baseObjectId = ObjectId.fromString(baseHash);
    }
    listener.getLogger().printf("Merging %s commit %s into PR head commit %s%n", baseName, baseObjectId.name(),
            rev.getSha1String());
    checkout(scm, build, git, listener, rev);
    try {
        /* could parse out of JenkinsLocationConfiguration.get().getAdminAddress() but seems overkill */
        git.setAuthor("Jenkins", "nobody@nowhere");
        git.setCommitter("Jenkins", "nobody@nowhere");
        MergeCommand cmd = git.merge().setRevisionToMerge(baseObjectId);
        for (GitSCMExtension ext : scm.getExtensions()) {
            // By default we do a regular merge, allowing it to fast-forward.
            ext.decorateMergeCommand(scm, build, git, listener, cmd);
        }
        cmd.execute();
    } catch (GitException x) {
        // TODO clarify these TODO comments copied from GitHub Branch Source

        // Try to revert merge conflict markers.
        // TODO IGitAPI offers a reset(hard) method yet GitClient does not. Why?
        checkout(scm, build, git, listener, rev);
        // TODO would be nicer to throw an AbortException with just the message, but this is actually worse
        // until git-client 1.19.7+
        throw x;
    }
    build.addAction(new MergeRecord(baseName, baseObjectId.getName())); // does not seem to be used, but just in case
    ObjectId mergeRev = git.revParse(Constants.HEAD);
    listener.getLogger().println("Merge succeeded, producing " + mergeRev.name());
    return new Revision(mergeRev, rev.getBranches()); // note that this ensures Build.revision != Build.marked
}