Example usage for org.eclipse.jgit.lib FileMode fromBits

List of usage examples for org.eclipse.jgit.lib FileMode fromBits

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib FileMode fromBits.

Prototype

public static final FileMode fromBits(int bits) 

Source Link

Document

Convert a set of mode bits into a FileMode enumerated value.

Usage

From source file:com.itemis.maven.plugins.unleash.scm.providers.merge.UnleashGitMerger.java

License:Eclipse Distribution License

/**
 * Updates the index after a content merge has happened. If no conflict has
 * occurred this includes persisting the merged content to the object
 * database. In case of conflicts this method takes care to write the
 * correct stages to the index.//w  ww  . j  a  v a 2  s  .c o  m
 *
 * @param base
 * @param ours
 * @param theirs
 * @param result
 * @throws FileNotFoundException
 * @throws IOException
 */
private void updateIndex(CanonicalTreeParser base, CanonicalTreeParser ours, CanonicalTreeParser theirs,
        MergeResult<RawText> result) throws FileNotFoundException, IOException {
    File mergedFile = !this.inCore ? writeMergedFile(result) : null;
    if (result.containsConflicts()) {
        // A conflict occurred, the file will contain conflict markers
        // the index will be populated with the three stages and the
        // workdir (if used) contains the halfway merged content.
        add(this.tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
        add(this.tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
        add(this.tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
        this.mergeResults.put(this.tw.getPathString(), result);
        return;
    }

    // No conflict occurred, the file will contain fully merged content.
    // The index will be populated with the new merged version.
    DirCacheEntry dce = new DirCacheEntry(this.tw.getPathString());

    // Set the mode for the new content. Fall back to REGULAR_FILE if
    // we can't merge modes of OURS and THEIRS.
    int newMode = mergeFileModes(this.tw.getRawMode(0), this.tw.getRawMode(1), this.tw.getRawMode(2));
    dce.setFileMode(newMode == FileMode.MISSING.getBits() ? FileMode.REGULAR_FILE : FileMode.fromBits(newMode));
    if (mergedFile != null) {
        long len = mergedFile.length();
        dce.setLastModified(mergedFile.lastModified());
        dce.setLength((int) len);
        InputStream is = new FileInputStream(mergedFile);
        try {
            dce.setObjectId(getObjectInserter().insert(OBJ_BLOB, len, is));
        } finally {
            is.close();
        }
    } else {
        dce.setObjectId(insertMergeResult(result));
    }
    this.builder.add(dce);
}

From source file:org.eclipse.emf.compare.egit.internal.merge.DirCacheResourceVariantTreeProvider.java

License:Open Source License

/**
 * Constructs the resource variant trees by iterating over the given repository's DirCache entries.
 *
 * @param repository/*  ww w  .  j  a  va2s.co m*/
 *            The repository which DirCache info we need to cache as IResourceVariantTrees.
 * @param useWorkspace
 *            Whether we should use local data instead of what's in the index for our side.
 * @throws IOException
 *             if we somehow cannot read the DirCache.
 */
public DirCacheResourceVariantTreeProvider(Repository repository, boolean useWorkspace) throws IOException {
    final DirCache cache = repository.readDirCache();
    final GitResourceVariantCache baseCache = new GitResourceVariantCache();
    final GitResourceVariantCache sourceCache = new GitResourceVariantCache();
    final GitResourceVariantCache remoteCache = new GitResourceVariantCache();

    for (int i = 0; i < cache.getEntryCount(); i++) {
        final DirCacheEntry entry = cache.getEntry(i);
        final IResource resource = ModelEGitResourceUtil.getResourceHandleForLocation(repository,
                entry.getPathString(), FileMode.fromBits(entry.getRawMode()) == FileMode.TREE);
        // Resource variants only make sense for IResources. Do not consider
        // files outside of the workspace or otherwise non accessible.
        if (resource == null || resource.getProject() == null || !resource.getProject().isAccessible()) {
            continue;
        }
        switch (entry.getStage()) {
        case DirCacheEntry.STAGE_0:
            if (useWorkspace) {
                sourceCache.setVariant(resource, new GitLocalResourceVariant(resource));
            } else {
                sourceCache.setVariant(resource, IndexResourceVariant.create(repository, entry));
            }
            baseCache.setVariant(resource, IndexResourceVariant.create(repository, entry));
            remoteCache.setVariant(resource, IndexResourceVariant.create(repository, entry));
            break;
        case DirCacheEntry.STAGE_1:
            baseCache.setVariant(resource, IndexResourceVariant.create(repository, entry));
            break;
        case DirCacheEntry.STAGE_2:
            if (useWorkspace) {
                sourceCache.setVariant(resource, new GitLocalResourceVariant(resource));
            } else {
                sourceCache.setVariant(resource, IndexResourceVariant.create(repository, entry));
            }
            break;
        case DirCacheEntry.STAGE_3:
            remoteCache.setVariant(resource, IndexResourceVariant.create(repository, entry));
            break;
        default:
            throw new IllegalStateException("Invalid stage: " + entry.getStage()); //$NON-NLS-1$
        }
    }

    baseTree = new GitCachedResourceVariantTree(baseCache);
    sourceTree = new GitCachedResourceVariantTree(sourceCache);
    remoteTree = new GitCachedResourceVariantTree(remoteCache);

    roots = new LinkedHashSet<IResource>();
    roots.addAll(baseCache.getRoots());
    roots.addAll(sourceCache.getRoots());
    roots.addAll(remoteCache.getRoots());

    knownResources = new LinkedHashSet<IResource>();
    knownResources.addAll(baseCache.getKnownResources());
    knownResources.addAll(sourceCache.getKnownResources());
    knownResources.addAll(remoteCache.getKnownResources());
}

From source file:org.eclipse.emf.compare.egit.internal.merge.RecursiveModelMerger.java

License:Open Source License

@Override
protected boolean mergeTreeWalk(TreeWalk treeWalk, boolean ignoreConflicts) throws IOException {
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("STARTING Recursive model merge."); //$NON-NLS-1$
    }/*from w  w w.  j  a  v a 2  s.  co  m*/
    final TreeWalkResourceVariantTreeProvider variantTreeProvider = new TreeWalkResourceVariantTreeProvider(
            getRepository(), treeWalk, T_BASE, T_OURS, T_THEIRS);
    final GitResourceVariantTreeSubscriber subscriber = new GitResourceVariantTreeSubscriber(
            variantTreeProvider);
    final RemoteResourceMappingContext remoteMappingContext = new SubscriberResourceMappingContext(subscriber,
            true);

    try {
        refreshRoots(subscriber.roots());
    } catch (CoreException e) {
        // We cannot be sure that Team and/or the merger implementations
        // will properly handle unrefreshed files. Fall back to merging
        // without workspace awareness.
        Activator.logError(MergeText.RecursiveModelMerger_RefreshError, e);
        return super.mergeTreeWalk(treeWalk, ignoreConflicts);
    }

    monitor.beginTask(MergeText.RecursiveModelMerger_BuildLogicalModels, ProgressMonitor.UNKNOWN);
    // Eager lookup for the logical models to avoid issues in case we
    // iterate over a file that does not exist locally before the rest of
    // its logical model.
    final LogicalModels logicalModels = new LogicalModels();
    logicalModels.build(variantTreeProvider.getKnownResources(), remoteMappingContext);
    monitor.endTask();

    if (monitor.isCancelled()) {
        throw new OperationCanceledException();
    }

    // We are done with the setup. We can now iterate over the tree walk and
    // either delegate to the logical model's merger if any or fall back to
    // standard git merging. Basically, any file that is not a part of a
    // logical model that defines its own specific merger will be handled as
    // it would by the RecursiveMerger.
    while (treeWalk.next()) {
        final int modeBase = treeWalk.getRawMode(T_BASE);
        final int modeOurs = treeWalk.getRawMode(T_OURS);
        final int modeTheirs = treeWalk.getRawMode(T_THEIRS);
        if (modeBase == 0 && modeOurs == 0 && modeTheirs == 0) {
            // untracked
            continue;
        }
        final String path = treeWalk.getPathString();
        if (handledPaths.contains(path)) {
            // This one has been handled as a result of a previous model
            // merge. Simply make sure we use its latest content if it is
            // not in conflict.
            if (treeWalk.isSubtree() && enterSubtree) {
                treeWalk.enterSubtree();
            }
            if (!unmergedPaths.contains(path)) {
                registerMergedPath(path);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Ignoring previously handled file: " + path); //$NON-NLS-1$
                }
            }
            continue;
        }

        final int nonZeroMode = modeBase != 0 ? modeBase : modeOurs != 0 ? modeOurs : modeTheirs;
        final IResource resource = variantTreeProvider.getResourceHandleForLocation(getRepository(), path,
                FileMode.fromBits(nonZeroMode) == FileMode.TREE);
        Set<IResource> logicalModel = logicalModels.getModel(resource);

        IResourceMappingMerger modelMerger = null;
        if (logicalModel != null) {
            try {
                // We need to refresh because new resources may have been added
                refreshRoots(subscriber.roots());
                modelMerger = LogicalModels.findAdapter(logicalModel, IResourceMappingMerger.class);
            } catch (CoreException e) {
                Activator.logError(MergeText.RecursiveModelMerger_AdaptError, e);
                // ignore this model and fall back to default
                if (!fallBackToDefaultMerge(treeWalk, ignoreConflicts)) {
                    cleanUp();
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info(
                                "FAILED - Recursive model merge, could not find appropriate merger and default merge failed."); //$NON-NLS-1$
                    }
                    return false;
                }
            }
        }
        if (modelMerger != null) {
            enterSubtree = true;

            boolean success = new ModelMerge(this, subscriber, remoteMappingContext, path, logicalModel,
                    modelMerger).run(new JGitProgressMonitorWrapper(monitor));
            if (!success) {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("FAILED - Recursive model merge."); //$NON-NLS-1$
                }
                return false;
            } else if (!unmergedPaths.contains(path)) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Merged model file: " + path); //$NON-NLS-1$
                }
                registerMergedPath(path);
            }
            if (treeWalk.isSubtree()) {
                enterSubtree = true;
            }
        } else if (!fallBackToDefaultMerge(treeWalk, ignoreConflicts)) {
            cleanUp();
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("FAILED - Recursive model merge, default merge failed."); //$NON-NLS-1$
            }
            return false;
        }
        if (treeWalk.isSubtree() && enterSubtree) {
            treeWalk.enterSubtree();
        }
    }
    if (!makeInSync.isEmpty()) {
        indexModelMergedFiles();
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("SUCCESS - Recursive model merge."); //$NON-NLS-1$
    }
    return true;
}

From source file:org.eclipse.emf.compare.egit.internal.merge.RecursiveModelMerger.java

License:Open Source License

private void add(String path, DirCacheBuilder cacheBuilder, TreeParserResourceVariant variant, int stage) {
    if (variant != null && !FileMode.TREE.equals(variant.getRawMode())) {
        DirCacheEntry e = new DirCacheEntry(path, stage);
        e.setFileMode(FileMode.fromBits(variant.getRawMode()));
        e.setObjectId(variant.getObjectId());
        e.setLastModified(0);/*from ww  w . j a v a 2  s.co m*/
        e.setLength(0);
        cacheBuilder.add(e);
    }
}

From source file:org.eclipse.emf.compare.egit.internal.merge.TreeWalkResourceVariantTreeProvider.java

License:Open Source License

/**
 * Constructs the resource variant trees by iterating over the given tree walk. This TreeWalk must contain
 * at least three trees corresponding to the three "sides" we need.
 * <p>//from   w ww . j  av a  2  s.  c o m
 * The tree walk will be reset to its initial state when we are done with the iteration.
 * </p>
 *
 * @param repository
 *            The repository this tree walk has been created for.
 * @param treeWalk
 *            The tree walk to iterate over.
 * @param baseIndex
 *            Index of the ancestor tree in the given TreeWalk (value returned by
 *            {@link TreeWalk#addTree(AbstractTreeIterator)})
 * @param ourIndex
 *            Index of our tree in the given TreeWalk (value returned by
 *            {@link TreeWalk#addTree(AbstractTreeIterator)})
 * @param theirIndex
 *            Index of their tree in the given TreeWalk (value returned by
 *            {@link TreeWalk#addTree(AbstractTreeIterator)})
 * @throws IOException
 *             if we somehow cannot iterate over the treewalk.
 */
public TreeWalkResourceVariantTreeProvider(Repository repository, TreeWalk treeWalk, int baseIndex,
        int ourIndex, int theirIndex) throws IOException {
    // Record the initial state of this tree walk before iterating
    final AbstractTreeIterator[] initialTrees = new AbstractTreeIterator[treeWalk.getTreeCount()];
    for (int i = 0; i < treeWalk.getTreeCount(); i++) {
        initialTrees[i] = treeWalk.getTree(i, AbstractTreeIterator.class);
    }

    final GitResourceVariantCache baseCache = new GitResourceVariantCache();
    final GitResourceVariantCache theirsCache = new GitResourceVariantCache();
    final GitResourceVariantCache oursCache = new GitResourceVariantCache();

    while (treeWalk.next()) {
        final int modeBase = treeWalk.getRawMode(baseIndex);
        final int modeOurs = treeWalk.getRawMode(ourIndex);
        final int modeTheirs = treeWalk.getRawMode(theirIndex);
        if (!hasSignificantDifference(modeBase, modeOurs, modeTheirs)) {
            // conflict on file modes, leave the default merger handle it
            continue;
        }

        final CanonicalTreeParser base = treeWalk.getTree(baseIndex, CanonicalTreeParser.class);
        final CanonicalTreeParser ours = treeWalk.getTree(ourIndex, CanonicalTreeParser.class);
        final CanonicalTreeParser theirs = treeWalk.getTree(theirIndex, CanonicalTreeParser.class);

        final int nonZeroMode = modeBase != 0 ? modeBase : modeOurs != 0 ? modeOurs : modeTheirs;
        final IResource resource = getResourceHandleForLocation(repository, treeWalk.getPathString(),
                FileMode.fromBits(nonZeroMode) == FileMode.TREE);

        // Resource variants only make sense for IResources.
        if (resource != null) {
            IPath workspacePath = resource.getFullPath();
            if (modeBase != 0) {
                baseCache.setVariant(resource,
                        TreeParserResourceVariant.create(repository, base, workspacePath));
            }
            if (modeOurs != 0) {
                oursCache.setVariant(resource,
                        TreeParserResourceVariant.create(repository, ours, workspacePath));
            }
            if (modeTheirs != 0) {
                theirsCache.setVariant(resource,
                        TreeParserResourceVariant.create(repository, theirs, workspacePath));
            }
        }

        if (treeWalk.isSubtree()) {
            treeWalk.enterSubtree();
        }
    }

    // TODO any better way to reset the tree walk after an iteration?
    treeWalk.reset();
    for (int i = 0; i < initialTrees.length; i++) {
        initialTrees[i].reset();
        treeWalk.addTree(initialTrees[i]);
    }

    baseTree = new GitCachedResourceVariantTree(baseCache);
    theirsTree = new GitCachedResourceVariantTree(theirsCache);
    oursTree = new GitCachedResourceVariantTree(oursCache);

    roots = new LinkedHashSet<IResource>();
    roots.addAll(baseCache.getRoots());
    roots.addAll(oursCache.getRoots());
    roots.addAll(theirsCache.getRoots());

    knownResources = new LinkedHashSet<IResource>();
    knownResources.addAll(baseCache.getKnownResources());
    knownResources.addAll(oursCache.getKnownResources());
    knownResources.addAll(theirsCache.getKnownResources());
}

From source file:org.eclipse.emf.compare.egit.internal.merge.TreeWalkResourceVariantTreeProvider.java

License:Open Source License

private boolean hasSignificantDifference(int modeBase, int modeOurs, int modeTheirs) {
    if (modeBase == 0) {
        if (FileMode.fromBits(modeOurs | modeTheirs) != FileMode.MISSING) {
            return true;
        } else {/*from   w ww  . jav  a2 s . c  o m*/
            return (FileMode.fromBits(modeOurs) == FileMode.TREE
                    && FileMode.fromBits(modeTheirs) != FileMode.TREE)
                    || (FileMode.fromBits(modeOurs) != FileMode.TREE
                            && FileMode.fromBits(modeTheirs) == FileMode.TREE);
        }
    }
    return FileMode.fromBits(modeBase & modeOurs) != FileMode.MISSING
            || FileMode.fromBits(modeBase & modeTheirs) != FileMode.MISSING;
}

From source file:org.gitective.core.filter.commit.CommitDiffFilter.java

License:Open Source License

@Override
public boolean include(final RevWalk walker, final RevCommit commit) throws IOException {
    final TreeWalk walk = createTreeWalk(walker, commit);
    final List<DiffEntry> diffs;
    final int treeCount = walk.getTreeCount();
    switch (treeCount) {
    case 0://from w  w w  . j a  va2s .c  om
    case 1:
        diffs = Collections.emptyList();
        break;
    case 2:
        diffs = DiffEntry.scan(walk);
        break;
    default:
        diffs = new ArrayList<DiffEntry>();
        final MutableObjectId currentId = new MutableObjectId();
        final int currentTree = treeCount - 1;
        while (walk.next()) {
            final int currentMode = walk.getRawMode(currentTree);
            int parentMode = 0;
            boolean same = false;
            for (int i = 0; i < currentTree; i++) {
                final int mode = walk.getRawMode(i);
                same = mode == currentMode && walk.idEqual(currentTree, i);
                if (same)
                    break;
                parentMode |= mode;
            }
            if (same)
                continue;

            final LocalDiffEntry diff = new LocalDiffEntry(walk.getPathString());
            diff.setOldMode(FileMode.fromBits(parentMode));
            diff.setNewMode(FileMode.fromBits(currentMode));
            walk.getObjectId(currentId, currentTree);
            diff.setNewId(AbbreviatedObjectId.fromObjectId(currentId));
            if (parentMode == 0 && currentMode != 0)
                diff.setChangeType(ChangeType.ADD);
            else if (parentMode != 0 && currentMode == 0)
                diff.setChangeType(ChangeType.DELETE);
            else
                diff.setChangeType(ChangeType.MODIFY);
            diffs.add(diff);
        }
    }
    if (detectRenames) {
        renameDetector.reset();
        renameDetector.addAll(diffs);
        return include(walker, commit, renameDetector.compute(walker.getObjectReader(), INSTANCE)) ? true
                : include(false);
    } else
        return include(walker, commit, diffs) ? true : include(false);
}