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.amd.gerrit.plugins.manifestsubscription.ManifestSubscription.java

License:Open Source License

private void watchProjectsInCanonicalManifest(String store, String branchPath, String defaultBranch,
        List<com.amd.gerrit.plugins.manifestsubscription.manifest.Project> projects) {
    ProjectBranchKey pbKey;//  ww w .  ja  va2  s .c o  m
    for (com.amd.gerrit.plugins.manifestsubscription.manifest.Project project : projects) {
        if (manifestStores.containsRow(project.getName()) && !manifestStores.row(project.getName()).isEmpty()) {
            // Skip if it's one of the repo for storing
            // manifest to avoid infinite loop
            // This is a bit too general, but it's done to avoid the complexity
            // of actually tracing out the loop
            // i.e. manifest1->store2 --> manifest2->store1
            continue;
        }

        // Make sure revision is branch ref w/o refs/heads
        String branch = project.getRevision() == null ? defaultBranch
                : (project.getUpstream() != null ? project.getUpstream() : project.getRevision());
        pbKey = new ProjectBranchKey(project.getName(), Repository.shortenRefName(branch));

        //TODO only update manifests that changed
        if (!subscribedRepos.contains(pbKey, store)) {
            subscribedRepos.put(pbKey, store,
                    Maps.<String, Set<com.amd.gerrit.plugins.manifestsubscription.manifest.Project>>newHashMap());
        }

        Map<String, Set<com.amd.gerrit.plugins.manifestsubscription.manifest.Project>> ps;
        ps = subscribedRepos.get(pbKey, store);
        if (!ps.containsKey(branchPath)) {
            ps.put(branchPath, Sets.<com.amd.gerrit.plugins.manifestsubscription.manifest.Project>newHashSet());
        }
        ps.get(branchPath).add(project);

        if (project.getProject().size() > 0) {
            watchProjectsInCanonicalManifest(store, branchPath, defaultBranch, project.getProject());
        }
    }
}

From source file:com.genuitec.org.eclipse.egit.ui.internal.branch.BranchOperationUI.java

License:Open Source License

/**
 * @param result//from   w w  w  .  j  a  v  a2s .  co m
 *            the result to show
 */
public void show(final CheckoutResult result) {
    if (result.getStatus() == CheckoutResult.Status.CONFLICTS) {
        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
            public void run() {
                Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                CleanupUncomittedChangesDialog cleanupUncomittedChangesDialog = new CleanupUncomittedChangesDialog(
                        shell, UIText.BranchResultDialog_CheckoutConflictsTitle,
                        NLS.bind(UIText.BranchResultDialog_CheckoutConflictsMessage,
                                Repository.shortenRefName(target)),
                        repository, result.getConflictList());
                cleanupUncomittedChangesDialog.open();
                if (cleanupUncomittedChangesDialog.shouldContinue()) {
                    BranchOperationUI op = BranchOperationUI.checkoutWithoutQuestion(repository, target)
                            .doneCallback(doneCallback);
                    op.start();
                }
            }
        });
    } else if (result.getStatus() == CheckoutResult.Status.NONDELETED) {
        // double-check if the files are still there
        boolean show = false;
        List<String> pathList = result.getUndeletedList();
        for (String path : pathList)
            if (new File(repository.getWorkTree(), path).exists()) {
                show = true;
                break;
            }
        if (!show)
            return;
        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
            public void run() {
                Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                new NonDeletedFilesDialog(shell, repository, result.getUndeletedList()).open();
            }
        });
    } else if (result.getStatus() == CheckoutResult.Status.OK) {
        if (RepositoryUtil.isDetachedHead(repository))
            showDetachedHeadWarning();
    }
    if (doneCallback != null) {
        doneCallback.done(result);
    }
}

From source file:com.gitblit.client.EditRepositoryDialog.java

License:Apache License

private boolean validateFields() {
    String rname = nameField.getText();
    if (StringUtils.isEmpty(rname)) {
        error("Please enter a repository name!");
        return false;
    }// ww  w  . j a  v  a2s .  co  m

    // automatically convert backslashes to forward slashes
    rname = rname.replace('\\', '/');
    // Automatically replace // with /
    rname = rname.replace("//", "/");

    // prohibit folder paths
    if (rname.startsWith("/")) {
        error("Leading root folder references (/) are prohibited.");
        return false;
    }
    if (rname.startsWith("../")) {
        error("Relative folder references (../) are prohibited.");
        return false;
    }
    if (rname.contains("/../")) {
        error("Relative folder references (../) are prohibited.");
        return false;
    }
    if (rname.endsWith("/")) {
        rname = rname.substring(0, rname.length() - 1);
    }

    // confirm valid characters in repository name
    Character c = StringUtils.findInvalidCharacter(rname);
    if (c != null) {
        error(MessageFormat.format("Illegal character ''{0}'' in repository name!", c));
        return false;
    }

    // verify repository name uniqueness on create
    if (isCreate) {
        // force repo names to lowercase
        // this means that repository name checking for rpc creation
        // is case-insensitive, regardless of the Gitblit server's
        // filesystem
        if (repositoryNames.contains(rname.toLowerCase())) {
            error(MessageFormat.format("Can not create repository ''{0}'' because it already exists.", rname));
            return false;
        }
    } else {
        // check rename collision
        if (!repositoryName.equalsIgnoreCase(rname)) {
            if (repositoryNames.contains(rname.toLowerCase())) {
                error(MessageFormat.format("Failed to rename ''{0}'' because ''{1}'' already exists.",
                        repositoryName, rname));
                return false;
            }
        }
    }

    if (accessRestriction.getSelectedItem() == null) {
        error("Please select access restriction!");
        return false;
    }

    if (federationStrategy.getSelectedItem() == null) {
        error("Please select federation strategy!");
        return false;
    }

    repository.name = rname;
    repository.description = descriptionField.getText();
    repository.owners.clear();
    repository.owners.addAll(ownersPalette.getSelections());
    repository.HEAD = headRefField.getSelectedItem() == null ? null : headRefField.getSelectedItem().toString();
    repository.gcPeriod = (Integer) gcPeriod.getSelectedItem();
    repository.gcThreshold = gcThreshold.getText();
    repository.acceptNewPatchsets = acceptNewPatchsets.isSelected();
    repository.acceptNewTickets = acceptNewTickets.isSelected();
    repository.requireApproval = requireApproval.isSelected();
    repository.mergeTo = mergeToField.getSelectedItem() == null ? null
            : Repository.shortenRefName(mergeToField.getSelectedItem().toString());
    repository.useIncrementalPushTags = useIncrementalPushTags.isSelected();
    repository.showRemoteBranches = showRemoteBranches.isSelected();
    repository.skipSizeCalculation = skipSizeCalculation.isSelected();
    repository.skipSummaryMetrics = skipSummaryMetrics.isSelected();
    repository.maxActivityCommits = (Integer) maxActivityCommits.getSelectedItem();

    repository.isFrozen = isFrozen.isSelected();
    repository.allowForks = allowForks.isSelected();
    repository.verifyCommitter = verifyCommitter.isSelected();

    String ml = mailingListsField.getText();
    if (!StringUtils.isEmpty(ml)) {
        Set<String> list = new HashSet<String>();
        for (String address : ml.split("(,|\\s)")) {
            if (StringUtils.isEmpty(address)) {
                continue;
            }
            list.add(address.toLowerCase());
        }
        repository.mailingLists = new ArrayList<String>(list);
    }

    repository.accessRestriction = (AccessRestrictionType) accessRestriction.getSelectedItem();
    repository.authorizationControl = allowAuthenticated.isSelected() ? AuthorizationControl.AUTHENTICATED
            : AuthorizationControl.NAMED;
    repository.federationStrategy = (FederationStrategy) federationStrategy.getSelectedItem();

    if (repository.federationStrategy.exceeds(FederationStrategy.EXCLUDE)) {
        repository.federationSets = setsPalette.getSelections();
    }

    repository.indexedBranches = indexedBranchesPalette.getSelections();
    repository.preReceiveScripts = preReceivePalette.getSelections();
    repository.postReceiveScripts = postReceivePalette.getSelections();

    // Custom Fields
    repository.customFields = new LinkedHashMap<String, String>();
    if (customTextfields != null) {
        for (JTextField field : customTextfields) {
            String key = field.getName();
            String value = field.getText();
            repository.customFields.put(key, value);
        }
    }
    return true;
}

From source file:com.gitblit.git.GitblitReceivePack.java

License:Apache License

/**
 * Automatically closes open tickets and adds references to tickets if made in the commit message.
 *
 * @param cmd/*  ww w  .  j  a va  2 s . com*/
 */
private Collection<TicketModel> processReferencedTickets(ReceiveCommand cmd) {
    Map<Long, TicketModel> changedTickets = new LinkedHashMap<Long, TicketModel>();

    final RevWalk rw = getRevWalk();
    try {
        rw.reset();
        rw.markStart(rw.parseCommit(cmd.getNewId()));
        if (!ObjectId.zeroId().equals(cmd.getOldId())) {
            rw.markUninteresting(rw.parseCommit(cmd.getOldId()));
        }

        RevCommit c;
        while ((c = rw.next()) != null) {
            rw.parseBody(c);
            List<TicketLink> ticketLinks = JGitUtils.identifyTicketsFromCommitMessage(getRepository(), settings,
                    c);
            if (ticketLinks == null) {
                continue;
            }

            for (TicketLink link : ticketLinks) {

                TicketModel ticket = ticketService.getTicket(repository, link.targetTicketId);
                if (ticket == null) {
                    continue;
                }

                Change change = null;
                String commitSha = c.getName();
                String branchName = Repository.shortenRefName(cmd.getRefName());

                switch (link.action) {
                case Commit: {
                    //A commit can reference a ticket in any branch even if the ticket is closed.
                    //This allows developers to identify and communicate related issues
                    change = new Change(user.username);
                    change.referenceCommit(commitSha);
                }
                    break;

                case Close: {
                    // As this isn't a patchset theres no merging taking place when closing a ticket
                    if (ticket.isClosed()) {
                        continue;
                    }

                    change = new Change(user.username);
                    change.setField(Field.status, Status.Fixed);

                    if (StringUtils.isEmpty(ticket.responsible)) {
                        // unassigned tickets are assigned to the closer
                        change.setField(Field.responsible, user.username);
                    }
                }

                default: {
                    //No action
                }
                    break;
                }

                if (change != null) {
                    ticket = ticketService.updateTicket(repository, ticket.number, change);
                }

                if (ticket != null) {
                    sendInfo("");
                    sendHeader("#{0,number,0}: {1}", ticket.number,
                            StringUtils.trimString(ticket.title, Constants.LEN_SHORTLOG));

                    switch (link.action) {
                    case Commit: {
                        sendInfo("referenced by push of {0} to {1}", commitSha, branchName);
                        changedTickets.put(ticket.number, ticket);
                    }
                        break;

                    case Close: {
                        sendInfo("closed by push of {0} to {1}", commitSha, branchName);
                        changedTickets.put(ticket.number, ticket);
                    }
                        break;

                    default: {
                    }
                    }

                    sendInfo(ticketService.getTicketUrl(ticket));
                    sendInfo("");
                } else {
                    switch (link.action) {
                    case Commit: {
                        sendError("FAILED to reference ticket {0} by push of {1}", link.targetTicketId,
                                commitSha);
                    }
                        break;

                    case Close: {
                        sendError("FAILED to close ticket {0} by push of {1}", link.targetTicketId, commitSha);
                    }
                        break;

                    default: {
                    }
                    }
                }
            }
        }

    } catch (IOException e) {
        LOGGER.error("Can't scan for changes to reference or close", e);
    } finally {
        rw.reset();
    }

    return changedTickets.values();
}

From source file:com.gitblit.git.PatchsetReceivePack.java

License:Apache License

/** Extracts the integration branch from the ref name */
private String getIntegrationBranch(String refName) {
    String patchsetRef = getPatchsetRef(refName);
    String branch = refName.substring(patchsetRef.length());
    if (branch.indexOf('%') > -1) {
        branch = branch.substring(0, branch.indexOf('%'));
    }/*from w  w w .  j  a  va 2s.co m*/

    String defaultBranch = "master";
    try {
        defaultBranch = getRepository().getBranch();
    } catch (Exception e) {
        LOGGER.error("failed to determine default branch for " + repository.name, e);
    }

    if (!StringUtils.isEmpty(getRepositoryModel().mergeTo)) {
        // repository settings specifies a default integration branch
        defaultBranch = Repository.shortenRefName(getRepositoryModel().mergeTo);
    }

    long ticketId = 0L;
    try {
        ticketId = Long.parseLong(branch);
    } catch (Exception e) {
        // not a number
    }
    if (ticketId > 0 || branch.equalsIgnoreCase("default") || branch.equalsIgnoreCase("new")) {
        return defaultBranch;
    }
    return branch;
}

From source file:com.gitblit.git.PatchsetReceivePack.java

License:Apache License

/**
 * Prepares a patchset command.//from w w w  .ja v a  2  s . c om
 *
 * @param cmd
 * @return the patchset command
 */
private PatchsetCommand preparePatchset(ReceiveCommand cmd) {
    String branch = getIntegrationBranch(cmd.getRefName());
    long number = getTicketId(cmd.getRefName());

    TicketModel ticket = null;
    if (number > 0 && ticketService.hasTicket(repository, number)) {
        ticket = ticketService.getTicket(repository, number);
    }

    if (ticket == null) {
        if (number > 0) {
            // requested ticket does not exist
            sendError("Sorry, {0} does not have ticket {1,number,0}!", repository.name, number);
            sendRejection(cmd, "Invalid ticket number");
            return null;
        }
    } else {
        if (ticket.isMerged()) {
            // ticket already merged & resolved
            Change mergeChange = null;
            for (Change change : ticket.changes) {
                if (change.isMerge()) {
                    mergeChange = change;
                    break;
                }
            }
            if (mergeChange != null) {
                sendError("Sorry, {0} already merged {1} from ticket {2,number,0} to {3}!", mergeChange.author,
                        mergeChange.patchset, number, ticket.mergeTo);
            }
            sendRejection(cmd, "Ticket {0,number,0} already resolved", number);
            return null;
        } else if (!StringUtils.isEmpty(ticket.mergeTo)) {
            // ticket specifies integration branch
            branch = ticket.mergeTo;
        }
    }

    final int shortCommitIdLen = settings.getInteger(Keys.web.shortCommitIdLength, 6);
    final String shortTipId = cmd.getNewId().getName().substring(0, shortCommitIdLen);
    final RevCommit tipCommit = JGitUtils.getCommit(getRepository(), cmd.getNewId().getName());
    final String forBranch = branch;
    RevCommit mergeBase = null;
    Ref forBranchRef = getAdvertisedRefs().get(Constants.R_HEADS + forBranch);
    if (forBranchRef == null || forBranchRef.getObjectId() == null) {
        // unknown integration branch
        sendError("Sorry, there is no integration branch named ''{0}''.", forBranch);
        sendRejection(cmd, "Invalid integration branch specified");
        return null;
    } else {
        // determine the merge base for the patchset on the integration branch
        String base = JGitUtils.getMergeBase(getRepository(), forBranchRef.getObjectId(), tipCommit.getId());
        if (StringUtils.isEmpty(base)) {
            sendError("");
            sendError("There is no common ancestry between {0} and {1}.", forBranch, shortTipId);
            sendError("Please reconsider your proposed integration branch, {0}.", forBranch);
            sendError("");
            sendRejection(cmd, "no merge base for patchset and {0}", forBranch);
            return null;
        }
        mergeBase = JGitUtils.getCommit(getRepository(), base);
    }

    // ensure that the patchset can be cleanly merged right now
    MergeStatus status = JGitUtils.canMerge(getRepository(), tipCommit.getName(), forBranch,
            repository.mergeType);
    switch (status) {
    case ALREADY_MERGED:
        sendError("");
        sendError("You have already merged this patchset.", forBranch);
        sendError("");
        sendRejection(cmd, "everything up-to-date");
        return null;
    case MERGEABLE:
        break;
    default:
        if (ticket == null || requireMergeablePatchset) {
            sendError("");
            sendError("Your patchset can not be cleanly merged into {0}.", forBranch);
            sendError("Please rebase your patchset and push again.");
            sendError("NOTE:", number);
            sendError("You should push your rebase to refs/for/{0,number,0}", number);
            sendError("");
            sendError("  git push origin HEAD:refs/for/{0,number,0}", number);
            sendError("");
            sendRejection(cmd, "patchset not mergeable");
            return null;
        }
    }

    // check to see if this commit is already linked to a ticket
    if (ticket != null
            && JGitUtils.getTicketNumberFromCommitBranch(getRepository(), tipCommit) == ticket.number) {
        sendError("{0} has already been pushed to ticket {1,number,0}.", shortTipId, ticket.number);
        sendRejection(cmd, "everything up-to-date");
        return null;
    }

    List<TicketLink> ticketLinks = JGitUtils.identifyTicketsFromCommitMessage(getRepository(), settings,
            tipCommit);

    PatchsetCommand psCmd;
    if (ticket == null) {
        /*
         *  NEW TICKET
         */
        Patchset patchset = newPatchset(null, mergeBase.getName(), tipCommit.getName());

        int minLength = 10;
        int maxLength = 100;
        String minTitle = MessageFormat.format("  minimum length of a title is {0} characters.", minLength);
        String maxTitle = MessageFormat.format("  maximum length of a title is {0} characters.", maxLength);

        if (patchset.commits > 1) {
            sendError("");
            sendError("You may not create a ''{0}'' branch proposal ticket from {1} commits!", forBranch,
                    patchset.commits);
            sendError("");
            // display an ellipsized log of the commits being pushed
            RevWalk walk = getRevWalk();
            walk.reset();
            walk.sort(RevSort.TOPO);
            int boundary = 3;
            int count = 0;
            try {
                walk.markStart(tipCommit);
                walk.markUninteresting(mergeBase);

                for (;;) {

                    RevCommit c = walk.next();
                    if (c == null) {
                        break;
                    }

                    if (count < boundary || count >= (patchset.commits - boundary)) {

                        walk.parseBody(c);
                        sendError("   {0}  {1}", c.getName().substring(0, shortCommitIdLen),
                                StringUtils.trimString(c.getShortMessage(), 60));

                    } else if (count == boundary) {

                        sendError("   ... more commits ...");

                    }

                    count++;
                }

            } catch (IOException e) {
                // Should never happen, the core receive process would have
                // identified the missing object earlier before we got control.
                LOGGER.error("failed to get commit count", e);
            } finally {
                walk.close();
            }

            sendError("");
            sendError("Possible Solutions:");
            sendError("");
            int solution = 1;
            String forSpec = cmd.getRefName().substring(Constants.R_FOR.length());
            if (forSpec.equals("default") || forSpec.equals("new")) {
                try {
                    // determine other possible integration targets
                    List<String> bases = Lists.newArrayList();
                    for (Ref ref : getRepository().getRefDatabase().getRefs(Constants.R_HEADS).values()) {
                        if (!ref.getName().startsWith(Constants.R_TICKET)
                                && !ref.getName().equals(forBranchRef.getName())) {
                            if (JGitUtils.isMergedInto(getRepository(), ref.getObjectId(), tipCommit)) {
                                bases.add(Repository.shortenRefName(ref.getName()));
                            }
                        }
                    }

                    if (!bases.isEmpty()) {

                        if (bases.size() == 1) {
                            // suggest possible integration targets
                            String base = bases.get(0);
                            sendError("{0}. Propose this change for the ''{1}'' branch.", solution++, base);
                            sendError("");
                            sendError("   git push origin HEAD:refs/for/{0}", base);
                            sendError("   pt propose {0}", base);
                            sendError("");
                        } else {
                            // suggest possible integration targets
                            sendError("{0}. Propose this change for a different branch.", solution++);
                            sendError("");
                            for (String base : bases) {
                                sendError("   git push origin HEAD:refs/for/{0}", base);
                                sendError("   pt propose {0}", base);
                                sendError("");
                            }
                        }

                    }
                } catch (IOException e) {
                    LOGGER.error(null, e);
                }
            }
            sendError("{0}. Squash your changes into a single commit with a meaningful message.", solution++);
            sendError("");
            sendError("{0}. Open a ticket for your changes and then push your {1} commits to the ticket.",
                    solution++, patchset.commits);
            sendError("");
            sendError("   git push origin HEAD:refs/for/{id}");
            sendError("   pt propose {id}");
            sendError("");
            sendRejection(cmd, "too many commits");
            return null;
        }

        // require a reasonable title/subject
        String title = tipCommit.getFullMessage().trim().split("\n")[0];
        if (title.length() < minLength) {
            // reject, title too short
            sendError("");
            sendError("Please supply a longer title in your commit message!");
            sendError("");
            sendError(minTitle);
            sendError(maxTitle);
            sendError("");
            sendRejection(cmd, "ticket title is too short [{0}/{1}]", title.length(), maxLength);
            return null;
        }
        if (title.length() > maxLength) {
            // reject, title too long
            sendError("");
            sendError("Please supply a more concise title in your commit message!");
            sendError("");
            sendError(minTitle);
            sendError(maxTitle);
            sendError("");
            sendRejection(cmd, "ticket title is too long [{0}/{1}]", title.length(), maxLength);
            return null;
        }

        // assign new id
        long ticketId = ticketService.assignNewId(repository);

        // create the patchset command
        psCmd = new PatchsetCommand(user.username, patchset);
        psCmd.newTicket(tipCommit, forBranch, ticketId, cmd.getRefName());
    } else {
        /*
         *  EXISTING TICKET
         */
        Patchset patchset = newPatchset(ticket, mergeBase.getName(), tipCommit.getName());
        psCmd = new PatchsetCommand(user.username, patchset);
        psCmd.updateTicket(tipCommit, forBranch, ticket, cmd.getRefName());
    }

    // confirm user can push the patchset
    boolean pushPermitted = ticket == null || !ticket.hasPatchsets() || ticket.isAuthor(user.username)
            || ticket.isPatchsetAuthor(user.username) || ticket.isResponsible(user.username)
            || user.canPush(repository);

    switch (psCmd.getPatchsetType()) {
    case Proposal:
        // proposals (first patchset) are always acceptable
        break;
    case FastForward:
        // patchset updates must be permitted
        if (!pushPermitted) {
            // reject
            sendError("");
            sendError("To push a patchset to this ticket one of the following must be true:");
            sendError("  1. you created the ticket");
            sendError("  2. you created the first patchset");
            sendError("  3. you are specified as responsible for the ticket");
            sendError("  4. you have push (RW) permissions to {0}", repository.name);
            sendError("");
            sendRejection(cmd, "not permitted to push to ticket {0,number,0}", ticket.number);
            return null;
        }
        break;
    default:
        // non-fast-forward push
        if (!pushPermitted) {
            // reject
            sendRejection(cmd, "non-fast-forward ({0})", psCmd.getPatchsetType());
            return null;
        }
        break;
    }

    Change change = psCmd.getChange();
    change.pendingLinks = ticketLinks;

    return psCmd;
}

From source file:com.gitblit.git.PatchsetReceivePack.java

License:Apache License

/**
 * Automatically closes open tickets that have been merged to their integration
 * branch by a client and adds references to tickets if made in the commit message.
 *
 * @param cmd//from   w w  w  . j a  v a  2s .c om
 */
private Collection<TicketModel> processReferencedTickets(ReceiveCommand cmd) {
    Map<Long, TicketModel> mergedTickets = new LinkedHashMap<Long, TicketModel>();
    final RevWalk rw = getRevWalk();
    try {
        rw.reset();
        rw.markStart(rw.parseCommit(cmd.getNewId()));
        if (!ObjectId.zeroId().equals(cmd.getOldId())) {
            rw.markUninteresting(rw.parseCommit(cmd.getOldId()));
        }

        RevCommit c;
        while ((c = rw.next()) != null) {
            rw.parseBody(c);
            List<TicketLink> ticketLinks = JGitUtils.identifyTicketsFromCommitMessage(getRepository(), settings,
                    c);
            if (ticketLinks == null) {
                continue;
            }

            for (TicketLink link : ticketLinks) {

                if (mergedTickets.containsKey(link.targetTicketId)) {
                    continue;
                }

                TicketModel ticket = ticketService.getTicket(repository, link.targetTicketId);
                if (ticket == null) {
                    continue;
                }
                String integrationBranch;
                if (StringUtils.isEmpty(ticket.mergeTo)) {
                    // unspecified integration branch
                    integrationBranch = null;
                } else {
                    // specified integration branch
                    integrationBranch = Constants.R_HEADS + ticket.mergeTo;
                }

                Change change;
                Patchset patchset = null;
                String mergeSha = c.getName();
                String mergeTo = Repository.shortenRefName(cmd.getRefName());

                if (link.action == TicketAction.Commit) {
                    //A commit can reference a ticket in any branch even if the ticket is closed.
                    //This allows developers to identify and communicate related issues
                    change = new Change(user.username);
                    change.referenceCommit(mergeSha);
                } else {
                    // ticket must be open and, if specified, the ref must match the integration branch
                    if (ticket.isClosed()
                            || (integrationBranch != null && !integrationBranch.equals(cmd.getRefName()))) {
                        continue;
                    }

                    String baseRef = PatchsetCommand.getBasePatchsetBranch(ticket.number);
                    boolean knownPatchset = false;
                    Set<Ref> refs = getRepository().getAllRefsByPeeledObjectId().get(c.getId());
                    if (refs != null) {
                        for (Ref ref : refs) {
                            if (ref.getName().startsWith(baseRef)) {
                                knownPatchset = true;
                                break;
                            }
                        }
                    }

                    if (knownPatchset) {
                        // identify merged patchset by the patchset tip
                        for (Patchset ps : ticket.getPatchsets()) {
                            if (ps.tip.equals(mergeSha)) {
                                patchset = ps;
                                break;
                            }
                        }

                        if (patchset == null) {
                            // should not happen - unless ticket has been hacked
                            sendError("Failed to find the patchset for {0} in ticket {1,number,0}?!", mergeSha,
                                    ticket.number);
                            continue;
                        }

                        // create a new change
                        change = new Change(user.username);
                    } else {
                        // new patchset pushed by user
                        String base = cmd.getOldId().getName();
                        patchset = newPatchset(ticket, base, mergeSha);
                        PatchsetCommand psCmd = new PatchsetCommand(user.username, patchset);
                        psCmd.updateTicket(c, mergeTo, ticket, null);

                        // create a ticket patchset ref
                        updateRef(psCmd.getPatchsetBranch(), c.getId(), patchset.type);
                        RefUpdate ru = updateRef(psCmd.getTicketBranch(), c.getId(), patchset.type);
                        updateReflog(ru);

                        // create a change from the patchset command
                        change = psCmd.getChange();
                    }

                    // set the common change data about the merge
                    change.setField(Field.status, Status.Merged);
                    change.setField(Field.mergeSha, mergeSha);
                    change.setField(Field.mergeTo, mergeTo);

                    if (StringUtils.isEmpty(ticket.responsible)) {
                        // unassigned tickets are assigned to the closer
                        change.setField(Field.responsible, user.username);
                    }
                }

                ticket = ticketService.updateTicket(repository, ticket.number, change);

                if (ticket != null) {
                    sendInfo("");
                    sendHeader("#{0,number,0}: {1}", ticket.number,
                            StringUtils.trimString(ticket.title, Constants.LEN_SHORTLOG));

                    switch (link.action) {
                    case Commit: {
                        sendInfo("referenced by push of {0} to {1}", c.getName(), mergeTo);
                    }
                        break;

                    case Close: {
                        sendInfo("closed by push of {0} to {1}", patchset, mergeTo);
                        mergedTickets.put(ticket.number, ticket);
                    }
                        break;

                    default: {

                    }
                    }

                    sendInfo(ticketService.getTicketUrl(ticket));
                    sendInfo("");

                } else {
                    String shortid = mergeSha.substring(0,
                            settings.getInteger(Keys.web.shortCommitIdLength, 6));

                    switch (link.action) {
                    case Commit: {
                        sendError("FAILED to reference ticket {0,number,0} by push of {1}", link.targetTicketId,
                                shortid);
                    }
                        break;
                    case Close: {
                        sendError("FAILED to close ticket {0,number,0} by push of {1}", link.targetTicketId,
                                shortid);
                    }
                        break;

                    default: {

                    }
                    }
                }
            }
        }

    } catch (IOException e) {
        LOGGER.error("Can't scan for changes to reference or close", e);
    } finally {
        rw.reset();
    }

    return mergedTickets.values();
}

From source file:com.gitblit.plugin.flowdock.FlowDockReceiveHook.java

License:Apache License

@Override
public void onPostReceive(GitblitReceivePack receivePack, Collection<ReceiveCommand> commands) {
    if (!shallPost(receivePack, commands)) {
        return;//from   w  ww.  j  a  v  a  2  s .  c  om
    }

    IRuntimeManager runtimeManager = GitblitContext.getManager(IRuntimeManager.class);
    try {
        for (ReceiveCommand cmd : commands) {
            if (cmd.getRefName().startsWith(Constants.R_TAGS)) {
                boolean shallPostTag = runtimeManager.getSettings().getBoolean(Plugin.SETTING_POST_TAGS, true);
                if (!shallPostTag) {
                    continue;
                }
            } else if (cmd.getRefName().startsWith(Constants.R_HEADS)) {
                boolean shallPostBranch = runtimeManager.getSettings().getBoolean(Plugin.SETTING_POST_BRANCHES,
                        true);
                if (!shallPostBranch) {
                    continue;
                }
            } else {
                // ignore other refs
                continue;
            }

            RepositoryModel repo = receivePack.getRepositoryModel();

            String repoUrl = getUrl(repo.name, null, null);
            String diffUrl = getUrl(repo.name, cmd.getOldId().getName(), cmd.getNewId().getName());

            GitPayload payload = new GitPayload().pusher(receivePack.getUserModel()).repository(repo.name)
                    .repoUrl(repoUrl).tags(getTags(repo)).ref(cmd.getRefName())
                    .refName(Repository.shortenRefName(cmd.getRefName())).diffUrl(diffUrl)
                    .before(cmd.getOldId().getName()).after(cmd.getNewId().getName());

            List<RevCommit> commits = getCommits(receivePack, cmd.getOldId().name(), cmd.getNewId().name());
            for (RevCommit commit : commits) {
                Commit c = new Commit();
                c.id = commit.getName();
                c.url = getUrl(repo.name, null, commit.getName());
                c.message = commit.getFullMessage().trim();

                PersonIdent author = commit.getAuthorIdent();
                c.author = new Ident(author.getName(), author.getEmailAddress());
                c.timestamp = author.getWhen();
                if (c.timestamp == null) {
                    c.timestamp = commit.getCommitterIdent().getWhen();
                }

                List<PathChangeModel> paths = JGitUtils.getFilesInCommit(receivePack.getRepository(), commit);
                c.added = filter(paths, ChangeType.ADD);
                c.modified = filter(paths, ChangeType.MODIFY);
                c.removed = filter(paths, ChangeType.DELETE);

                payload.add(c);
            }

            flowdock.setFlow(repo, payload);
            flowdock.sendAsync(payload);
        }
    } catch (Exception e) {
        log.error("Failed to notify FlowDock!", e);
    }
}

From source file:com.gitblit.plugin.glip.GlipReceiveHook.java

License:Apache License

/**
 * Sends a Glip message when a branch or a tag is created.
 *
 * @param receivePack/* www . ja  v a 2  s  .c o  m*/
 * @param cmd
 * @param rType
 */
protected void sendCreate(GitblitReceivePack receivePack, ReceiveCommand cmd, RefType rType)
        throws IOException {
    UserModel user = receivePack.getUserModel();
    RepositoryModel repo = receivePack.getRepositoryModel();
    String shortRef = Repository.shortenRefName(cmd.getRefName());
    String repoUrl = getUrl(repo.name, null, null);
    String logUrl = getUrl(repo.name, shortRef, null);

    String activity = String.format("%s has pushed to %s", user.getDisplayName(),
            StringUtils.stripDotGit(repo.name));

    String msg = String.format("**%s** has created %s [%s](%s) in [%s](%s)", user.getDisplayName(),
            rType.name().toLowerCase(), shortRef, logUrl, StringUtils.stripDotGit(repo.name), repoUrl);

    Payload payload = new Payload().icon(getIconUrl(user)).activity(activity).body(msg);

    glip.setConversation(repo, payload);
    glip.sendAsync(payload);
}

From source file:com.gitblit.plugin.glip.GlipReceiveHook.java

License:Apache License

/**
 * Sends a Glip message when a branch or a tag has been updated.
 *
 * @param receivePack//ww w.  j  ava  2  s  .  c o  m
 * @param cmd
 * @param rType
 * @param isFF
 */
protected void sendUpdate(GitblitReceivePack receivePack, ReceiveCommand cmd, RefType rType, boolean isFF)
        throws IOException {
    UserModel user = receivePack.getUserModel();
    RepositoryModel repo = receivePack.getRepositoryModel();
    String shortRef = Repository.shortenRefName(cmd.getRefName());
    String repoUrl = getUrl(repo.name, null, null);

    String activity = String.format("%s has pushed to %s", user.getDisplayName(),
            StringUtils.stripDotGit(repo.name));

    List<RevCommit> commits = null;
    String action;
    String url;
    switch (rType) {
    case TAG:
        // commit link
        url = getUrl(repo.name, null, shortRef);
        action = "**MOVED** tag";
        break;
    default:
        // log link
        url = getUrl(repo.name, shortRef, null);
        if (isFF) {
            commits = getCommits(receivePack, cmd.getOldId().name(), cmd.getNewId().name());
            if (commits.size() == 1) {
                action = "pushed 1 commit to";
            } else {
                action = String.format("pushed %d commits to", commits.size());
            }
        } else {
            action = "**REWRITTEN**";
        }
        break;
    }

    StringBuilder sb = new StringBuilder();
    String msg = String.format("**%s** has %s [%s](%s) in [%s](%s)", user.getDisplayName(), action, shortRef,
            url, StringUtils.stripDotGit(repo.name), repoUrl);
    sb.append(msg);

    if (commits != null) {
        // abbreviated commit list
        int shortIdLen = receivePack.getGitblit().getSettings().getInteger(Keys.web.shortCommitIdLength, 6);
        int maxCommits = 5;
        sb.append("\n\n");
        for (int i = 0; i < Math.min(maxCommits, commits.size()); i++) {
            RevCommit commit = commits.get(i);
            String username = "";
            String email = "";
            if (commit.getAuthorIdent().getEmailAddress() != null) {
                username = commit.getAuthorIdent().getName();
                email = commit.getAuthorIdent().getEmailAddress().toLowerCase();
                if (StringUtils.isEmpty(username)) {
                    username = email;
                }
            } else {
                username = commit.getAuthorIdent().getName();
                email = username.toLowerCase();
            }
            //            String gravatarUrl = ActivityUtils.getGravatarThumbnailUrl(email, 16);
            String commitUrl = getUrl(repo.name, null, commit.getName());
            String shortId = commit.getName().substring(0, shortIdLen);
            String shortMessage = StringUtils.escapeForHtml(
                    StringUtils.trimString(commit.getShortMessage(), Constants.LEN_SHORTLOG), false);
            //            String row = String.format("|![%s](%s)|[%s](%s)|%s|\n",
            //                  username, gravatarUrl, shortId, commitUrl, shortMessage);
            String row = String.format("|%s|[%s](%s)|%s|\n", username, shortId, commitUrl, shortMessage);
            sb.append(row);
        }
        sb.append("\n");

        // compare link
        if (commits.size() > 1) {
            String compareUrl = getUrl(repo.name, cmd.getOldId().getName(), cmd.getNewId().getName());
            String compareText;
            if (commits.size() > maxCommits) {
                int diff = commits.size() - maxCommits;
                if (diff == 1) {
                    compareText = "1 more commit";
                } else {
                    compareText = String.format("%d more commits", diff);
                }
            } else {
                compareText = String.format("view comparison of these %s commits", commits.size());
            }
            sb.append(String.format("[%s](%s)", compareText, compareUrl));
        }
    }

    Payload payload = new Payload().icon(getIconUrl(user)).activity(activity).body(sb.toString());

    glip.setConversation(repo, payload);
    glip.sendAsync(payload);
}