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

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

Introduction

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

Prototype

@NonNull
public ObjectReader newObjectReader() 

Source Link

Document

Create a new reader to read objects from #getObjectDatabase() .

Usage

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

License:Apache License

@SuppressWarnings("unchecked")
private void loadBuckets(Repository gitRepo, RevCommit commit, boolean isLatestCommit,
        Map<String, ObjectId> bucketObjectIds, Map<String, ObjectId> flowSnapshotObjectIds) throws IOException {
    final Yaml yaml = new Yaml();
    for (String bucketFilePath : bucketObjectIds.keySet()) {
        final ObjectId bucketObjectId = bucketObjectIds.get(bucketFilePath);
        final Map<String, Object> bucketMeta;
        try (InputStream bucketIn = gitRepo.newObjectReader().open(bucketObjectId).openStream()) {
            bucketMeta = yaml.load(bucketIn);
        }//from w  w  w  . j  a v  a 2 s. c  om

        if (!validateRequiredValue(bucketMeta, bucketFilePath, LAYOUT_VERSION, BUCKET_ID, FLOWS)) {
            continue;
        }

        int layoutVersion = (int) bucketMeta.get(LAYOUT_VERSION);
        if (layoutVersion > CURRENT_LAYOUT_VERSION) {
            logger.warn("{} has unsupported {} {}. This Registry can only support {} or lower. Skipping it.",
                    bucketFilePath, LAYOUT_VERSION, layoutVersion, CURRENT_LAYOUT_VERSION);
            continue;
        }

        final String bucketId = (String) bucketMeta.get(BUCKET_ID);

        final Bucket bucket;
        if (isLatestCommit) {
            // If this is the latest commit, then create one.
            bucket = getBucketOrCreate(bucketId);
        } else {
            // Otherwise non-existing bucket means it's already deleted.
            final Optional<Bucket> bucketOpt = getBucket(bucketId);
            if (bucketOpt.isPresent()) {
                bucket = bucketOpt.get();
            } else {
                logger.debug("Bucket {} does not exist any longer. It may have been deleted.", bucketId);
                continue;
            }
        }

        // Since the bucketName is restored from pathname, it can be different from the original bucket name when it sanitized.
        final String bucketDirName = bucketFilePath.substring(0, bucketFilePath.lastIndexOf("/"));

        // Since commits are read in LIFO order, avoid old commits overriding the latest bucket name.
        if (isEmpty(bucket.getBucketDirName())) {
            bucket.setBucketDirName(bucketDirName);
        }

        final Map<String, Object> flows = (Map<String, Object>) bucketMeta.get(FLOWS);
        loadFlows(commit, isLatestCommit, bucket, bucketFilePath, flows, flowSnapshotObjectIds);
    }
}

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

From source file:org.dstadler.jgit.porcelain.ShowBranchDiff.java

License:Apache License

private static AbstractTreeIterator prepareTreeParser(Repository repository, String ref) throws IOException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    Ref head = repository.exactRef(ref);
    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(head.getObjectId());
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
        try (ObjectReader oldReader = repository.newObjectReader()) {
            oldTreeParser.reset(oldReader, tree.getId());
        }// w ww. j ava  2 s .co m

        walk.dispose();

        return oldTreeParser;
    }
}

From source file:org.dstadler.jgit.porcelain.ShowFileDiff.java

License:Apache License

private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId)
        throws IOException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    //noinspection Duplicates
    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(ObjectId.fromString(objectId));
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
        try (ObjectReader oldReader = repository.newObjectReader()) {
            oldTreeParser.reset(oldReader, tree.getId());
        }/*from  w  ww.j  a v  a 2  s .c  o m*/

        walk.dispose();

        return oldTreeParser;
    }
}

From source file:org.eclipse.egit.core.internal.rebase.RebaseInteractivePlan.java

License:Open Source License

private void reparsePlan(Repository repository) {
    if (repository != null) {
        try (RevWalk walk = new RevWalk(repository.newObjectReader())) {
            doneList = parseDone(repository, walk);
            todoList = parseTodo(repository, walk);
        }//from  w  ww  . j a v a2s. c  om
        planList = JoinedList.wrap(doneList, todoList);
        notifyPlanWasUpdatedFromRepository();
    }
}

From source file:org.eclipse.egit.ui.internal.dialogs.CompareTreeView.java

License:Open Source License

private void buildMaps(Repository repository, RevCommit baseCommit, RevCommit compareCommit,
        IProgressMonitor monitor) throws InterruptedException, IOException {
    monitor.beginTask(UIText.CompareTreeView_AnalyzingRepositoryTaskText, IProgressMonitor.UNKNOWN);
    boolean useIndex = compareVersion.equals(INDEX_VERSION);
    deletedPaths.clear();/*from   ww w.  j  a v a 2  s .  c  o m*/
    equalContentPaths.clear();
    baseVersionMap.clear();
    compareVersionMap.clear();
    compareVersionPathsWithChildren.clear();
    addedPaths.clear();
    baseVersionPathsWithChildren.clear();
    boolean checkIgnored = false;
    TreeWalk tw = new TreeWalk(repository);
    try {
        int baseTreeIndex;
        if (baseCommit == null) {
            checkIgnored = true;
            baseTreeIndex = tw.addTree(
                    new AdaptableFileTreeIterator(repository, ResourcesPlugin.getWorkspace().getRoot()));
        } else
            baseTreeIndex = tw
                    .addTree(new CanonicalTreeParser(null, repository.newObjectReader(), baseCommit.getTree()));
        int compareTreeIndex;
        if (!useIndex)
            compareTreeIndex = tw.addTree(
                    new CanonicalTreeParser(null, repository.newObjectReader(), compareCommit.getTree()));
        else
            compareTreeIndex = tw.addTree(new DirCacheIterator(repository.readDirCache()));

        if (input instanceof IResource[]) {
            IResource[] resources = (IResource[]) input;
            List<TreeFilter> orFilters = new ArrayList<TreeFilter>(resources.length);

            for (IResource resource : resources) {
                String relPath = repositoryMapping.getRepoRelativePath(resource);
                if (relPath.length() > 0)
                    orFilters.add(PathFilter.create(relPath));
            }
            if (checkIgnored) {
                if (orFilters.size() > 1) {
                    TreeFilter andFilter = AndTreeFilter.create(new NotIgnoredFilter(baseTreeIndex),
                            OrTreeFilter.create(orFilters));
                    tw.setFilter(andFilter);
                } else if (orFilters.size() == 1) {
                    TreeFilter andFilter = AndTreeFilter.create(new NotIgnoredFilter(baseTreeIndex),
                            orFilters.get(0));
                    tw.setFilter(andFilter);
                } else
                    tw.setFilter(new NotIgnoredFilter(baseTreeIndex));

            } else if (orFilters.size() > 1)
                tw.setFilter(OrTreeFilter.create(orFilters));
            else if (orFilters.size() == 1)
                tw.setFilter(orFilters.get(0));
        }

        tw.setRecursive(true);

        if (monitor.isCanceled())
            throw new InterruptedException();
        while (tw.next()) {
            if (monitor.isCanceled())
                throw new InterruptedException();
            AbstractTreeIterator compareVersionIterator = tw.getTree(compareTreeIndex,
                    AbstractTreeIterator.class);
            AbstractTreeIterator baseVersionIterator = tw.getTree(baseTreeIndex, AbstractTreeIterator.class);
            if (compareVersionIterator != null && baseVersionIterator != null) {
                monitor.setTaskName(baseVersionIterator.getEntryPathString());
                IPath currentPath = new Path(baseVersionIterator.getEntryPathString());
                if (!useIndex)
                    compareVersionMap.put(currentPath, GitFileRevision.inCommit(repository, compareCommit,
                            baseVersionIterator.getEntryPathString(), tw.getObjectId(compareTreeIndex)));
                else
                    compareVersionMap.put(currentPath,
                            GitFileRevision.inIndex(repository, baseVersionIterator.getEntryPathString()));
                if (baseCommit != null)
                    baseVersionMap.put(currentPath, GitFileRevision.inCommit(repository, baseCommit,
                            baseVersionIterator.getEntryPathString(), tw.getObjectId(baseTreeIndex)));
                boolean equalContent = compareVersionIterator.getEntryObjectId()
                        .equals(baseVersionIterator.getEntryObjectId());
                if (equalContent)
                    equalContentPaths.add(currentPath);

                if (equalContent && !showEquals)
                    continue;

                while (currentPath.segmentCount() > 0) {
                    currentPath = currentPath.removeLastSegments(1);
                    if (!baseVersionPathsWithChildren.add(currentPath))
                        break;
                }

            } else if (baseVersionIterator != null && compareVersionIterator == null) {
                monitor.setTaskName(baseVersionIterator.getEntryPathString());
                // only on base side
                IPath currentPath = new Path(baseVersionIterator.getEntryPathString());
                addedPaths.add(currentPath);
                if (baseCommit != null)
                    baseVersionMap.put(currentPath, GitFileRevision.inCommit(repository, baseCommit,
                            baseVersionIterator.getEntryPathString(), tw.getObjectId(baseTreeIndex)));
                while (currentPath.segmentCount() > 0) {
                    currentPath = currentPath.removeLastSegments(1);
                    if (!baseVersionPathsWithChildren.add(currentPath))
                        break;
                }

            } else if (compareVersionIterator != null && baseVersionIterator == null) {
                monitor.setTaskName(compareVersionIterator.getEntryPathString());
                // only on compare side
                IPath currentPath = new Path(compareVersionIterator.getEntryPathString());
                deletedPaths.add(currentPath);
                List<PathNodeAdapter> children = compareVersionPathsWithChildren
                        .get(currentPath.removeLastSegments(1));
                if (children == null) {
                    children = new ArrayList<PathNodeAdapter>(1);
                    compareVersionPathsWithChildren.put(currentPath.removeLastSegments(1), children);
                }
                children.add(new PathNodeAdapter(new PathNode(currentPath, Type.FILE_DELETED)));

                if (!useIndex)
                    compareVersionMap.put(currentPath, GitFileRevision.inCommit(repository, compareCommit,
                            compareVersionIterator.getEntryPathString(), tw.getObjectId(compareTreeIndex)));
                else
                    compareVersionMap.put(currentPath,
                            GitFileRevision.inIndex(repository, compareVersionIterator.getEntryPathString()));
            }
        }
    } finally {
        tw.release();
        monitor.done();
    }
}

From source file:org.eclipse.egit.ui.internal.history.FileDiff.java

License:Open Source License

/**
 * Creates a textual diff together with meta information.
 * TODO So far this works only in case of one parent commit.
 *
 * @param d/*from  w  w  w  .  ja  va  2 s .c  o m*/
 *            the StringBuilder where the textual diff is added to
 * @param db
 *            the Repo
 * @param diffFmt
 *            the DiffFormatter used to create the textual diff
 * @param gitFormat
 *            if false, do not show any source or destination prefix,
 *            and the paths are calculated relative to the eclipse
 *            project, otherwise relative to the git repository
 * @throws IOException
 */
public void outputDiff(final StringBuilder d, final Repository db, final DiffFormatter diffFmt,
        boolean gitFormat) throws IOException {
    if (gitFormat) {
        diffFmt.setRepository(db);
        diffFmt.format(diffEntry);
        return;
    }

    ObjectReader reader = db.newObjectReader();
    try {
        outputEclipseDiff(d, db, reader, diffFmt);
    } finally {
        reader.release();
    }
}

From source file:org.eclipse.egit.ui.internal.merge.MergeResultDialog.java

License:Open Source License

/**
 * @param parentShell/*www .ja va2  s  . co  m*/
 * @param repository
 * @param mergeResult
 */
public MergeResultDialog(Shell parentShell, Repository repository, MergeResult mergeResult) {
    super(parentShell);
    setShellStyle(getShellStyle() | SWT.RESIZE);
    this.repository = repository;
    this.mergeResult = mergeResult;
    objectReader = repository.newObjectReader();
}

From source file:org.eclipse.egit.ui.internal.push.PushResultTable.java

License:Open Source License

void setData(final Repository localDb, final PushOperationResult result) {
    reader = localDb.newObjectReader();
    abbrevations = new HashMap<ObjectId, String>();

    // We have to recreate columns.
    for (final TableColumn tc : tableViewer.getTable().getColumns())
        tc.dispose();/*  w w  w. j av  a 2 s.c  o  m*/
    // Set empty result for a while.
    tableViewer.setInput(null);

    // Layout should be recreated to work properly.
    final TableColumnLayout layout = new TableColumnLayout();
    tablePanel.setLayout(layout);

    final TableViewerColumn modeViewer = createColumn(layout, UIText.PushResultTable_columnMode,
            COLUMN_MODE_WEIGHT, SWT.CENTER);
    modeViewer.setLabelProvider(new CenteredImageLabelProvider() {
        @Override
        public Image getImage(Object element) {
            if (((RefUpdateElement) element).isDelete())
                return imageRegistry.get(IMAGE_DELETE);
            return imageRegistry.get(IMAGE_ADD);
        }

        @Override
        public String getToolTipText(Object element) {
            if (((RefUpdateElement) element).isDelete())
                return UIText.RefSpecPanel_modeDeleteDescription;
            return UIText.RefSpecPanel_modeUpdateDescription;
        }
    });

    final TableViewerColumn srcViewer = createColumn(layout, UIText.PushResultTable_columnSrc,
            COLUMN_SRC_WEIGHT, SWT.LEFT);
    srcViewer.setLabelProvider(new ColumnLabelProvider() {
        @Override
        public String getText(Object element) {
            return ((RefUpdateElement) element).getSrcRefName();
        }
    });

    final TableViewerColumn dstViewer = createColumn(layout, UIText.PushResultTable_columnDst,
            COLUMN_DST_WEIGHT, SWT.LEFT);
    dstViewer.setLabelProvider(new ColumnLabelProvider() {
        @Override
        public String getText(Object element) {
            return ((RefUpdateElement) element).getDstRefName();
        }
    });

    if (result == null) {
        tablePanel.layout();
        return;
    }

    int i = 0;
    for (final URIish uri : result.getURIs()) {
        final TableViewerColumn statusViewer = createColumn(layout,
                NLS.bind(UIText.PushResultTable_columnStatusRepo, Integer.toString(++i)), COLUMN_STATUS_WEIGHT,
                SWT.LEFT);
        statusViewer.getColumn().setToolTipText(uri.toString());
        statusViewer.setLabelProvider(new UpdateStatusLabelProvider(uri));
    }
    tableViewer.setInput(result);
    // select the first row of table to get the details of the first
    // push result shown in the Text control
    Table table = tableViewer.getTable();
    if (table.getItemCount() > 0) {
        tableViewer.setSelection(new StructuredSelection(table.getItem(0).getData()));
    }
    tablePanel.layout();
}

From source file:org.eclipse.emf.compare.git.pgm.internal.app.AbstractLogicalApplication.java

License:Open Source License

/**
 * Gets the tree iterator of the id located in the repository.
 * /*from  w w w  .ja  va2  s .  c om*/
 * @param repository
 *            the repository containing the id.
 * @param id
 *            the id for which we want the tree iterator.
 * @return the tree iterator of the id located in the repository.
 * @throws IOException
 */
protected AbstractTreeIterator getTreeIterator(Repository repository, ObjectId id) throws IOException {
    final CanonicalTreeParser p = new CanonicalTreeParser();
    final ObjectReader or = repository.newObjectReader();
    try {
        p.reset(or, new RevWalk(repository).parseTree(id));
        return p;
    } finally {
        or.release();
    }
}