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

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

Introduction

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

Prototype

@Override
public List<DiffEntry> call() throws GitAPIException 

Source Link

Document

Executes the Diff command with all the options and parameters collected by the setter methods (e.g.

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
 *//*from w ww. j  a  v  a  2  s . c  om*/
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:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public GitDiffs getDiffs(String branch, String path) throws Exception {
    fetch();// ww w .  j a  v  a2  s  . co m
    GitDiffs diffs = new GitDiffs();
    ObjectId remoteHead = localRepo.resolve("origin/" + branch + "^{tree}");
    if (remoteHead == null)
        throw new IOException("Unable to determine Git Diffs due to missing remote HEAD");
    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    newTreeIter.reset(localRepo.newObjectReader(), remoteHead);
    DiffCommand dc = git.diff().setNewTree(newTreeIter);
    if (path != null)
        dc.setPathFilter(PathFilter.create(path));
    dc.setShowNameAndStatusOnly(true);
    for (DiffEntry diff : dc.call()) {
        if (diff.getChangeType() == ChangeType.ADD || diff.getChangeType() == ChangeType.COPY) {
            diffs.add(DiffType.MISSING, diff.getNewPath());
        } else if (diff.getChangeType() == ChangeType.MODIFY) {
            diffs.add(DiffType.DIFFERENT, diff.getNewPath());
        } else if (diff.getChangeType() == ChangeType.DELETE) {
            diffs.add(DiffType.EXTRA, diff.getOldPath());
        } else if (diff.getChangeType() == ChangeType.RENAME) {
            diffs.add(DiffType.MISSING, diff.getNewPath());
            diffs.add(DiffType.EXTRA, diff.getOldPath());
        }
    }
    // we're purposely omitting folders
    Status status = git.status().addPath(path).call();
    for (String untracked : status.getUntracked()) {
        if (!untracked.startsWith(path + "/Archive/"))
            diffs.add(DiffType.EXTRA, untracked);
    }
    for (String added : status.getAdded()) {
        diffs.add(DiffType.EXTRA, added);
    }
    for (String missing : status.getMissing()) {
        diffs.add(DiffType.MISSING, missing);
    }
    for (String removed : status.getRemoved()) {
        diffs.add(DiffType.MISSING, removed);
    }
    for (String changed : status.getChanged()) {
        diffs.add(DiffType.DIFFERENT, changed);
    }
    for (String modified : status.getModified()) {
        diffs.add(DiffType.DIFFERENT, modified);
    }
    for (String conflict : status.getConflicting()) {
        diffs.add(DiffType.DIFFERENT, conflict);
    }
    return diffs;
}

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

License:Open Source License

/**
 * {@inheritDoc}./*www  .ja v a 2 s  .  c  om*/
 */
@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  .c  o m
        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

private List<String> addNewFiles(Git git, IProgressMonitor monitor) throws IOException, GitAPIException {
    monitor.beginTask("Creating Diff", 100);
    DiffCommand diffCommand = git.diff();

    AddCommand addCommand = git.add();/*  w  ww  .  j  av a2  s.  co  m*/
    List<String> changedFiles = new ArrayList<String>();
    List<String> newFiles = new ArrayList<String>();

    List<DiffEntry> result = diffCommand.call();
    //TODO: delete won't work
    for (DiffEntry diffEntry : result) {
        checkCanceled(monitor);
        if (diffEntry.getChangeType() == ChangeType.ADD) {
            addCommand.addFilepattern(diffEntry.getNewPath());
            newFiles.add(diffEntry.getNewPath());
            monitor.subTask(diffEntry.getNewPath());
        } else if (diffEntry.getChangeType() == ChangeType.MODIFY) {
            monitor.subTask(diffEntry.getOldPath());
            changedFiles.add(diffEntry.getOldPath());
        }
        monitor.worked(0);
    }
    if (!newFiles.isEmpty())
        addCommand.call();

    changedFiles.addAll(newFiles);
    monitor.done();
    return changedFiles;
}

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  ww .ja  v  a 2 s.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);/*w  ww . j  a v a 2  s .c  o  m*/

    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;
}