Example usage for org.eclipse.jgit.lib Repository shortenRefName

List of usage examples for org.eclipse.jgit.lib Repository shortenRefName

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository shortenRefName.

Prototype

@NonNull
public static String shortenRefName(String refName) 

Source Link

Document

Get a shortened more user friendly ref name

Usage

From source file:com.gitblit.wicket.panels.ActivityPanel.java

License:Apache License

public ActivityPanel(String wicketId, List<Activity> recentActivity) {
    super(wicketId);

    Collections.sort(recentActivity);

    final int shortHashLen = app().settings().getInteger(Keys.web.shortCommitIdLength, 6);
    DataView<Activity> activityView = new DataView<Activity>("activity",
            new ListDataProvider<Activity>(recentActivity)) {
        private static final long serialVersionUID = 1L;

        @Override/*from  w  w w  .  j a  v a  2s  .c om*/
        public void populateItem(final Item<Activity> activityItem) {
            final Activity entry = activityItem.getModelObject();
            activityItem.add(
                    WicketUtils.createDatestampLabel("title", entry.startDate, getTimeZone(), getTimeUtils()));

            // display the commits in chronological order
            DataView<RepositoryCommit> commits = new DataView<RepositoryCommit>("commit",
                    new ListDataProvider<RepositoryCommit>(entry.getCommits())) {
                private static final long serialVersionUID = 1L;

                @Override
                public void populateItem(final Item<RepositoryCommit> commitItem) {
                    final RepositoryCommit commit = commitItem.getModelObject();

                    // commit time of day
                    commitItem.add(WicketUtils.createTimeLabel("time", commit.getCommitterIdent().getWhen(),
                            getTimeZone(), getTimeUtils()));

                    // avatar
                    commitItem.add(new AvatarImage("avatar", commit.getAuthorIdent(), 40));

                    // merge icon
                    if (commit.getParentCount() > 1) {
                        commitItem.add(WicketUtils.newImage("commitIcon", "commit_merge_16x16.png"));
                    } else {
                        commitItem.add(WicketUtils.newBlankImage("commitIcon").setVisible(false));
                    }

                    // author search link
                    String author = commit.getAuthorIdent().getName();
                    LinkPanel authorLink = new LinkPanel("author", "list", author, GitSearchPage.class,
                            WicketUtils.newSearchParameter(commit.repository, null, author,
                                    Constants.SearchType.AUTHOR),
                            true);
                    setPersonSearchTooltip(authorLink, author, Constants.SearchType.AUTHOR);
                    commitItem.add(authorLink);

                    // repository
                    String repoName = StringUtils.stripDotGit(commit.repository);
                    LinkPanel repositoryLink = new LinkPanel("repository", null, repoName, SummaryPage.class,
                            WicketUtils.newRepositoryParameter(commit.repository), true);
                    WicketUtils.setCssBackground(repositoryLink, repoName);
                    commitItem.add(repositoryLink);

                    // repository branch
                    LinkPanel branchLink = new LinkPanel("branch", "list",
                            Repository.shortenRefName(commit.branch), LogPage.class,
                            WicketUtils.newObjectParameter(commit.repository, commit.branch), true);
                    WicketUtils.setCssStyle(branchLink, "color: #008000;");
                    commitItem.add(branchLink);

                    LinkPanel commitid = new LinkPanel("commitid", "list subject",
                            commit.getName().substring(0, shortHashLen), CommitPage.class,
                            WicketUtils.newObjectParameter(commit.repository, commit.getName()), true);
                    commitItem.add(commitid);

                    // message/commit link
                    String shortMessage = commit.getShortMessage();
                    String trimmedMessage = shortMessage;
                    if (commit.getRefs() != null && commit.getRefs().size() > 0) {
                        trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG_REFS);
                    } else {
                        trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG);
                    }
                    LinkPanel shortlog = new LinkPanel("message", "list subject", trimmedMessage,
                            CommitPage.class,
                            WicketUtils.newObjectParameter(commit.repository, commit.getName()), true);
                    if (!shortMessage.equals(trimmedMessage)) {
                        WicketUtils.setHtmlTooltip(shortlog, shortMessage);
                    }
                    commitItem.add(shortlog);

                    // refs
                    commitItem.add(new RefsPanel("commitRefs", commit.repository, commit.getRefs()));

                    // diff, tree links
                    commitItem.add(new BookmarkablePageLink<Void>("diff", CommitDiffPage.class,
                            WicketUtils.newObjectParameter(commit.repository, commit.getName()))
                                    .setEnabled(commit.getParentCount() > 0));
                    commitItem.add(new BookmarkablePageLink<Void>("tree", TreePage.class,
                            WicketUtils.newObjectParameter(commit.repository, commit.getName())));
                }
            };
            activityItem.add(commits);
        }
    };
    add(activityView);
}

From source file:com.gitblit.wicket.panels.BranchesPanel.java

License:Apache License

public BranchesPanel(String wicketId, final RepositoryModel model, Repository r, final int maxCount,
        final boolean showAdmin) {
    super(wicketId);

    // branches/* w  ww  .  j av a 2  s . com*/
    List<RefModel> branches = new ArrayList<RefModel>();
    UserModel user = GitBlitWebSession.get().getUser();
    if (user == null) {
        user = UserModel.ANONYMOUS;
    }

    List<RefModel> localBranches = JGitUtils.getLocalBranches(r, false, -1);
    for (RefModel refModel : localBranches) {
        if (user.canView(model, refModel.reference.getName())) {
            branches.add(refModel);
        }
    }
    if (model.showRemoteBranches) {
        List<RefModel> remoteBranches = JGitUtils.getRemoteBranches(r, false, -1);
        for (RefModel refModel : remoteBranches) {
            if (user.canView(model, refModel.reference.getName())) {
                branches.add(refModel);
            }
        }
    }
    Collections.sort(branches);
    Collections.reverse(branches);
    if (maxCount > 0 && branches.size() > maxCount) {
        branches = new ArrayList<RefModel>(branches.subList(0, maxCount));
    }

    if (maxCount > 0) {
        // summary page
        // show branches page link
        add(new LinkPanel("branches", "title", new StringResourceModel("gb.branches", this, null),
                BranchesPage.class, WicketUtils.newRepositoryParameter(model.name)));
    } else {
        // branches page
        add(new Label("branches", new StringResourceModel("gb.branches", this, null)));
    }

    // only allow delete if we have multiple branches
    final boolean showDelete = showAdmin && branches.size() > 1;

    ListDataProvider<RefModel> branchesDp = new ListDataProvider<RefModel>(branches);
    DataView<RefModel> branchesView = new DataView<RefModel>("branch", branchesDp) {
        private static final long serialVersionUID = 1L;
        int counter;

        @Override
        public void populateItem(final Item<RefModel> item) {
            final RefModel entry = item.getModelObject();

            PageParameters shortUniqRef = WicketUtils.newObjectParameter(model.name,
                    Repository.shortenRefName(entry.getName()));

            item.add(WicketUtils.createDateLabel("branchDate", entry.getDate(), getTimeZone(), getTimeUtils()));

            item.add(new LinkPanel("branchName", "list name", StringUtils.trimString(entry.displayName, 28),
                    LogPage.class, shortUniqRef));

            String author = entry.getAuthorIdent().getName();
            LinkPanel authorLink = new LinkPanel("branchAuthor", "list", author, GitSearchPage.class,
                    WicketUtils.newSearchParameter(model.name, entry.getName(), author,
                            Constants.SearchType.AUTHOR));
            setPersonSearchTooltip(authorLink, author, Constants.SearchType.AUTHOR);
            item.add(authorLink);

            // short message
            String shortMessage = entry.getShortMessage();
            String trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG);
            LinkPanel shortlog = new LinkPanel("branchLog", "list subject", trimmedMessage, CommitPage.class,
                    shortUniqRef);
            if (!shortMessage.equals(trimmedMessage)) {
                shortlog.setTooltip(shortMessage);
            }
            item.add(shortlog);

            if (maxCount <= 0) {
                Fragment fragment = new Fragment("branchLinks",
                        showDelete ? "branchPageAdminLinks" : "branchPageLinks", BranchesPanel.this);
                fragment.add(new BookmarkablePageLink<Void>("log", LogPage.class, shortUniqRef));
                fragment.add(new BookmarkablePageLink<Void>("tree", TreePage.class, shortUniqRef));
                String rawUrl = RawServlet.asLink(getContextUrl(), model.name,
                        Repository.shortenRefName(entry.getName()), null);
                fragment.add(new ExternalLink("raw", rawUrl));
                fragment.add(new BookmarkablePageLink<Void>("metrics", MetricsPage.class, shortUniqRef));
                fragment.add(new ExternalLink("syndication",
                        SyndicationServlet.asLink(GitBlitRequestUtils.getRelativePathPrefixToContextRoot(),
                                model.name, Repository.shortenRefName(entry.getName()), 0)));
                if (showDelete) {
                    fragment.add(createDeleteBranchLink(model, entry));
                }
                item.add(fragment);
            } else {
                Fragment fragment = new Fragment("branchLinks", "branchPanelLinks", BranchesPanel.this);
                fragment.add(new BookmarkablePageLink<Void>("log", LogPage.class, shortUniqRef));
                fragment.add(new BookmarkablePageLink<Void>("tree", TreePage.class, shortUniqRef));
                String rawUrl = RawServlet.asLink(getContextUrl(), model.name,
                        Repository.shortenRefName(entry.getName()), null);
                fragment.add(new ExternalLink("raw", rawUrl));
                item.add(fragment);
            }
            WicketUtils.setAlternatingBackground(item, counter);
            counter++;
        }
    };
    add(branchesView);
    if (branches.size() < maxCount || maxCount <= 0) {
        add(new Label("allBranches", "").setVisible(false));
    } else {
        add(new LinkPanel("allBranches", "link", new StringResourceModel("gb.allBranches", this, null),
                BranchesPage.class, WicketUtils.newRepositoryParameter(model.name)));
    }
    // We always have 1 branch
    hasBranches = (branches.size() > 1)
            || ((branches.size() == 1) && !branches.get(0).displayName.equalsIgnoreCase("master"));
}

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

License:Apache License

/**
 * Returns the short names of refs which are as well in the matchingRefs list
 * as well as in the allRef list./* w  w  w  .  java 2  s . co  m*/
 */
private static List<String> getMatchingRefNames(Set<String> matchingRefs, Collection<Ref> allRefs) {
    List<String> refNames = Lists.newArrayListWithCapacity(matchingRefs.size());
    for (Ref r : allRefs) {
        if (matchingRefs.contains(r.getName())) {
            refNames.add(Repository.shortenRefName(r.getName()));
        }
    }
    return refNames;
}

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();/*www.  j  a  v a2  s  . c  o m*/
    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.ReceiveCommits.java

License:Apache License

private void markChangeMergedByPush(ReviewDb db, final ReplaceRequest result, ChangeControl control)
        throws OrmException, IOException {
    Change.Id id = result.change.getId();
    db.changes().beginTransaction(id);//from ww  w .  j  a va2  s . c o m
    Change change;

    ChangeUpdate update;
    try {
        change = db.changes().atomicUpdate(id, new AtomicUpdate<Change>() {
            @Override
            public Change update(Change change) {
                if (change.getStatus().isOpen()) {
                    change.setCurrentPatchSet(result.info);
                    change.setStatus(Change.Status.MERGED);
                    ChangeUtil.updated(change);
                }
                return change;
            }
        });
        String mergedIntoRef = result.mergedIntoRef;

        StringBuilder msgBuf = new StringBuilder();
        msgBuf.append("Change has been successfully pushed");
        if (!mergedIntoRef.equals(change.getDest().get())) {
            msgBuf.append(" into ");
            if (mergedIntoRef.startsWith(Constants.R_HEADS)) {
                msgBuf.append("branch ");
                msgBuf.append(Repository.shortenRefName(mergedIntoRef));
            } else {
                msgBuf.append(mergedIntoRef);
            }
        }
        msgBuf.append(".");
        ChangeMessage msg = new ChangeMessage(new ChangeMessage.Key(id, ChangeUtil.messageUUID(db)),
                currentUser.getAccountId(), change.getLastUpdatedOn(), result.info.getKey());
        msg.setMessage(msgBuf.toString());

        update = updateFactory.create(control, change.getLastUpdatedOn());

        cmUtil.addChangeMessage(db, update, msg);
        db.commit();
    } finally {
        db.rollback();
    }
    indexer.index(db, change);
    update.commit();
}

From source file:com.microsoft.gittf.core.util.StashUtil.java

License:Open Source License

/**
 * Creates a stash/*from  w  ww .ja  va  2s .  c  om*/
 * 
 * @param repository
 *        the git repository
 * @param repositoryInserter
 *        the repository inserter object to use
 * @param rootBaseTree
 *        the tree id for the base commit of the stash
 * @param rootStashTree
 *        the tree id for the commit of the stash
 * @param rootIndexTree
 *        the tree id for the index commit of the stash
 * @param baseParentId
 *        the parent of the base tree commit
 * @param ownerDisplayName
 *        the owner display name of the stash
 * @param ownerName
 *        the owner name of the stash
 * @param stashComment
 *        the comment used to for the stash
 * @param stashName
 *        the stash name
 * @return
 * @throws IOException
 */
public static final ObjectId create(final Repository repository, final ObjectInserter repositoryInserter,
        final ObjectId rootBaseTree, final ObjectId rootStashTree, final ObjectId rootIndexTree,
        final ObjectId baseParentId, final String ownerDisplayName, final String ownerName,
        final String stashComment, final String stashName) throws IOException {
    Check.notNull(repository, "repository"); //$NON-NLS-1$
    Check.notNull(repositoryInserter, "repositoryInserter"); //$NON-NLS-1$
    Check.notNull(rootBaseTree, "rootBaseTree"); //$NON-NLS-1$
    Check.notNull(rootStashTree, "rootStashTree"); //$NON-NLS-1$
    Check.notNull(rootIndexTree, "rootIndexTree"); //$NON-NLS-1$

    /* identifies the head and the branch we are creating the stash for */
    Ref headReference = repository.getRef(Constants.HEAD);
    RevCommit headCommit = new RevWalk(repository).parseCommit(headReference.getObjectId());
    String currentBranchName = Repository.shortenRefName(headReference.getTarget().getName());

    PersonIdent author = new PersonIdent(ownerDisplayName, ownerName);

    /* create the base commit */
    CommitBuilder commitBuilder = new CommitBuilder();
    commitBuilder.setTreeId(rootBaseTree);
    if (baseParentId != null) {
        commitBuilder.setParentId(baseParentId);
    }
    commitBuilder.setMessage(stashComment);
    commitBuilder.setAuthor(author);
    commitBuilder.setCommitter(author);

    ObjectId baseCommit = repositoryInserter.insert(commitBuilder);

    /* create the index commit */
    commitBuilder.setTreeId(rootIndexTree);
    commitBuilder.setParentId(baseCommit);
    commitBuilder.setMessage(MessageFormat.format(STASH_INDEX_COMMENT, currentBranchName,
            headCommit.abbreviate(7).name(), stashName));
    commitBuilder.setAuthor(author);
    commitBuilder.setCommitter(author);

    ObjectId indexCommit = repositoryInserter.insert(commitBuilder);

    /* create the stash commit */
    commitBuilder.setTreeId(rootStashTree);
    commitBuilder.setParentId(baseCommit);
    commitBuilder.addParentId(indexCommit);

    String stashRefLogComment = MessageFormat.format(STASH_COMMENT, currentBranchName,
            headCommit.abbreviate(7).name(), stashName);
    commitBuilder.setMessage(stashRefLogComment);

    ObjectId stashCommit = repositoryInserter.insert(commitBuilder);

    repositoryInserter.flush();

    /* Update the stash reference and ref log */
    RefUpdate stashReferenceUpdate = repository.updateRef(Constants.R_STASH);
    stashReferenceUpdate.setNewObjectId(stashCommit);
    stashReferenceUpdate.setRefLogIdent(author);
    stashReferenceUpdate.setRefLogMessage(stashRefLogComment, false);

    Ref currentStashRef = repository.getRef(Constants.R_STASH);
    if (currentStashRef != null) {
        stashReferenceUpdate.setExpectedOldObjectId(currentStashRef.getObjectId());
    } else {
        stashReferenceUpdate.setExpectedOldObjectId(ObjectId.zeroId());
    }

    stashReferenceUpdate.forceUpdate();

    return stashCommit;
}

From source file:com.mooregreatsoftware.gitprocess.lib.Branch.java

License:Apache License

@Pure
@NonNull// ww w .  j  a  v  a 2s . com
private static String computePotentialRemoteRefName(@NonNull GitLib gitLib, @NonNull String name) {
    final String shortName = Repository.shortenRefName(name);
    final String remoteName = remoteName(gitLib, shortName);
    return remoteName != null ? R_REMOTES + name : R_HEADS + shortName;
}

From source file:com.mooregreatsoftware.gitprocess.lib.Branch.java

License:Apache License

/**
 * The "nice" name for the branch.//w ww  .j  ava  2 s  . c o m
 * <p>
 * For example, instead of "refs/remotes/origin/master" this returns "origin/master"
 */
@NonNull
public String shortName() {
    return Repository.shortenRefName(name());
}

From source file:com.mooregreatsoftware.gitprocess.lib.Branch.java

License:Apache License

@Override
public String toString() {
    return "Branch{" + Repository.shortenRefName(name()) + "(" + objectId().abbreviate(7).name() + ")}";
}

From source file:com.mooregreatsoftware.gitprocess.lib.config.StoredBranchConfig.java

License:Apache License

@Override
@Nullable//w  w w. j  a  v a 2s. c om
@SuppressWarnings("RedundantCast")
public Branch getUpstream(Branch branch) {
    final String remoteName = getString(CONFIG_BRANCH_SECTION, branch.shortName(), CONFIG_KEY_REMOTE);

    if (remoteName == null) {
        LOG.debug("There is no upstream set for \"{}\"", branch.shortName());
        return null;
    }

    final String remotePath = (remoteName.equals(".") ? "" : remoteName + "/");

    final String upstreamBranchName = getString(CONFIG_BRANCH_SECTION, branch.shortName(), CONFIG_KEY_MERGE);

    if (upstreamBranchName == null) {
        throw new IllegalStateException("There is no configuration value for \"" + CONFIG_BRANCH_SECTION + '.'
                + branch.shortName() + '.' + CONFIG_KEY_MERGE + "\", which is an invalid Git state");
    }

    final String fullRemotePath = remotePath + Repository.shortenRefName(upstreamBranchName);

    final Branch upstream = branches.branch(fullRemotePath);

    if (upstream == null) {
        throw new IllegalArgumentException(
                "The upstream for \"" + branch.shortName() + "\" (\"" + fullRemotePath + "\") does not exist");
    }

    return upstream;
}