Example usage for org.eclipse.jgit.lib ObjectId name

List of usage examples for org.eclipse.jgit.lib ObjectId name

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ObjectId name.

Prototype

public final String name() 

Source Link

Document

name.

Usage

From source file:com.creactiviti.piper.core.git.JGitTemplate.java

License:Apache License

private List<IdentifiableResource> getHeadFiles(Repository aRepository, String... aSearchPaths) {
    List<String> searchPaths = Arrays.asList(aSearchPaths);
    List<IdentifiableResource> resources = new ArrayList<>();
    try (ObjectReader reader = aRepository.newObjectReader();
            RevWalk walk = new RevWalk(reader);
            TreeWalk treeWalk = new TreeWalk(aRepository, reader);) {
        final ObjectId id = aRepository.resolve(Constants.HEAD);
        RevCommit commit = walk.parseCommit(id);
        RevTree tree = commit.getTree();
        treeWalk.addTree(tree);//from ww w.j a  va  2  s . c o m
        treeWalk.setRecursive(true);
        while (treeWalk.next()) {
            String path = treeWalk.getPathString();
            if (searchPaths.stream().anyMatch((sp) -> path.startsWith(sp))) {
                ObjectId objectId = treeWalk.getObjectId(0);
                logger.debug("Loading {} [{}]", path, objectId.name());
                resources.add(readBlob(aRepository, path.substring(0, path.indexOf('.')), objectId.name()));
            }
        }
        return resources;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

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

License:Apache License

/** Execute commands to update references. */
@Override/*from  w w  w. j  a  v a  2 s.  co  m*/
protected void executeCommands() {
    List<ReceiveCommand> toApply = filterCommands(Result.NOT_ATTEMPTED);
    if (toApply.isEmpty()) {
        return;
    }

    ProgressMonitor updating = NullProgressMonitor.INSTANCE;
    boolean sideBand = isCapabilityEnabled(CAPABILITY_SIDE_BAND_64K);
    if (sideBand) {
        SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut);
        pm.setDelayStart(250, TimeUnit.MILLISECONDS);
        updating = pm;
    }

    BatchRefUpdate batch = getRepository().getRefDatabase().newBatchUpdate();
    batch.setAllowNonFastForwards(isAllowNonFastForwards());
    batch.setRefLogIdent(getRefLogIdent());
    batch.setRefLogMessage("push", true);

    for (ReceiveCommand cmd : toApply) {
        if (Result.NOT_ATTEMPTED != cmd.getResult()) {
            // Already rejected by the core receive process.
            continue;
        }
        batch.addCommand(cmd);
    }

    if (!batch.getCommands().isEmpty()) {
        try {
            batch.execute(getRevWalk(), updating);
        } catch (IOException err) {
            for (ReceiveCommand cmd : toApply) {
                if (cmd.getResult() == Result.NOT_ATTEMPTED) {
                    sendRejection(cmd, "lock error: {0}", err.getMessage());
                }
            }
        }
    }

    //
    // if there are ref update receive commands that were
    // successfully processed and there is an active ticket service for the repository
    // then process any referenced tickets
    //
    if (ticketService != null) {
        List<ReceiveCommand> allUpdates = ReceiveCommand.filter(batch.getCommands(), Result.OK);
        if (!allUpdates.isEmpty()) {
            int ticketsProcessed = 0;
            for (ReceiveCommand cmd : allUpdates) {
                switch (cmd.getType()) {
                case CREATE:
                case UPDATE:
                    if (cmd.getRefName().startsWith(Constants.R_HEADS)) {
                        Collection<TicketModel> tickets = processReferencedTickets(cmd);
                        ticketsProcessed += tickets.size();
                        for (TicketModel ticket : tickets) {
                            ticketNotifier.queueMailing(ticket);
                        }
                    }
                    break;

                case UPDATE_NONFASTFORWARD:
                    if (cmd.getRefName().startsWith(Constants.R_HEADS)) {
                        String base = JGitUtils.getMergeBase(getRepository(), cmd.getOldId(), cmd.getNewId());
                        List<TicketLink> deletedRefs = JGitUtils.identifyTicketsBetweenCommits(getRepository(),
                                settings, base, cmd.getOldId().name());
                        for (TicketLink link : deletedRefs) {
                            link.isDelete = true;
                        }
                        Change deletion = new Change(user.username);
                        deletion.pendingLinks = deletedRefs;
                        ticketService.updateTicket(repository, 0, deletion);

                        Collection<TicketModel> tickets = processReferencedTickets(cmd);
                        ticketsProcessed += tickets.size();
                        for (TicketModel ticket : tickets) {
                            ticketNotifier.queueMailing(ticket);
                        }
                    }
                    break;
                case DELETE:
                    //Identify if the branch has been merged 
                    SortedMap<Integer, String> bases = new TreeMap<Integer, String>();
                    try {
                        ObjectId dObj = cmd.getOldId();
                        Collection<Ref> tips = getRepository().getRefDatabase().getRefs(Constants.R_HEADS)
                                .values();
                        for (Ref ref : tips) {
                            ObjectId iObj = ref.getObjectId();
                            String mergeBase = JGitUtils.getMergeBase(getRepository(), dObj, iObj);
                            if (mergeBase != null) {
                                int d = JGitUtils.countCommits(getRepository(), getRevWalk(), mergeBase,
                                        dObj.name());
                                bases.put(d, mergeBase);
                                //All commits have been merged into some other branch
                                if (d == 0) {
                                    break;
                                }
                            }
                        }

                        if (bases.isEmpty()) {
                            //TODO: Handle orphan branch case
                        } else {
                            if (bases.firstKey() > 0) {
                                //Delete references from the remaining commits that haven't been merged
                                String mergeBase = bases.get(bases.firstKey());
                                List<TicketLink> deletedRefs = JGitUtils.identifyTicketsBetweenCommits(
                                        getRepository(), settings, mergeBase, dObj.name());

                                for (TicketLink link : deletedRefs) {
                                    link.isDelete = true;
                                }
                                Change deletion = new Change(user.username);
                                deletion.pendingLinks = deletedRefs;
                                ticketService.updateTicket(repository, 0, deletion);
                            }
                        }

                    } catch (IOException e) {
                        LOGGER.error(null, e);
                    }
                    break;

                default:
                    break;
                }
            }

            if (ticketsProcessed == 1) {
                sendInfo("1 ticket updated");
            } else if (ticketsProcessed > 1) {
                sendInfo("{0} tickets updated", ticketsProcessed);
            }
        }

        // reset the ticket caches for the repository
        ticketService.resetCaches(repository);
    }
}

From source file:com.github.gitreport.ReleaseReport.java

License:Open Source License

/**
 * Get name for id/* w  ww.j av a2s . c om*/
 * 
 * @param id
 * @return name
 */
public String getCommitName(ObjectId id) {
    if (linker != null) {
        String url = linker.getCommitUrl(id.name());
        if (url != null) {
            return "<a href=\"" + url + "\">" + id.name() + "</a>";
        }
    }
    return id.name();
}

From source file:com.github.gitreport.ReleaseReport.java

License:Open Source License

/**
 * Get abbreviated name for id// w ww.  j  ava 2 s .  com
 * 
 * @param id
 * @return short name
 */
public String getCommitShortName(ObjectId id) {
    if (linker != null) {
        String url = linker.getCommitUrl(id.name());
        if (url != null) {
            return "<a href=\"" + url + "\">" + id.abbreviate(7).name() + "</a>";
        }
    }
    return id.abbreviate(7).name();
}

From source file:com.github.kevinsawicki.git.reports.ReleaseReport.java

License:Open Source License

/**
 * Get name for id/*w w w.j a va 2s. c o m*/
 *
 * @param id
 * @return name
 */
public String getCommitName(ObjectId id) {
    if (linker != null) {
        String url = linker.getCommitUrl(id.name());
        if (url != null)
            return "<a href=\"" + url + "\">" + id.name() + "</a>";
    }
    return id.name();
}

From source file:com.github.kevinsawicki.git.reports.ReleaseReport.java

License:Open Source License

/**
 * Get abbreviated name for id//from   w  w  w.j  a  v a2s .com
 *
 * @param id
 * @return short name
 */
public String getCommitShortName(ObjectId id) {
    if (linker != null) {
        String url = linker.getCommitUrl(id.name());
        if (url != null)
            return "<a href=\"" + url + "\">" + id.abbreviate(7).name() + "</a>";
    }
    return id.abbreviate(7).name();
}

From source file:com.github.pascalgn.maven.properties.GitProperties.java

License:Apache License

private void addProperties(Map<String, String> map) throws IOException {
    Repository repository = new FileRepositoryBuilder().setWorkTree(new File(".")).readEnvironment()
            .findGitDir().setMustExist(true).build();
    logger.debug("Using git repository: " + repository.getDirectory());

    ObjectId head = repository.resolve("HEAD");
    if (head == null) {
        throw new IllegalStateException("No such revision: HEAD");
    }/*from  www .  j  a v a2s  .  c om*/

    String branch = nullToEmpty(repository.getBranch());
    map.put("git.branch", branch);

    String commitId = head.name();
    map.put("git.commit.id", commitId);

    String commitIdAbbrev = repository.newObjectReader().abbreviate(head).name();
    map.put("git.commit.id.abbrev", commitIdAbbrev);

    RevWalk walk = new RevWalk(repository);
    walk.setRetainBody(false);
    RevCommit headCommit = walk.parseCommit(head);
    int count = RevWalkUtils.count(walk, headCommit, null);
    map.put("git.count", Integer.toString(count));

    String color = commitId.substring(0, 6);
    map.put("git.commit.color.value", color);
    map.put("git.commit.color.name", ColorHelper.getColorName(color));
    map.put("git.commit.color.lightness", Integer.toString(ColorHelper.getLightness(color)));
    map.put("git.commit.color.foreground", ColorHelper.getForeground(color));

    map.put("git.build.datetime.simple", getFormattedDate());
}

From source file:com.google.gerrit.acceptance.git.SubmoduleSubscriptionsIT.java

License:Apache License

@Test

public void testSubmoduleCommitMessage() throws Exception {
    TestRepository<?> superRepo = createProjectWithPush("super-project");
    TestRepository<?> subRepo = createProjectWithPush("subscribed-to-project");

    pushChangeTo(subRepo, "master");
    createSubscription(superRepo, "master", "subscribed-to-project", "master");
    ObjectId subHEAD = pushChangeTo(subRepo, "master");

    // The first update doesn't include the rev log
    RevWalk rw = subRepo.getRevWalk();//from   w  w  w  .j av a2 s .  c  o m
    RevCommit subCommitMsg = rw.parseCommit(subHEAD);
    expectToHaveCommitMessage(superRepo, "master", "Updated git submodules\n\n" + "Project: "
            + name("subscribed-to-project") + " master " + subHEAD.name() + "\n\n");

    // The next commit should generate only its commit message,
    // omitting previous commit logs
    subHEAD = pushChangeTo(subRepo, "master");
    subCommitMsg = rw.parseCommit(subHEAD);
    expectToHaveCommitMessage(superRepo, "master",
            "Updated git submodules\n\n" + "Project: " + name("subscribed-to-project") + " master "
                    + subHEAD.name() + "\n\n" + subCommitMsg.getFullMessage() + "\n\n");
}

From source file:com.google.gerrit.acceptance.rest.change.AbstractSubmit.java

License:Apache License

protected void assertCurrentRevision(String changeId, int expectedNum, ObjectId expectedId) throws Exception {
    ChangeInfo c = get(changeId, CURRENT_REVISION);
    assertThat(c.currentRevision).isEqualTo(expectedId.name());
    assertThat(c.revisions.get(expectedId.name())._number).isEqualTo(expectedNum);
    try (Repository repo = repoManager.openRepository(new Project.NameKey(c.project))) {
        Ref ref = repo.getRef(new PatchSet.Id(new Change.Id(c._number), expectedNum).toRefName());
        assertThat(ref).isNotNull();// w  w w . ja  va 2  s.c o m
        assertThat(ref.getObjectId()).isEqualTo(expectedId);
    }
}

From source file:com.google.gerrit.acceptance.rest.change.AbstractSubmitByRebase.java

License:Apache License

@Test
public void repairChangeStateAfterFailure() throws Exception {
    // In NoteDb-only mode, repo and meta updates are atomic (at least in InMemoryRepository).
    assume().that(notesMigration.disableChangeReviewDb()).isFalse();

    RevCommit initialHead = getRemoteHead();
    PushOneCommit.Result change = createChange("Change 1", "a.txt", "content");
    submit(change.getChangeId());/*from  www .j  a  v a 2  s.c  o  m*/

    RevCommit headAfterFirstSubmit = getRemoteHead();
    testRepo.reset(initialHead);
    PushOneCommit.Result change2 = createChange("Change 2", "b.txt", "other content");
    Change.Id id2 = change2.getChange().getId();
    SubmitInput failAfterRefUpdates = new TestSubmitInput(new SubmitInput(), true);
    submit(change2.getChangeId(), failAfterRefUpdates, ResourceConflictException.class,
            "Failing after ref updates");
    RevCommit headAfterFailedSubmit = getRemoteHead();

    // Bad: ref advanced but change wasn't updated.
    PatchSet.Id psId1 = new PatchSet.Id(id2, 1);
    PatchSet.Id psId2 = new PatchSet.Id(id2, 2);
    ChangeInfo info = gApi.changes().id(id2.get()).get();
    assertThat(info.status).isEqualTo(ChangeStatus.NEW);
    assertThat(info.revisions.get(info.currentRevision)._number).isEqualTo(1);
    assertThat(getPatchSet(psId2)).isNull();

    ObjectId rev2;
    try (Repository repo = repoManager.openRepository(project); RevWalk rw = new RevWalk(repo)) {
        ObjectId rev1 = repo.exactRef(psId1.toRefName()).getObjectId();
        assertThat(rev1).isNotNull();

        rev2 = repo.exactRef(psId2.toRefName()).getObjectId();
        assertThat(rev2).isNotNull();
        assertThat(rev2).isNotEqualTo(rev1);
        assertThat(rw.parseCommit(rev2).getParent(0)).isEqualTo(headAfterFirstSubmit);

        assertThat(repo.exactRef("refs/heads/master").getObjectId()).isEqualTo(rev2);
    }

    submit(change2.getChangeId());
    RevCommit headAfterSecondSubmit = getRemoteHead();
    assertThat(headAfterSecondSubmit).isEqualTo(headAfterFailedSubmit);

    // Change status and patch set entities were updated, and branch tip stayed
    // the same.
    info = gApi.changes().id(id2.get()).get();
    assertThat(info.status).isEqualTo(ChangeStatus.MERGED);
    assertThat(info.revisions.get(info.currentRevision)._number).isEqualTo(2);
    PatchSet ps2 = getPatchSet(psId2);
    assertThat(ps2).isNotNull();
    assertThat(ps2.getRevision().get()).isEqualTo(rev2.name());
    assertThat(Iterables.getLast(info.messages).message).isEqualTo(
            "Change has been successfully rebased and submitted as " + rev2.name() + " by Administrator");

    try (Repository repo = repoManager.openRepository(project)) {
        assertThat(repo.exactRef("refs/heads/master").getObjectId()).isEqualTo(rev2);
    }

    assertRefUpdatedEvents(initialHead, headAfterFirstSubmit);
    assertChangeMergedEvents(change.getChangeId(), headAfterFirstSubmit.name(), change2.getChangeId(),
            headAfterSecondSubmit.name());
}