Search in sources :

Example 26 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project zeppelin by apache.

the class GitNotebookRepoTest method initNonemptyNotebookDir.

@Test
public void initNonemptyNotebookDir() throws IOException, GitAPIException {
    // given - .git does not exit
    File dotGit = new File(String.join(File.separator, notebooksDir, ".git"));
    assertFalse(dotGit.exists());
    // when
    notebookRepo = new GitNotebookRepo(conf);
    // then
    Git git = notebookRepo.getGit();
    assertNotNull(git);
    assertTrue(dotGit.exists());
    assertFalse(notebookRepo.list(null).isEmpty());
    List<DiffEntry> diff = git.diff().call();
    // no commit, diff isn't empty
    assertFalse(diff.isEmpty());
}
Also used : Git(org.eclipse.jgit.api.Git) File(java.io.File) DiffEntry(org.eclipse.jgit.diff.DiffEntry) Test(org.junit.Test)

Example 27 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project gerrit by GerritCodeReview.

the class DiffOperationsImpl method loadModifiedFilesWithoutCache.

/**
 * Loads the modified file paths between two commits without inspecting the diff cache.
 */
private static Map<String, ModifiedFile> loadModifiedFilesWithoutCache(Project.NameKey project, DiffParameters diffParams, RevWalk revWalk, Config repoConfig) throws DiffNotAvailableException {
    ObjectId newCommit = diffParams.newCommit();
    ObjectId oldCommit = diffParams.baseCommit();
    try {
        ObjectReader reader = revWalk.getObjectReader();
        List<DiffEntry> diffEntries;
        try (DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) {
            df.setReader(reader, repoConfig);
            df.setDetectRenames(false);
            diffEntries = df.scan(oldCommit.equals(ObjectId.zeroId()) ? null : oldCommit, newCommit);
        }
        List<ModifiedFile> modifiedFiles = diffEntries.stream().map(entry -> ModifiedFile.builder().changeType(toChangeType(entry.getChangeType())).oldPath(getGitPath(entry.getOldPath())).newPath(getGitPath(entry.getNewPath())).build()).collect(Collectors.toList());
        return DiffUtil.mergeRewrittenModifiedFiles(modifiedFiles).stream().collect(ImmutableMap.toImmutableMap(ModifiedFile::getDefaultPath, Function.identity()));
    } catch (IOException e) {
        throw new DiffNotAvailableException(String.format("Failed to compute the modified files for project '%s'," + " old commit '%s', new commit '%s'.", project, oldCommit.name(), newCommit.name()), e);
    }
}
Also used : Patch(com.google.gerrit.entities.Patch) Module(com.google.inject.Module) ModifiedFilesCache(com.google.gerrit.server.patch.diff.ModifiedFilesCache) Whitespace(com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace) DiffAlgorithm(com.google.gerrit.server.patch.gitfilediff.GitFileDiffCacheImpl.DiffAlgorithm) Inject(com.google.inject.Inject) FileDiffCache(com.google.gerrit.server.patch.filediff.FileDiffCache) MERGE_LIST(com.google.gerrit.entities.Patch.MERGE_LIST) ImmutableCollection(com.google.common.collect.ImmutableCollection) Function(java.util.function.Function) ArrayList(java.util.ArrayList) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Config(org.eclipse.jgit.lib.Config) ChangeType(com.google.gerrit.entities.Patch.ChangeType) ImmutableList(com.google.common.collect.ImmutableList) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) Map(java.util.Map) ModifiedFilesCacheKey(com.google.gerrit.server.patch.diff.ModifiedFilesCacheKey) GitModifiedFilesCacheImpl(com.google.gerrit.server.patch.gitdiff.GitModifiedFilesCacheImpl) DiffPreferencesInfo(com.google.gerrit.extensions.client.DiffPreferencesInfo) ImmutableMap(com.google.common.collect.ImmutableMap) ModifiedFile(com.google.gerrit.server.patch.gitdiff.ModifiedFile) DisabledOutputStream(org.eclipse.jgit.util.io.DisabledOutputStream) FileDiffCacheKey(com.google.gerrit.server.patch.filediff.FileDiffCacheKey) FileDiffCacheImpl(com.google.gerrit.server.patch.filediff.FileDiffCacheImpl) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) COMMIT_MSG(com.google.gerrit.entities.Patch.COMMIT_MSG) CacheModule(com.google.gerrit.server.cache.CacheModule) GitFileDiffCacheImpl(com.google.gerrit.server.patch.gitfilediff.GitFileDiffCacheImpl) ObjectId(org.eclipse.jgit.lib.ObjectId) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) AutoValue(com.google.auto.value.AutoValue) Project(com.google.gerrit.entities.Project) Optional(java.util.Optional) DiffEntry(org.eclipse.jgit.diff.DiffEntry) ModifiedFilesCacheImpl(com.google.gerrit.server.patch.diff.ModifiedFilesCacheImpl) ObjectReader(org.eclipse.jgit.lib.ObjectReader) FluentLogger(com.google.common.flogger.FluentLogger) Singleton(com.google.inject.Singleton) ObjectId(org.eclipse.jgit.lib.ObjectId) ModifiedFile(com.google.gerrit.server.patch.gitdiff.ModifiedFile) ObjectReader(org.eclipse.jgit.lib.ObjectReader) IOException(java.io.IOException) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 28 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project gerrit by GerritCodeReview.

the class PRED_commit_delta_4 method exec.

@Override
public Operation exec(Prolog engine) throws PrologException {
    engine.cont = cont;
    engine.setB0();
    Term a1 = arg1.dereference();
    if (a1 instanceof VariableTerm) {
        throw new PInstantiationException(this, 1);
    }
    if (!(a1 instanceof SymbolTerm)) {
        throw new IllegalTypeException(this, 1, "symbol", a1);
    }
    Pattern regex = Pattern.compile(a1.name());
    engine.r1 = new JavaObjectTerm(regex);
    engine.r2 = arg2;
    engine.r3 = arg3;
    engine.r4 = arg4;
    Repository repository = StoredValues.REPOSITORY.get(engine);
    try (DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE)) {
        diffFormatter.setRepository(repository);
        // Do not detect renames; that would require reading file contents, which is slow for large
        // files.
        RevCommit commit = StoredValues.COMMIT.get(engine);
        List<DiffEntry> diffEntries = diffFormatter.scan(// parent #0 is always the right choice, if it exists.
        commit.getParentCount() > 0 ? commit.getParent(0) : null, commit);
        engine.r5 = new JavaObjectTerm(diffEntries.iterator());
    } catch (IOException e) {
        throw new JavaException(e);
    }
    return engine.jtry5(commit_delta_check, commit_delta_next);
}
Also used : Pattern(java.util.regex.Pattern) JavaException(com.googlecode.prolog_cafe.exceptions.JavaException) IllegalTypeException(com.googlecode.prolog_cafe.exceptions.IllegalTypeException) SymbolTerm(com.googlecode.prolog_cafe.lang.SymbolTerm) Term(com.googlecode.prolog_cafe.lang.Term) JavaObjectTerm(com.googlecode.prolog_cafe.lang.JavaObjectTerm) SymbolTerm(com.googlecode.prolog_cafe.lang.SymbolTerm) VariableTerm(com.googlecode.prolog_cafe.lang.VariableTerm) IOException(java.io.IOException) PInstantiationException(com.googlecode.prolog_cafe.exceptions.PInstantiationException) Repository(org.eclipse.jgit.lib.Repository) JavaObjectTerm(com.googlecode.prolog_cafe.lang.JavaObjectTerm) VariableTerm(com.googlecode.prolog_cafe.lang.VariableTerm) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 29 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project chuidiang-ejemplos by chuidiang.

the class GitAnalyzer method analyze.

public void analyze(HtmlFormat format, String issuePattern, String issueName) throws IOException {
    try (RevWalk walk = new RevWalk(repository)) {
        RevFilter filter = MessageRevFilter.create(issuePattern);
        walk.setRevFilter(filter);
        walk.markStart(walk.parseCommit(repository.resolve("HEAD")));
        Iterator<RevCommit> iterator = walk.iterator();
        if (!iterator.hasNext()) {
            return;
        }
        format.addIssue(issueName);
        while (iterator.hasNext()) {
            RevCommit commit = iterator.next();
            String commitNumber = commit.getId().getName();
            Date date = commit.getAuthorIdent().getWhen();
            String author = commit.getAuthorIdent().getName();
            String comment = commit.getFullMessage();
            ObjectId objectId = commit.getTree().getId();
            RevCommit parent = commit.getParent(0);
            PatchIdDiffFormatter formatter = new PatchIdDiffFormatter();
            formatter.setRepository(repository);
            ArrayList<String> files = new ArrayList<>();
            try {
                List<DiffEntry> entries = formatter.scan(parent, objectId);
                entries.forEach((entry) -> {
                    try {
                        FileHeader header = formatter.toFileHeader(entry);
                        files.add(header.getChangeType() + " " + getPath(header));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            format.addChange(commitNumber, date, author, comment, files.toArray(new String[] {}));
        }
        format.endIssue();
    } catch (Exception e) {
        format.endIssue();
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Date(java.util.Date) IOException(java.io.IOException) MessageRevFilter(org.eclipse.jgit.revwalk.filter.MessageRevFilter) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) FileHeader(org.eclipse.jgit.patch.FileHeader) RevCommit(org.eclipse.jgit.revwalk.RevCommit) PatchIdDiffFormatter(org.eclipse.jgit.diff.PatchIdDiffFormatter) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 30 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project sonarqube by SonarSource.

the class GitScmProvider method collectChangedLines.

private void collectChangedLines(Repository repo, RevCommit mergeBaseCommit, Map<Path, Set<Integer>> changedLines, Path changedFile) {
    ChangedLinesComputer computer = new ChangedLinesComputer();
    try (DiffFormatter diffFmt = new DiffFormatter(new BufferedOutputStream(computer.receiver()))) {
        // copied from DiffCommand so that we can use a custom DiffFormatter which ignores white spaces.
        diffFmt.setRepository(repo);
        diffFmt.setProgressMonitor(NullProgressMonitor.INSTANCE);
        diffFmt.setDiffComparator(RawTextComparator.WS_IGNORE_ALL);
        Path workTree = repo.getWorkTree().toPath();
        String relativePath = workTree.relativize(changedFile).toString();
        PathFilter pathFilter = PathFilter.create(toGitPath(relativePath));
        diffFmt.setPathFilter(pathFilter);
        AbstractTreeIterator mergeBaseTree = prepareTreeParser(repo, mergeBaseCommit);
        List<DiffEntry> diffEntries = diffFmt.scan(mergeBaseTree, new FileTreeIterator(repo));
        diffFmt.format(diffEntries);
        diffFmt.flush();
        diffEntries.stream().filter(diffEntry -> diffEntry.getChangeType() == DiffEntry.ChangeType.ADD || diffEntry.getChangeType() == DiffEntry.ChangeType.MODIFY).findAny().ifPresent(diffEntry -> changedLines.put(changedFile, computer.changedLines()));
    } catch (Exception e) {
        LOG.warn("Failed to get changed lines from git for file " + changedFile, e);
    }
}
Also used : Path(java.nio.file.Path) AbstractTreeIterator(org.eclipse.jgit.treewalk.AbstractTreeIterator) PathFilter(org.eclipse.jgit.treewalk.filter.PathFilter) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) BufferedOutputStream(java.io.BufferedOutputStream) FileTreeIterator(org.eclipse.jgit.treewalk.FileTreeIterator) MessageException(org.sonar.api.utils.MessageException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Aggregations

DiffEntry (org.eclipse.jgit.diff.DiffEntry)66 RevCommit (org.eclipse.jgit.revwalk.RevCommit)24 RevWalk (org.eclipse.jgit.revwalk.RevWalk)23 DiffFormatter (org.eclipse.jgit.diff.DiffFormatter)22 ObjectReader (org.eclipse.jgit.lib.ObjectReader)21 CanonicalTreeParser (org.eclipse.jgit.treewalk.CanonicalTreeParser)20 IOException (java.io.IOException)19 Git (org.eclipse.jgit.api.Git)18 ObjectId (org.eclipse.jgit.lib.ObjectId)15 ArrayList (java.util.ArrayList)14 File (java.io.File)13 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)12 RevTree (org.eclipse.jgit.revwalk.RevTree)11 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 Path (java.nio.file.Path)8 Test (org.junit.Test)8 FileTreeIterator (org.eclipse.jgit.treewalk.FileTreeIterator)7 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)7 Ref (org.eclipse.jgit.lib.Ref)6 Repository (org.eclipse.jgit.lib.Repository)6