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

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

Introduction

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

Prototype

public final String getName() 

Source Link

Document

Get string form of the SHA-1, in lower case hexadecimal.

Usage

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

License:Open Source License

@Test
public void given_filesystem_when_askingChangesSinceNewRevision_then_changesArePopulatedButEmpty()
        throws Exception {
    File gitDir = new File(".");
    GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("git").getClient();

    ObjectId git260 = client.revParse("git-2.6.0");
    AbstractGitSCMSource.SCMRevisionImpl rev261 = new AbstractGitSCMSource.SCMRevisionImpl(
            new SCMHead("origin"), git260.getName());
    GitSCMFileSystem instance = new GitSCMFileSystem(client, "origin", git260.getName(), rev261);

    ObjectId git261 = client.revParse("git-2.6.1");
    AbstractGitSCMSource.SCMRevisionImpl rev260 = new AbstractGitSCMSource.SCMRevisionImpl(
            new SCMHead("origin"), git261.getName());
    GitSCMFileSystem gitPlugin300FS = new GitSCMFileSystem(client, "origin", git261.getName(), rev260);
    assertEquals(git261.getName(), gitPlugin300FS.getRevision().getHash());

    assertThat(git261, not(is(git260)));

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    assertTrue(instance.changesSince(rev260, out));
    assertThat(out.toString(), is(""));
}

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;
    if (StringUtils.isBlank(baseHash)) {
        try {//from   w ww .j a  va  2  s  . c  om
            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
}

From source file:net.erdfelt.android.sdkfido.git.internal.GitInfo.java

License:Apache License

public static void infoObjectId(Repository db, ObjectId oid) throws IOException {
    System.out.printf("ObjectID: %s%n", oid.getName());
    ObjectLoader or = db.open(oid);//  w  w  w .j  a va  2 s  . c  o m
    if (or == null) {
        System.out.println("  Object not found!");
    }
    System.out.printf("  .type: %s%n", asObjectType(or.getType()));
    System.out.printf("  .size: %,d%n", or.getSize());
}

From source file:net.fatlenny.datacitation.service.GitCitationDBService.java

License:Apache License

private TableModel retrieveDatasetForQuery(String directory, String query, ObjectId head)
        throws CitationDBException {

    try (Connection conn = getCSVConnection(directory)) {
        Statement stmt = conn.createStatement();
        ResultSet set = stmt.executeQuery(query);
        ResultSetMetaData metaData = set.getMetaData();
        int columnCount = metaData.getColumnCount();

        String[] columns = new String[columnCount];
        for (int i = 1; i <= columnCount; i++) {
            columns[i - 1] = metaData.getColumnName(i);
        }/*from  w  w  w.  j  a v  a 2  s. c om*/

        TableModelMetaData tableMetaData = new DefaultTableModelMetaData(new DefaultRevision(head.getName()));
        DefaultTableModel model = new DefaultTableModel(tableMetaData, Arrays.asList(columns));

        while (set.next()) {
            String[] row = new String[columnCount];
            for (int i = 1; i <= columnCount; i++) {
                row[i - 1] = (String) set.getObject(i);

            }
            model.addRow(row);
        }

        return model;
    } catch (SQLException e) {
        throw new CitationDBException(e);
    }
}

From source file:org.ajoberstar.reckon.core.git.GitInventorySupplier.java

License:Apache License

@Override
public VcsInventory getInventory() {
    try (RevWalk walk = new RevWalk(repo)) {
        walk.setRetainBody(false);/*from  www .ja v a 2 s  .com*/

        ObjectId headObjectId = repo.getRefDatabase().getRef("HEAD").getObjectId();

        if (headObjectId == null) {
            logger.debug("No HEAD commit. Presuming repo is empty.");
            return new VcsInventory(null, null, null, null, 0, null, null);
        }

        logger.debug("Found HEAD commit {}", headObjectId);

        RevCommit headCommit = walk.parseCommit(headObjectId);

        Set<TaggedVersion> taggedVersions = getTaggedVersions(walk);

        logger.debug("Found tagged versions: {}", taggedVersions);

        Version currentVersion = findCurrent(headCommit, taggedVersions.stream()).map(TaggedVersion::getVersion)
                .orElse(null);
        TaggedVersion baseNormal = findBase(walk, headCommit,
                taggedVersions.stream().filter(TaggedVersion::isNormal));
        TaggedVersion baseVersion = findBase(walk, headCommit, taggedVersions.stream());

        int commitsSinceBase = RevWalkUtils.count(walk, headCommit, baseNormal.getCommit());

        Set<TaggedVersion> parallelCandidates = findParallelCandidates(walk, headCommit, taggedVersions);

        Set<RevCommit> taggedCommits = taggedVersions.stream().map(TaggedVersion::getCommit)
                .collect(Collectors.toSet());
        Set<Version> parallelVersions = parallelCandidates.stream()
                .map(version -> findParallel(walk, headCommit, version, taggedCommits))
                // TODO Java 9 Optional::stream
                .flatMap(opt -> opt.isPresent() ? Stream.of(opt.get()) : Stream.empty())
                .collect(Collectors.toSet());

        Set<Version> claimedVersions = taggedVersions.stream().map(TaggedVersion::getVersion)
                .collect(Collectors.toSet());

        return new VcsInventory(headObjectId.getName(), currentVersion, baseVersion.getVersion(),
                baseNormal.getVersion(), commitsSinceBase, parallelVersions, claimedVersions);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.apache.nifi.registry.provider.flow.git.GitFlowMetaData.java

License:Apache License

@SuppressWarnings("unchecked")
private void loadFlows(RevCommit commit, boolean isLatestCommit, Bucket bucket, String backetFilePath,
        Map<String, Object> flows, Map<String, ObjectId> flowSnapshotObjectIds) {
    for (String flowId : flows.keySet()) {
        final Map<String, Object> flowMeta = (Map<String, Object>) flows.get(flowId);

        if (!validateRequiredValue(flowMeta, backetFilePath + ":" + flowId, VER, FILE)) {
            continue;
        }/*w w w  .j av a  2s.c  o  m*/

        final Flow flow;
        if (isLatestCommit) {
            // If this is the latest commit, then create one.
            flow = bucket.getFlowOrCreate(flowId);
        } else {
            // Otherwise non-existing flow means it's already deleted.
            final Optional<Flow> flowOpt = bucket.getFlow(flowId);
            if (flowOpt.isPresent()) {
                flow = flowOpt.get();
            } else {
                logger.debug("Flow {} does not exist in bucket {}:{} any longer. It may have been deleted.",
                        flowId, bucket.getBucketDirName(), bucket.getBucketId());
                continue;
            }
        }

        final int version = (int) flowMeta.get(VER);
        final String flowSnapshotFilename = (String) flowMeta.get(FILE);

        // Since commits are read in LIFO order, avoid old commits overriding the latest pointer.
        if (!flow.hasVersion(version)) {
            final Flow.FlowPointer pointer = new Flow.FlowPointer(flowSnapshotFilename);
            final File flowSnapshotFile = new File(new File(backetFilePath).getParent(), flowSnapshotFilename);
            final ObjectId objectId = flowSnapshotObjectIds.get(flowSnapshotFile.getPath());
            if (objectId == null) {
                logger.warn(
                        "Git object id for Flow {} version {} with path {} in bucket {}:{} was not found. Ignoring this entry.",
                        flowId, version, flowSnapshotFile.getPath(), bucket.getBucketDirName(),
                        bucket.getBucketId());
                continue;
            }
            pointer.setGitRev(commit.getName());
            pointer.setObjectId(objectId.getName());

            if (flowMeta.containsKey(FLOW_NAME)) {
                pointer.setFlowName((String) flowMeta.get(FLOW_NAME));
            }
            if (flowMeta.containsKey(FLOW_DESC)) {
                pointer.setFlowDescription((String) flowMeta.get(FLOW_DESC));
            }
            if (flowMeta.containsKey(AUTHOR)) {
                pointer.setAuthor((String) flowMeta.get(AUTHOR));
            }
            if (flowMeta.containsKey(COMMENTS)) {
                pointer.setComment((String) flowMeta.get(COMMENTS));
            }
            if (flowMeta.containsKey(CREATED)) {
                pointer.setCreated((long) flowMeta.get(CREATED));
            }

            flow.putVersion(version, pointer);
        }
    }
}

From source file:org.apache.zeppelin.notebook.repo.GitNotebookRepo.java

License:Apache License

/**
 * the idea is to:/*  w ww . j  a v  a2 s.c om*/
 * 1. stash current changes
 * 2. remember head commit and checkout to the desired revision
 * 3. get note and checkout back to the head
 * 4. apply stash on top and remove it
 */
@Override
public synchronized Note get(String noteId, String notePath, String revId, AuthenticationInfo subject)
        throws IOException {
    Note note = null;
    RevCommit stash = null;
    String noteFileName = buildNoteFileName(noteId, notePath);
    try {
        List<DiffEntry> gitDiff = git.diff().setPathFilter(PathFilter.create(noteFileName)).call();
        boolean modified = !gitDiff.isEmpty();
        if (modified) {
            // stash changes
            stash = git.stashCreate().call();
            Collection<RevCommit> stashes = git.stashList().call();
            LOGGER.debug("Created stash : {}, stash size : {}", stash, stashes.size());
        }
        ObjectId head = git.getRepository().resolve(Constants.HEAD);
        // checkout to target revision
        git.checkout().setStartPoint(revId).addPath(noteFileName).call();
        // get the note
        note = super.get(noteId, notePath, subject);
        // checkout back to head
        git.checkout().setStartPoint(head.getName()).addPath(noteFileName).call();
        if (modified && stash != null) {
            // unstash changes
            ObjectId applied = git.stashApply().setStashRef(stash.getName()).call();
            ObjectId dropped = git.stashDrop().setStashRef(0).call();
            Collection<RevCommit> stashes = git.stashList().call();
            LOGGER.debug("Stash applied as : {}, and dropped : {}, stash size: {}", applied, dropped,
                    stashes.size());
        }
    } catch (GitAPIException e) {
        LOGGER.error("Failed to return note from revision \"{}\"", revId, e);
    }
    return note;
}

From source file:org.apache.zeppelin.notebook.repo.OldGitNotebookRepo.java

License:Apache License

/**
 * the idea is to:// ww  w .  j a v  a 2s  .c  o m
 * 1. stash current changes
 * 2. remember head commit and checkout to the desired revision
 * 3. get note and checkout back to the head
 * 4. apply stash on top and remove it
 */
@Override
public synchronized Note get(String noteId, String revId, AuthenticationInfo subject) throws IOException {
    Note note = null;
    RevCommit stash = null;
    try {
        List<DiffEntry> gitDiff = git.diff().setPathFilter(PathFilter.create(noteId)).call();
        boolean modified = !gitDiff.isEmpty();
        if (modified) {
            // stash changes
            stash = git.stashCreate().call();
            Collection<RevCommit> stashes = git.stashList().call();
            LOG.debug("Created stash : {}, stash size : {}", stash, stashes.size());
        }
        ObjectId head = git.getRepository().resolve(Constants.HEAD);
        // checkout to target revision
        git.checkout().setStartPoint(revId).addPath(noteId).call();
        // get the note
        note = super.get(noteId, subject);
        // checkout back to head
        git.checkout().setStartPoint(head.getName()).addPath(noteId).call();
        if (modified && stash != null) {
            // unstash changes
            ObjectId applied = git.stashApply().setStashRef(stash.getName()).call();
            ObjectId dropped = git.stashDrop().setStashRef(0).call();
            Collection<RevCommit> stashes = git.stashList().call();
            LOG.debug("Stash applied as : {}, and dropped : {}, stash size: {}", applied, dropped,
                    stashes.size());
        }
    } catch (GitAPIException e) {
        LOG.error("Failed to return note from revision \"{}\"", revId, e);
    }
    return note;
}

From source file:org.cicomponents.git.impl.LatestRevisionGitBranchMonitor.java

License:Mozilla Public License

@SneakyThrows
protected void emitRevisionIfNecessary(RefsChangedEvent event) {
    synchronized (git) {
        ObjectId newHead = event.getRepository().findRef("refs/heads/" + branch).getObjectId();
        if (!newHead.equals(head)) {
            log.info("Detected refs change for {}, branch {}, old: {}, new: {}", git, branch, head, newHead);
            WorkingDirectory workingDirectory = getWorkingDirectory();
            String directory = workingDirectory.getDirectory() + "/git";
            Git clone = Git.cloneRepository()
                    .setURI("file://" + git.getRepository().getDirectory().getAbsolutePath())
                    .setDirectory(new File(directory)).call();
            Ref checkedOutRef = clone.checkout().setName(newHead.getName()).call();
            assert checkedOutRef == newHead;
            GitRevision resource = new LocalGitRevision(clone, newHead, workingDirectory);
            ResourceHolder<GitRevision> holder = new SimpleResourceHolder<>(resource);
            emit(holder);/*from   w w  w  .  ja v  a 2s  . c  om*/
            head = newHead;
            persistentMap.put(head.getName(), head.getName());
        }
    }
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public List<RepoOperationTO> getOperations(String site, String commitIdFrom, String commitIdTo) {
    List<RepoOperationTO> operations = new ArrayList<>();

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        try {//  w w w  . j a v a2s .  c  o  m
            // Get the sandbox repo, and then get a reference to the commitId we received and another for head
            Repository repo = helper.getRepository(site, SANDBOX);
            ObjectId objCommitIdFrom = repo.resolve(commitIdFrom);
            ObjectId objCommitIdTo = repo.resolve(commitIdTo);

            // If the commitIdFrom is the same as commitIdTo, there is nothing to calculate, otherwise, let's do it
            if (!objCommitIdFrom.equals(objCommitIdTo)) {
                // Compare HEAD with commitId we're given
                // Get list of commits between commitId and HEAD in chronological order
                try (Git git = new Git(repo)) {
                    // Get the log of all the commits between commitId and head
                    Iterable<RevCommit> commits = git.log().addRange(objCommitIdFrom, objCommitIdTo).call();

                    // Loop through through the commits and diff one from the next util head
                    ObjectId prevCommitId = objCommitIdFrom;
                    ObjectId nextCommitId = objCommitIdFrom;

                    Iterator<RevCommit> iterator = commits.iterator();
                    while (iterator.hasNext()) {
                        RevCommit commit = iterator.next();
                        nextCommitId = commit.getId();

                        RevTree prevTree = helper.getTreeForCommit(repo, prevCommitId.getName());
                        RevTree nextTree = helper.getTreeForCommit(repo, nextCommitId.getName());

                        try (ObjectReader reader = repo.newObjectReader()) {
                            CanonicalTreeParser prevCommitTreeParser = new CanonicalTreeParser();
                            CanonicalTreeParser nextCommitTreeParser = new CanonicalTreeParser();
                            prevCommitTreeParser.reset(reader, prevTree.getId());
                            nextCommitTreeParser.reset(reader, nextTree.getId());

                            // Diff the two commit Ids
                            List<DiffEntry> diffEntries = git.diff().setOldTree(prevCommitTreeParser)
                                    .setNewTree(nextCommitTreeParser).call();

                            // Now that we have a diff, let's itemize the file changes, pack them into a TO
                            // and add them to the list of RepoOperations to return to the caller
                            // also include date/time of commit by taking number of seconds and multiply by 1000 and
                            // convert to java date before sending over
                            operations.addAll(
                                    processDiffEntry(diffEntries, new Date(commit.getCommitTime() * 1000)));
                            prevCommitId = nextCommitId;
                        }
                    }
                } catch (GitAPIException e) {
                    logger.error("Error getting operations for site " + site + " from commit ID: "
                            + commitIdFrom + " to commit ID: " + commitIdTo, e);
                }
            }
        } catch (IOException e) {
            logger.error("Error getting operations for site " + site + " from commit ID: " + commitIdFrom
                    + " to commit ID: " + commitIdTo, e);
        }
    }

    return operations;
}