Example usage for org.eclipse.jgit.dircache DirCacheEntry getPathString

List of usage examples for org.eclipse.jgit.dircache DirCacheEntry getPathString

Introduction

In this page you can find the example usage for org.eclipse.jgit.dircache DirCacheEntry getPathString.

Prototype

public String getPathString() 

Source Link

Document

Get the entry's complete path.

Usage

From source file:com.gitblit.build.BuildGhPages.java

License:Apache License

/**
 * Creates an in-memory index of the issue change.
 * // w w  w .  j  ava2  s .  com
 * @param repo
 * @param headId
 * @param sourceFolder
 * @param obliterate
 *            if true the source folder tree is used as the new tree for
 *            gh-pages and non-existent files are considered deleted
 * @return an in-memory index
 * @throws IOException
 */
private static DirCache createIndex(Repository repo, ObjectId headId, File sourceFolder, boolean obliterate)
        throws IOException {

    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();

    try {
        // Add all files to the temporary index
        Set<String> ignorePaths = new TreeSet<String>();
        List<File> files = listFiles(sourceFolder);
        for (File file : files) {
            // create an index entry for the file
            final DirCacheEntry dcEntry = new DirCacheEntry(
                    StringUtils.getRelativePath(sourceFolder.getPath(), file.getPath()));
            dcEntry.setLength(file.length());
            dcEntry.setLastModified(file.lastModified());
            dcEntry.setFileMode(FileMode.REGULAR_FILE);

            // add this entry to the ignore paths set
            ignorePaths.add(dcEntry.getPathString());

            // insert object
            InputStream inputStream = new FileInputStream(file);
            try {
                dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, file.length(), inputStream));
            } finally {
                inputStream.close();
            }

            // add to temporary in-core index
            dcBuilder.add(dcEntry);
        }

        if (!obliterate) {
            // Traverse HEAD to add all other paths
            TreeWalk treeWalk = new TreeWalk(repo);
            int hIdx = -1;
            if (headId != null)
                hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
            treeWalk.setRecursive(true);

            while (treeWalk.next()) {
                String path = treeWalk.getPathString();
                CanonicalTreeParser hTree = null;
                if (hIdx != -1)
                    hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
                if (!ignorePaths.contains(path)) {
                    // add entries from HEAD for all other paths
                    if (hTree != null) {
                        // create a new DirCacheEntry with data retrieved
                        // from
                        // HEAD
                        final DirCacheEntry dcEntry = new DirCacheEntry(path);
                        dcEntry.setObjectId(hTree.getEntryObjectId());
                        dcEntry.setFileMode(hTree.getEntryFileMode());

                        // add to temporary in-core index
                        dcBuilder.add(dcEntry);
                    }
                }
            }

            // release the treewalk
            treeWalk.release();
        }

        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.release();
    }
    return inCoreIndex;
}

From source file:com.gitblit.tickets.BranchTicketService.java

License:Apache License

/**
 * Creates an in-memory index of the ticket change.
 *
 * @param changeId/*from  w w w  .ja v  a  2s .c  om*/
 * @param change
 * @return an in-memory index
 * @throws IOException
 */
private DirCache createIndex(Repository db, long ticketId, Change change)
        throws IOException, ClassNotFoundException, NoSuchFieldException {

    String ticketPath = toTicketPath(ticketId);
    DirCache newIndex = DirCache.newInCore();
    DirCacheBuilder builder = newIndex.builder();
    ObjectInserter inserter = db.newObjectInserter();

    Set<String> ignorePaths = new TreeSet<String>();
    try {
        // create/update the journal
        // exclude the attachment content
        List<Change> changes = getJournal(db, ticketId);
        changes.add(change);
        String journal = TicketSerializer.serializeJournal(changes).trim();

        byte[] journalBytes = journal.getBytes(Constants.ENCODING);
        String journalPath = ticketPath + "/" + JOURNAL;
        final DirCacheEntry journalEntry = new DirCacheEntry(journalPath);
        journalEntry.setLength(journalBytes.length);
        journalEntry.setLastModified(change.date.getTime());
        journalEntry.setFileMode(FileMode.REGULAR_FILE);
        journalEntry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, journalBytes));

        // add journal to index
        builder.add(journalEntry);
        ignorePaths.add(journalEntry.getPathString());

        // Add any attachments to the index
        if (change.hasAttachments()) {
            for (Attachment attachment : change.attachments) {
                // build a path name for the attachment and mark as ignored
                String path = toAttachmentPath(ticketId, attachment.name);
                ignorePaths.add(path);

                // create an index entry for this attachment
                final DirCacheEntry entry = new DirCacheEntry(path);
                entry.setLength(attachment.content.length);
                entry.setLastModified(change.date.getTime());
                entry.setFileMode(FileMode.REGULAR_FILE);

                // insert object
                entry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, attachment.content));

                // add to temporary in-core index
                builder.add(entry);
            }
        }

        for (DirCacheEntry entry : JGitUtils.getTreeEntries(db, BRANCH, ignorePaths)) {
            builder.add(entry);
        }

        // finish the index
        builder.finish();
    } finally {
        inserter.close();
    }
    return newIndex;
}

From source file:com.github.kaitoy.goslings.server.dao.jgit.RepositoryDaoImpl.java

License:Open Source License

@Override
public Index getIndex(String token) {
    try {//from w  w w.j av  a 2 s . c om
        DirCache index = resolver.getRepository(token).readDirCache();
        int numEntries = index.getEntryCount();
        List<IndexEntry> entries = new ArrayList<>(numEntries);
        for (int i = 0; i < numEntries; i++) {
            DirCacheEntry dce = index.getEntry(i);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            dce.getFileMode().copyTo(baos);
            entries.add(new IndexEntry(dce.getObjectId().getName(), dce.getPathString(), baos.toString(),
                    dce.getStage()));
        }
        return new Index(entries.toArray(new IndexEntry[numEntries]));
    } catch (NoWorkTreeException e) {
        String message = new StringBuilder().append("The repository ").append(token)
                .append(" is bare and so doesn't have index.").toString();
        LOG.error(message, e);
        throw new DaoException(message, e);
    } catch (CorruptObjectException e) {
        String message = new StringBuilder().append("Filed to get index of the repository ").append(token)
                .append(" due to an internal error.").toString();
        LOG.error(message, e);
        throw new DaoException(message, e);
    } catch (IOException e) {
        String message = new StringBuilder().append("Filed to get index of the repository ").append(token)
                .append(" due to an I/O error.").toString();
        LOG.error(message, e);
        throw new DaoException(message, e);
    }

}

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

License:Eclipse Distribution License

/**
 * adds a entry to the index builder which is a copy of the specified
 * DirCacheEntry/*from   ww w . j  a v  a 2 s  . c  om*/
 *
 * @param e
 *          the entry which should be copied
 *
 * @return the entry which was added to the index
 */
private DirCacheEntry keep(DirCacheEntry e) {
    DirCacheEntry newEntry = new DirCacheEntry(e.getPathString(), e.getStage());
    newEntry.setFileMode(e.getFileMode());
    newEntry.setObjectId(e.getObjectId());
    newEntry.setLastModified(e.getLastModified());
    newEntry.setLength(e.getLength());
    this.builder.add(newEntry);
    return newEntry;
}

From source file:ezbake.deployer.publishers.openShift.RhcApplication.java

License:Apache License

public void addStreamAsFile(File p, InputStream ios, Set<PosixFilePermission> filePermissions)
        throws DeploymentException {
    File resolvedPath = Files.resolve(getGitRepoPath(), p);
    if (Files.isDirectory(resolvedPath)) {
        throw new DeploymentException(
                "Directory exist by the name of file wishing to write to: " + resolvedPath.toString());
    }//from  w w  w  .j a v a2s  .com

    try {
        Files.createDirectories(resolvedPath.getParent());
        OutputStream oos = new FileOutputStream(resolvedPath);
        boolean permissions = (filePermissions != null && !filePermissions.isEmpty());
        DirCache cache = null;
        try {
            IOUtils.copy(ios, oos);
            if (permissions) {
                Files.setPosixFilePermissions(resolvedPath, filePermissions);
            }

            cache = gitRepo.add().addFilepattern(p.toString()).call();
            if (permissions) {
                // Add executable permissions
                cache.lock();
                // Most of these mthods throw an IOException so we will catch that and unlock
                DirCacheEntry entry = cache.getEntry(0);
                log.debug("Setting executable permissions for: " + entry.getPathString());
                entry.setFileMode(FileMode.EXECUTABLE_FILE);
                cache.write();
                cache.commit();
            }
        } catch (IOException e) {
            log.error("[" + getApplicationName() + "]" + "Error writing to file: " + resolvedPath.toString(),
                    e);
            // Most of the DirCache entries should just thow IOExceptions
            if (cache != null) {
                cache.unlock();
            }
            throw new DeploymentException("Error writing to file: " + resolvedPath.toString());
        } catch (GitAPIException e) {
            log.error("[" + getApplicationName() + "]" + "Error writing to file: " + resolvedPath.toString(),
                    e);
            throw new DeploymentException("Error writing to file: " + resolvedPath.toString());
        } finally {
            IOUtils.closeQuietly(oos);
        }
    } catch (IOException e) {
        log.error(
                "[" + getApplicationName() + "]" + "Error opening file for output: " + resolvedPath.toString(),
                e);
        throw new DeploymentException("Error opening file for output: " + resolvedPath.toString());
    }

}

From source file:org.eclipse.egit.core.GitMoveDeleteHook.java

License:Open Source License

private boolean moveIndexContent(String dPath, final RepositoryMapping srcm, final String sPath)
        throws IOException {
    final DirCache sCache = srcm.getRepository().lockDirCache();
    final DirCacheEntry[] sEnt = sCache.getEntriesWithin(sPath);
    if (sEnt.length == 0) {
        sCache.unlock();//from w ww . j  a v a 2 s.  c o m
        return false;
    }

    final DirCacheEditor sEdit = sCache.editor();
    sEdit.add(new DirCacheEditor.DeleteTree(sPath));
    final int sPathLen = sPath.length() + 1;
    for (final DirCacheEntry se : sEnt) {
        final String p = se.getPathString().substring(sPathLen);
        sEdit.add(new DirCacheEditor.PathEdit(dPath + p) {
            @Override
            public void apply(final DirCacheEntry dEnt) {
                dEnt.copyMetaData(se);
            }
        });
    }
    return sEdit.commit();
}

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

License:Open Source License

/**
 * Constructs the resource variant trees by iterating over the given
 * repository's DirCache entries./*w w  w.ja  v  a 2s .  c o  m*/
 *
 * @param repository
 *            The repository which DirCache info we need to cache as
 *            IResourceVariantTrees.
 * @throws IOException
 *             if we somehow cannot read the DirCache.
 */
public DirCacheResourceVariantTreeProvider(Repository repository) 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 IPath path = new Path(entry.getPathString());
        final IResource resource = ResourceUtil.getResourceHandleForLocation(path);
        // 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:
            // Skipped on purpose (no conflict)
            break;
        case DirCacheEntry.STAGE_1:
            baseCache.setVariant(resource, IndexResourceVariant.create(repository, entry));
            break;
        case DirCacheEntry.STAGE_2:
            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.egit.core.internal.merge.ResourceVariantTest.java

License:Open Source License

@Test
public void testIndexVariantsConflict() throws Exception {
    File file1 = testRepo.createFile(iProject, "file1");
    IFile iFile1 = testRepo.getIFile(iProject, file1);

    setupConflictingBranches();// w w w . j  ava 2  s.co  m
    // end setup

    // create a conflict to force multiple stages
    new MergeOperation(repo, BRANCH).execute(null);

    DirCache cache = repo.readDirCache();
    // 3 stages for file 1, 2 stages for file 2
    assertEquals(5, cache.getEntryCount());
    for (int i = 0; i < cache.getEntryCount(); i++) {
        final DirCacheEntry entry = cache.getEntry(i);

        AbstractGitResourceVariant variant = IndexResourceVariant.create(repo, entry);
        assertEquals(entry.getObjectId().getName(), variant.getContentIdentifier());
        assertEquals(entry.getObjectId(), variant.getObjectId());
        assertEquals(entry.getRawMode(), variant.getRawMode());
        if (iFile1.getName().equals(variant.getName())) {
            switch (entry.getStage()) {
            case DirCacheEntry.STAGE_1:
                assertContentEquals(variant, INITIAL_CONTENT_1);
                break;
            case DirCacheEntry.STAGE_2:
                assertContentEquals(variant, INITIAL_CONTENT_1 + MASTER_CHANGE);
                break;
            case DirCacheEntry.STAGE_3:
                assertContentEquals(variant, BRANCH_CHANGE + INITIAL_CONTENT_1);
                break;
            case DirCacheEntry.STAGE_0:
            default:
                fail("Unexpected entry stage " + entry.getStage() + " in the index for file "
                        + entry.getPathString());
                break;
            }
        } else {
            switch (entry.getStage()) {
            case DirCacheEntry.STAGE_2:
                assertContentEquals(variant, INITIAL_CONTENT_2 + MASTER_CHANGE);
                break;
            case DirCacheEntry.STAGE_3:
                assertContentEquals(variant, BRANCH_CHANGE + INITIAL_CONTENT_2);
                break;
            case DirCacheEntry.STAGE_0:
            case DirCacheEntry.STAGE_1:
            default:
                fail("Unexpected entry stage " + entry.getStage() + " in the index for file "
                        + entry.getPathString());
                break;
            }
        }
    }
}

From source file:org.eclipse.egit.core.internal.storage.IndexResourceVariant.java

License:Open Source License

/**
 * Constructs a resource variant corresponding to the given DirCache entry.
 *
 * @param repository/*from ww  w. j  a  va 2s.  c  om*/
 *            Repository from which this DirCacheEntry was extracted.
 * @param entry
 *            The DirCacheEntry for which content we need an
 *            IResourceVariant.
 * @return The created variant.
 */
public static IndexResourceVariant create(Repository repository, DirCacheEntry entry) {
    final String path = entry.getPathString();
    final boolean isContainer = FileMode.TREE.equals(entry.getFileMode());
    final ObjectId objectId = entry.getObjectId();
    final int rawMode = entry.getRawMode();

    return new IndexResourceVariant(repository, path, isContainer, objectId, rawMode);
}

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//from   ww w  .ja  va2  s.com
 *            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());
}