Search in sources :

Example 61 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project winery by eclipse.

the class GitBasedRepository method hasChangesInFile.

@Override
public boolean hasChangesInFile(DefinitionsChildId id) {
    RepositoryFileReference ref = BackendUtils.getRefOfDefinitions(id);
    try (Git git = getGit()) {
        if (!git.status().call().isClean()) {
            List<DiffEntry> diffEntries = git.diff().call();
            List<DiffEntry> entries = diffEntries.stream().filter(item -> item.getNewPath().startsWith(BackendUtils.getPathInsideRepo(ref.getParent()))).collect(Collectors.toList());
            git.getRepository().close();
            return entries.size() > 0;
        }
    } catch (GitAPIException e) {
        LOGGER.trace(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error("Error initializing Git.", e);
    }
    return false;
}
Also used : IWrappingRepository(org.eclipse.winery.repository.backend.IWrappingRepository) Status(org.eclipse.jgit.api.Status) RequirementTypeId(org.eclipse.winery.model.ids.definitions.RequirementTypeId) FileTime(java.nio.file.attribute.FileTime) OTTopologyFragmentRefinementModel(org.eclipse.winery.model.tosca.extensions.OTTopologyFragmentRefinementModel) TRelationshipTypeImplementation(org.eclipse.winery.model.tosca.TRelationshipTypeImplementation) OTComplianceRule(org.eclipse.winery.model.tosca.extensions.OTComplianceRule) ResetCommand(org.eclipse.jgit.api.ResetCommand) Map(java.util.Map) GenericId(org.eclipse.winery.model.ids.GenericId) Path(java.nio.file.Path) TArtifactType(org.eclipse.winery.model.tosca.TArtifactType) TDefinitions(org.eclipse.winery.model.tosca.TDefinitions) TEntityType(org.eclipse.winery.model.tosca.TEntityType) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Constants(org.eclipse.winery.common.Constants) CommitCommand(org.eclipse.jgit.api.CommitCommand) RelationshipTypeId(org.eclipse.winery.model.ids.definitions.RelationshipTypeId) CapabilityTypeId(org.eclipse.winery.model.ids.definitions.CapabilityTypeId) NoWorkTreeException(org.eclipse.jgit.errors.NoWorkTreeException) QName(javax.xml.namespace.QName) TRequirementType(org.eclipse.winery.model.tosca.TRequirementType) Iterables(com.google.common.collect.Iterables) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TopologyFragmentRefinementModelId(org.eclipse.winery.model.ids.extensions.TopologyFragmentRefinementModelId) MediaType(org.apache.tika.mime.MediaType) GitBasedRepositoryConfiguration(org.eclipse.winery.common.configuration.GitBasedRepositoryConfiguration) ArrayList(java.util.ArrayList) RelationshipTypeImplementationId(org.eclipse.winery.model.ids.definitions.RelationshipTypeImplementationId) TestRefinementModelId(org.eclipse.winery.model.ids.extensions.TestRefinementModelId) ArtifactTemplateId(org.eclipse.winery.model.ids.definitions.ArtifactTemplateId) TCapabilityType(org.eclipse.winery.model.tosca.TCapabilityType) XsdImportManager(org.eclipse.winery.repository.backend.xsd.XsdImportManager) CleanCommand(org.eclipse.jgit.api.CleanCommand) DefinitionsChildId(org.eclipse.winery.model.ids.definitions.DefinitionsChildId) ArtifactTypeId(org.eclipse.winery.model.ids.definitions.ArtifactTypeId) PushCommand(org.eclipse.jgit.api.PushCommand) Files(java.nio.file.Files) StringWriter(java.io.StringWriter) IOException(java.io.IOException) Configuration(org.apache.commons.configuration2.Configuration) TArtifactTemplate(org.eclipse.winery.model.tosca.TArtifactTemplate) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader) Repository(org.eclipse.jgit.lib.Repository) TNodeTypeImplementation(org.eclipse.winery.model.tosca.TNodeTypeImplementation) PullCommand(org.eclipse.jgit.api.PullCommand) SortedSet(java.util.SortedSet) Date(java.util.Date) ComplianceRuleId(org.eclipse.winery.model.ids.extensions.ComplianceRuleId) LoggerFactory(org.slf4j.LoggerFactory) Namespace(org.eclipse.winery.model.ids.Namespace) WineryRepositoryException(org.eclipse.winery.repository.exceptions.WineryRepositoryException) TServiceTemplate(org.eclipse.winery.model.tosca.TServiceTemplate) AddCommand(org.eclipse.jgit.api.AddCommand) TPolicyType(org.eclipse.winery.model.tosca.TPolicyType) OTRefinementModel(org.eclipse.winery.model.tosca.extensions.OTRefinementModel) OTTestRefinementModel(org.eclipse.winery.model.tosca.extensions.OTTestRefinementModel) ResetType(org.eclipse.jgit.api.ResetCommand.ResetType) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder) RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference) Collection(java.util.Collection) TNodeType(org.eclipse.winery.model.tosca.TNodeType) Collectors(java.util.stream.Collectors) List(java.util.List) TExtensibleElements(org.eclipse.winery.model.tosca.TExtensibleElements) GenericImportId(org.eclipse.winery.model.ids.definitions.imports.GenericImportId) RepositoryCorruptException(org.eclipse.winery.repository.exceptions.RepositoryCorruptException) Ref(org.eclipse.jgit.lib.Ref) Optional(java.util.Optional) ListBranchCommand(org.eclipse.jgit.api.ListBranchCommand) RmCommand(org.eclipse.jgit.api.RmCommand) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) HashMap(java.util.HashMap) OTPatternRefinementModel(org.eclipse.winery.model.tosca.extensions.OTPatternRefinementModel) EventBus(com.google.common.eventbus.EventBus) PatternRefinementModelId(org.eclipse.winery.model.ids.extensions.PatternRefinementModelId) BackendUtils(org.eclipse.winery.repository.backend.BackendUtils) NodeTypeImplementationId(org.eclipse.winery.model.ids.definitions.NodeTypeImplementationId) PolicyTypeId(org.eclipse.winery.model.ids.definitions.PolicyTypeId) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) Environments(org.eclipse.winery.common.configuration.Environments) TImplementationArtifact(org.eclipse.winery.model.tosca.TImplementationArtifact) HasInheritanceId(org.eclipse.winery.model.ids.definitions.HasInheritanceId) RefinementId(org.eclipse.winery.model.ids.extensions.RefinementId) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) ToscaElementId(org.eclipse.winery.model.ids.elements.ToscaElementId) NamespaceManager(org.eclipse.winery.repository.backend.NamespaceManager) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) TRelationshipType(org.eclipse.winery.model.tosca.TRelationshipType) Git(org.eclipse.jgit.api.Git) DiffEntry(org.eclipse.jgit.diff.DiffEntry) PolicyTemplateId(org.eclipse.winery.model.ids.definitions.PolicyTemplateId) TPolicyTemplate(org.eclipse.winery.model.tosca.TPolicyTemplate) InputStream(java.io.InputStream) NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference) IOException(java.io.IOException) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 62 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project winery by eclipse.

the class GitBasedRepository method postEventMap.

public Map<DiffEntry, String> postEventMap() throws GitAPIException {
    Map<DiffEntry, String> diffMap = new HashMap<>();
    try (OutputStream stream = new ByteArrayOutputStream();
        Git git = getGit()) {
        List<DiffEntry> list = git.diff().setOutputStream(stream).call();
        BufferedReader reader = new BufferedReader(new StringReader(stream.toString()));
        String line = reader.readLine();
        for (DiffEntry entry : list) {
            StringWriter diff = new StringWriter();
            if (line != null) {
                do {
                    diff.append(line);
                    diff.write('\n');
                    line = reader.readLine();
                } while (line != null && !line.startsWith("diff"));
            }
            diffMap.put(entry, diff.toString());
        }
        git.getRepository().close();
    } catch (IOException exc) {
        LOGGER.trace("Reading of git information failed!", exc);
    } catch (JGitInternalException gitException) {
        LOGGER.trace("Could not create Diff!", gitException);
    }
    this.eventBus.post(diffMap);
    return diffMap;
}
Also used : HashMap(java.util.HashMap) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Git(org.eclipse.jgit.api.Git) StringWriter(java.io.StringWriter) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 63 with DiffEntry

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

the class GitScmProvider method branchChangedFiles.

@CheckForNull
@Override
public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) {
    try (Repository repo = buildRepo(rootBaseDir)) {
        Ref targetRef = resolveTargetRef(targetBranchName, repo);
        if (targetRef == null) {
            addWarningTargetNotFound(targetBranchName);
            return null;
        }
        if (isDiffAlgoInvalid(repo.getConfig())) {
            LOG.warn("The diff algorithm configured in git is not supported. " + "No information regarding changes in the branch will be collected, which can lead to unexpected results.");
            return null;
        }
        Optional<RevCommit> mergeBaseCommit = findMergeBase(repo, targetRef);
        if (!mergeBaseCommit.isPresent()) {
            LOG.warn("No merge base found between HEAD and " + targetRef.getName());
            return null;
        }
        AbstractTreeIterator mergeBaseTree = prepareTreeParser(repo, mergeBaseCommit.get());
        // we compare a commit with HEAD, so no point ignoring line endings (it will be whatever is committed)
        try (Git git = newGit(repo)) {
            List<DiffEntry> diffEntries = git.diff().setShowNameAndStatusOnly(true).setOldTree(mergeBaseTree).setNewTree(prepareNewTree(repo)).call();
            return diffEntries.stream().filter(diffEntry -> diffEntry.getChangeType() == DiffEntry.ChangeType.ADD || diffEntry.getChangeType() == DiffEntry.ChangeType.MODIFY).map(diffEntry -> repo.getWorkTree().toPath().resolve(diffEntry.getNewPath())).collect(Collectors.toSet());
        }
    } catch (IOException | GitAPIException e) {
        LOG.warn(e.getMessage(), e);
    }
    return null;
}
Also used : ScmProvider(org.sonar.api.batch.scm.ScmProvider) RevCommit(org.eclipse.jgit.revwalk.RevCommit) FileTreeIterator(org.eclipse.jgit.treewalk.FileTreeIterator) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) RawTextComparator(org.eclipse.jgit.diff.RawTextComparator) HashMap(java.util.HashMap) BufferedOutputStream(java.io.BufferedOutputStream) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Config(org.eclipse.jgit.lib.Config) Loggers(org.sonar.api.utils.log.Loggers) PathFilter(org.eclipse.jgit.treewalk.filter.PathFilter) Map(java.util.Map) MessageException(org.sonar.api.utils.MessageException) Path(java.nio.file.Path) Logger(org.sonar.api.utils.log.Logger) RepositoryBuilder(org.eclipse.jgit.lib.RepositoryBuilder) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) System2(org.sonar.api.utils.System2) ConfigConstants(org.eclipse.jgit.lib.ConfigConstants) Set(java.util.Set) IOException(java.io.IOException) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) NullProgressMonitor(org.eclipse.jgit.lib.NullProgressMonitor) File(java.io.File) DiffAlgorithm(org.eclipse.jgit.diff.DiffAlgorithm) List(java.util.List) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) Ref(org.eclipse.jgit.lib.Ref) Optional(java.util.Optional) AbstractTreeIterator(org.eclipse.jgit.treewalk.AbstractTreeIterator) BlameCommand(org.sonar.api.batch.scm.BlameCommand) AnalysisWarnings(org.sonar.api.notifications.AnalysisWarnings) Pattern(java.util.regex.Pattern) Git(org.eclipse.jgit.api.Git) DiffEntry(org.eclipse.jgit.diff.DiffEntry) CheckForNull(javax.annotation.CheckForNull) ObjectReader(org.eclipse.jgit.lib.ObjectReader) Repository(org.eclipse.jgit.lib.Repository) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) AbstractTreeIterator(org.eclipse.jgit.treewalk.AbstractTreeIterator) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) IOException(java.io.IOException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry) CheckForNull(javax.annotation.CheckForNull)

Example 64 with DiffEntry

use of org.eclipse.jgit.diff.DiffEntry in project OpenGrok by OpenGrok.

the class GitRepository method findOriginalName.

/**
 * Get the name of file in given revision. The returned file name is relative to the repository root.
 * Assumes renamed file hanndling is on.
 *
 * @param fullpath full file path
 * @param changeset revision ID (could be short)
 * @return original filename relative to the repository root
 * @throws java.io.IOException if I/O exception occurred
 * @see #getPathRelativeToCanonicalRepositoryRoot(String)
 */
String findOriginalName(String fullpath, String changeset) throws IOException {
    if (fullpath == null || fullpath.isEmpty()) {
        throw new IOException(String.format("Invalid file path string: %s", fullpath));
    }
    if (changeset == null || changeset.isEmpty()) {
        throw new IOException(String.format("Invalid changeset string for path %s: %s", fullpath, changeset));
    }
    String fileInRepo = getGitFilePath(getPathRelativeToCanonicalRepositoryRoot(fullpath));
    String originalFile = fileInRepo;
    try (org.eclipse.jgit.lib.Repository repository = getJGitRepository(getDirectoryName());
        RevWalk walk = new RevWalk(repository)) {
        walk.markStart(walk.parseCommit(repository.resolve(Constants.HEAD)));
        walk.markUninteresting(walk.lookupCommit(repository.resolve(changeset)));
        Config config = repository.getConfig();
        config.setBoolean("diff", null, "renames", true);
        org.eclipse.jgit.diff.DiffConfig dc = config.get(org.eclipse.jgit.diff.DiffConfig.KEY);
        FollowFilter followFilter = FollowFilter.create(getGitFilePath(fileInRepo), dc);
        walk.setTreeFilter(followFilter);
        for (RevCommit commit : walk) {
            if (commit.getParentCount() > 1 && !isMergeCommitsEnabled()) {
                continue;
            }
            if (commit.getId().getName().startsWith(changeset)) {
                break;
            }
            if (commit.getParentCount() >= 1) {
                OutputStream outputStream = NullOutputStream.INSTANCE;
                try (DiffFormatter formatter = new DiffFormatter(outputStream)) {
                    formatter.setRepository(repository);
                    formatter.setDetectRenames(true);
                    List<DiffEntry> diffs = formatter.scan(prepareTreeParser(repository, commit.getParent(0)), prepareTreeParser(repository, commit));
                    for (DiffEntry diff : diffs) {
                        if (diff.getChangeType() == DiffEntry.ChangeType.RENAME && originalFile.equals(diff.getNewPath())) {
                            originalFile = diff.getOldPath();
                        }
                    }
                }
            }
        }
    }
    if (originalFile == null) {
        LOGGER.log(Level.WARNING, "Failed to get original name in revision {0} for: \"{1}\"", new Object[] { changeset, fullpath });
        return null;
    }
    return getNativePath(originalFile);
}
Also used : FollowFilter(org.eclipse.jgit.revwalk.FollowFilter) Config(org.eclipse.jgit.lib.Config) NullOutputStream(org.eclipse.jgit.util.io.NullOutputStream) CountingOutputStream(org.eclipse.jgit.util.io.CountingOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) Repository(org.eclipse.jgit.lib.Repository) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 65 with DiffEntry

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

the class GITRemoteRepository2 method indexIsEmpty.

private boolean indexIsEmpty(DirCache dc) throws Exception {
    DirCacheIterator dci = new DirCacheIterator(dc);
    AbstractTreeIterator old = prepareTreeParser(repository, repository.resolve(Constants.HEAD));
    try (Git git = new Git(repository)) {
        List<DiffEntry> diffs = git.diff().setOldTree(old).setNewTree(dci).call();
        return diffs.isEmpty();
    }
}
Also used : AbstractTreeIterator(org.eclipse.jgit.treewalk.AbstractTreeIterator) Git(org.eclipse.jgit.api.Git) DirCacheIterator(org.eclipse.jgit.dircache.DirCacheIterator) 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