Example usage for org.eclipse.jgit.api DiffCommand setOldTree

List of usage examples for org.eclipse.jgit.api DiffCommand setOldTree

Introduction

In this page you can find the example usage for org.eclipse.jgit.api DiffCommand setOldTree.

Prototype

public DiffCommand setOldTree(AbstractTreeIterator oldTree) 

Source Link

Document

Set old tree

Usage

From source file:com.addthis.hydra.job.store.JobStoreGit.java

License:Apache License

/**
 * Get the diff of a file against a particular commit
 *
 * @param jobId    The job config to diff
 * @param commitId If specified, the commit to compare against; otherwise, compare against the latest revision
 * @return A string description of the diff, comparable to the output of "git diff filename"
 * @throws GitAPIException If there is a problem fetching the diff from git
 * @throws IOException     If there is a problem reading from the file
 *//*  w  ww.ja v a 2s.com*/
public String getDiff(String jobId, String commitId) throws GitAPIException, IOException {
    OutputStream out = new ByteArrayOutputStream();
    DiffCommand diff = git.diff().setPathFilter(PathFilter.create(getPathForJobId(jobId))).setOutputStream(out)
            .setSourcePrefix("old:").setDestinationPrefix("new:");
    if (commitId != null) {
        diff.setOldTree(getTreeIterator(commitId));
        diff.setNewTree(getTreeIterator("HEAD"));
    }
    diff.call();
    return out.toString();
}

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

License:Open Source License

/**
 * {@inheritDoc}./*w ww  .  j  a va 2  s  . co m*/
 */
@Override
protected Integer performGitCommand() {
    try {
        IWorkspace ws = ResourcesPlugin.getWorkspace();

        // Call JGit diff to get the files involved
        OutputStream out = new ByteArrayOutputStream();
        DiffCommand diffCommand = Git.open(repo.getDirectory()).diff().setOutputStream(out);
        if (commit != null) {
            diffCommand = diffCommand.setOldTree(getTreeIterator(repo, commit));
        }
        if (commitWith != null) {
            diffCommand = diffCommand.setNewTree(getTreeIterator(repo, commitWith));
        }
        if (pathFilter != null) {
            diffCommand = diffCommand.setPathFilter(pathFilter);
        }
        Set<IFile> files = new HashSet<IFile>();
        List<DiffEntry> entries = diffCommand.call();

        for (DiffEntry diffEntry : entries) {
            String path = diffEntry.getOldPath();
            if (path != null) {
                IFile file = ws.getRoot().getFile(new Path(path));
                if (file != null) {
                    files.add(file);
                }
            }
        }

        if (files.isEmpty()) {
            System.out.println("No difference to display.");
            return Returns.COMPLETE.code();
        }

        for (IFile file : files) {
            RemoteResourceMappingContext mergeContext = createSubscriberForComparison(repo, commit, commitWith,
                    file);
            if (!isEMFCompareCompliantFile(mergeContext, file)) {
                diffCommand.setPathFilter(PathFilter.create(file.getProjectRelativePath().toString()));
                diffCommand.call();
                System.out.println(out.toString());
            } else {
                final ResourceMapping[] emfMappings = getResourceMappings(mergeContext, file);
                for (ResourceMapping mapping : emfMappings) {
                    if (mapping instanceof EMFResourceMapping) {
                        /*
                         * These two won't be used by the builder in our case since we retrieve the
                         * already created syncModel from the resource mapping.
                         */
                        final IModelMinimizer minimizer = new IdenticalResourceMinimizer();
                        final NullProgressMonitor nullProgressMonitor = new NullProgressMonitor();

                        mapping.getTraversals(mergeContext, nullProgressMonitor);
                        final SynchronizationModel syncModel = ((EMFResourceMapping) mapping).getLatestModel();
                        minimizer.minimize(syncModel, nullProgressMonitor);
                        final IComparisonScope scope = ComparisonScopeBuilder.create(syncModel,
                                nullProgressMonitor);

                        final Comparison comparison = EMFCompare.builder().build().compare(scope,
                                BasicMonitor.toMonitor(nullProgressMonitor));

                        Resource resource = new XMIResourceImpl();
                        Copier copier = new Copier(false);
                        EObject comparisonCopy = copier.copy(comparison);
                        copier.copyReferences();
                        resource.getContents().add(comparisonCopy);

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        resource.save(baos, null);
                        System.out.println(baos.toString("UTF-8"));//$NON-NLS-1$
                    }
                }
            }
        }
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    }

    return Returns.COMPLETE.code();
}

From source file:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

@Override
public Collection<PropertyFileDiff> update(ProjectVersion project, IProgressMonitor monitor)
        throws TeamProviderException {

    SubMonitor subMon = SubMonitor.convert(monitor, 100);
    List<PropertyFileDiff> updatedFiles = new ArrayList<PropertyFileDiff>();
    try {/*from w w w.j av a 2s.  com*/
        Repository repository = createRepository(project);
        Git git = Git.wrap(repository);
        FetchCommand fetchCommand = git.fetch();
        URI uri = project.getParent().getRepositoryURI();
        if (uri != null)
            fetchCommand.setRemote(stripUserInfo(uri).toString());
        String refspecString = "refs/heads/{0}:refs/remotes/origin/{0}";
        refspecString = MessageFormat.format(refspecString, project.getName());
        RefSpec spec = new RefSpec(refspecString);
        fetchCommand.setRefSpecs(spec);
        subMon.subTask("Fetching from remote");
        if (!"https".equals(uri.scheme()) && !"http".equals(uri.scheme()))
            fetchCommand.setTransportConfigCallback(createTransportConfigCallback(project.getParent()));
        fetchCommand.setCredentialsProvider(createCredentialsProvider(project.getParent()));
        fetchCommand.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(80)));
        fetchCommand.call();
        ObjectId remoteHead = repository.resolve("refs/remotes/origin/" + project.getName() + "^{tree}");

        DiffCommand diff = git.diff();
        subMon.subTask("Caculating Diff");
        diff.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(20)));
        diff.setOldTree(new FileTreeIterator(repository));
        CanonicalTreeParser p = new CanonicalTreeParser();
        ObjectReader reader = repository.newObjectReader();
        try {
            p.reset(reader, remoteHead);
        } finally {
            reader.release();
        }
        diff.setNewTree(p);
        checkCanceled(subMon);
        List<DiffEntry> diffs = diff.call();
        for (DiffEntry diffEntry : diffs) {
            checkCanceled(subMon);
            updatedFiles.add(convertDiffEntry(diffEntry));
            LOGGER.trace(diffEntry.toString());
        }
        if (!updatedFiles.isEmpty()) {
            checkCanceled(subMon);
            //no more cancel after this point
            ObjectId lastCommitID = repository
                    .resolve("refs/remotes/origin/" + project.getName() + "^{commit}");
            LOGGER.info("Merging remote commit {} to {}/{}",
                    new Object[] { lastCommitID, project.getName(), project.getParent().getName() });
            //TODO: use rebase here?
            if (isRebase(project)) {
                RebaseCommand rebase = git.rebase();
                rebase.setUpstream("refs/remotes/origin/" + project.getName());
                RebaseResult result = rebase.call();
                if (result.getStatus().isSuccessful()) {
                    LOGGER.info("Rebase finished: {}", result.getStatus());
                } else {
                    LOGGER.error("Rebase of {} failed. Attempting abort", project.relativePath());
                    rebase = git.rebase();
                    rebase.setOperation(Operation.ABORT);
                    result = rebase.call();
                    LOGGER.error("Abort finished with {}", result.getStatus());
                }
            } else {
                MergeCommand merge = git.merge();
                merge.include(lastCommitID);
                MergeResult mergeResult = merge.call();

                LOGGER.info("Merge finished: {}", mergeResult.getMergeStatus());
            }
        } else
            LOGGER.info("Update finished successfully. Nothing to merge, already up to date");
    } catch (JGitInternalException e) {
        throw new TeamProviderException(e);
    } catch (InvalidRemoteException e) {
        throw new TeamProviderException(e);
    } catch (GitAPIException e) {
        throw new TeamProviderException(e);
    } catch (AmbiguousObjectException e) {
        throw new TeamProviderException(e);
    } catch (IOException e) {
        throw new TeamProviderException(e);
    } finally {
        monitor.done();
    }
    return updatedFiles;
}

From source file:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

@Override
public Collection<PropertyFileDiff> reset(ProjectVersion project, IProgressMonitor monitor)
        throws TeamProviderException {

    List<PropertyFileDiff> updatedFiles = new ArrayList<PropertyFileDiff>();
    try {/*from  w  w  w.  ja  va 2s.c o m*/
        Repository repository = createRepository(project);
        SubMonitor subMon = SubMonitor.convert(monitor, "Reset", 100);
        Git git = new Git(repository);
        subMon.subTask("Calculating Diff");
        DiffCommand diffCommand = git.diff();
        diffCommand.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(30)));
        diffCommand.setOldTree(prepareTreeParser(repository, "refs/remotes/origin/" + project.getName()));
        diffCommand.setNewTree(null);
        List<DiffEntry> diffs = diffCommand.call();
        for (DiffEntry diffEntry : diffs) {
            checkCanceled(monitor);
            PropertyFileDiff fileDiff = createDiff(diffEntry, monitor);
            revertDiff(fileDiff);
            updatedFiles.add(fileDiff);
        }

        subMon.subTask("Executing Reset");
        ResetCommand reset = git.reset();
        reset.setMode(ResetType.HARD);
        reset.setRef("refs/remotes/origin/" + project.getName());
        reset.call();

        CleanCommand clean = git.clean();
        clean.setCleanDirectories(true);
        Set<String> call = clean.call();
        LOGGER.info("cleaned " + call);

    } catch (IOException e) {
        LOGGER.error("reset failed", e);
        throw new TeamProviderException(e);
    } catch (GitAPIException e) {
        LOGGER.error("reset failed", e);
        throw new TeamProviderException(e);
    }
    return updatedFiles;
}

From source file:org.kuali.student.git.importer.ConvertOldBranchesToTagsMain.java

License:Educational Community License

private static boolean commitContainsChangesToParent(Git git, Repository repo, AnyObjectId commitTreeId,
        AnyObjectId parentTreeId) throws MissingObjectException, IncorrectObjectTypeException,
        CorruptObjectException, IOException, GitAPIException {
    DiffCommand diffCommand = git.diff();

    TreeWalk parentWalk = new TreeWalk(repo);

    parentWalk.addTree(parentTreeId);//ww  w .ja  v a2 s . c  om

    parentWalk.setRecursive(true);

    TreeWalk commitWalk = new TreeWalk(repo);

    commitWalk.addTree(commitTreeId);

    commitWalk.setRecursive(true);

    CanonicalTreeParser commitTreeParser = new CanonicalTreeParser(null, commitWalk.getObjectReader(),
            commitTreeId);

    CanonicalTreeParser parentTreeParser = new CanonicalTreeParser(null, parentWalk.getObjectReader(),
            parentTreeId);

    diffCommand.setOldTree(parentTreeParser);
    diffCommand.setNewTree(commitTreeParser);

    List<DiffEntry> entries = diffCommand.call();

    if (entries.size() > 0)
        return true;
    else
        return false;
}