Example usage for org.eclipse.jgit.dircache DirCache unlock

List of usage examples for org.eclipse.jgit.dircache DirCache unlock

Introduction

In this page you can find the example usage for org.eclipse.jgit.dircache DirCache unlock.

Prototype

public void unlock() 

Source Link

Document

Unlock this file and abort this change.

Usage

From source file:com.microsoft.gittf.core.tasks.CloneTask.java

License:Open Source License

@Override
public TaskStatus run(final TaskProgressMonitor progressMonitor) throws Exception {
    final String taskName = Messages.formatString("CloneTask.CloningFormat", //$NON-NLS-1$
            tfsPath,//  w ww. j  a va  2 s.  c  o m
            bare ? repository.getDirectory().getAbsolutePath() : repository.getWorkTree().getAbsolutePath());

    progressMonitor.beginTask(taskName, 1,
            TaskProgressDisplay.DISPLAY_PROGRESS.combine(TaskProgressDisplay.DISPLAY_SUBTASK_DETAIL));

    /*
     * Query the changesets.
     */

    /* See if this is an actual server path. */
    final Item item = vcClient.getItem(tfsPath, versionSpec, DeletedState.NON_DELETED, GetItemsOptions.NONE);
    Check.notNull(item, "item"); //$NON-NLS-1$

    if (item.getItemType() != ItemType.FOLDER) {
        return new TaskStatus(TaskStatus.ERROR,
                Messages.formatString("CloneTask.CannotCloneFileFormat", tfsPath)); //$NON-NLS-1$
    }

    /* Determine the latest changeset on the server. */
    final Changeset[] changesets = vcClient.queryHistory(tfsPath, versionSpec, 0, RecursionType.FULL, null,
            new ChangesetVersionSpec(0), versionSpec, depth, false, false, false, false);

    /*
     * Create and configure the repository.
     */

    repository.create(bare);

    final ConfigureRepositoryTask configureTask = new ConfigureRepositoryTask(repository, serverURI, tfsPath);
    configureTask.setTag(tag);

    final TaskStatus configureStatus = new TaskExecutor(new NullTaskProgressMonitor()).execute(configureTask);

    if (!configureStatus.isOK()) {
        return configureStatus;
    }

    if (changesets.length > 0) {
        ObjectId lastCommitID = null;
        ObjectId lastTreeID = null;
        Item[] previousChangesetItems = null;

        /*
         * Download changesets.
         */
        final int numberOfChangesetToDownload = changesets.length;

        progressMonitor.setWork(numberOfChangesetToDownload);

        for (int i = numberOfChangesetToDownload; i > 0; i--) {
            CreateCommitForChangesetVersionSpecTask commitTask = new CreateCommitForChangesetVersionSpecTask(
                    repository, vcClient, changesets[i - 1], previousChangesetItems, lastCommitID, witClient);

            TaskStatus commitStatus = new TaskExecutor(progressMonitor.newSubTask(1)).execute(commitTask);

            if (!commitStatus.isOK()) {
                return commitStatus;
            }

            lastCommitID = commitTask.getCommitID();
            lastTreeID = commitTask.getCommitTreeID();
            previousChangesetItems = commitTask.getCommittedItems();

            Check.notNull(lastCommitID, "lastCommitID"); //$NON-NLS-1$
            Check.notNull(lastTreeID, "lastTreeID"); //$NON-NLS-1$

            new ChangesetCommitMap(repository).setChangesetCommit(changesets[i - 1].getChangesetID(),
                    commitTask.getCommitID());

            progressMonitor.displayVerbose(Messages.formatString("CloneTask.ClonedFormat", //$NON-NLS-1$
                    Integer.toString(changesets[i - 1].getChangesetID()),
                    ObjectIdUtil.abbreviate(repository, lastCommitID)));
        }

        progressMonitor.setDetail(Messages.getString("CloneTask.Finalizing")); //$NON-NLS-1$

        /* Update master head reference */
        RefUpdate ref = repository.updateRef(Constants.R_HEADS + Constants.MASTER);
        ref.setNewObjectId(lastCommitID);
        ref.update();

        /* Create tfs branch */
        TfsBranchUtil.create(repository, Constants.R_HEADS + Constants.MASTER);

        /*
         * Check out the cloned commit.
         */
        if (!bare) {
            DirCache dirCache = repository.lockDirCache();
            DirCacheCheckout checkout = new DirCacheCheckout(repository, dirCache, lastTreeID);
            checkout.checkout();
            dirCache.unlock();

            RepositoryUtil.fixFileAttributes(repository);
        }

        progressMonitor.endTask();

        final int finalChangesetID = changesets[0].getChangesetID();

        if (numberOfChangesetToDownload == 1) {
            progressMonitor.displayMessage(Messages.formatString("CloneTask.ClonedFormat", //$NON-NLS-1$
                    Integer.toString(finalChangesetID), ObjectIdUtil.abbreviate(repository, lastCommitID)));
        } else {
            progressMonitor.displayMessage(Messages.formatString("CloneTask.ClonedMultipleFormat", //$NON-NLS-1$
                    changesets.length, Integer.toString(finalChangesetID),
                    ObjectIdUtil.abbreviate(repository, lastCommitID)));
        }
    } else {
        // the folder exists on the server but is empty

        progressMonitor.displayMessage(Messages.getString("CloneTask.NothingToDownload")); //$NON-NLS-1$

        progressMonitor.displayMessage(Messages.formatString("CloneTask.ClonedFolderEmptyFormat", //$NON-NLS-1$
                tfsPath));
    }

    log.info("Clone task completed."); //$NON-NLS-1$

    return TaskStatus.OK_STATUS;
}

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

    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.che.git.impl.jgit.JGitDiffPage.java

License:Open Source License

/**
 * Show changes between index and working tree.
 *
 * @param formatter/*ww w  .  j a  v a 2  s  . co  m*/
 *            diff formatter
 * @return list of diff entries
 * @throws IOException
 *             if any i/o errors occurs
 */
private List<DiffEntry> indexToWorkingTree(DiffFormatter formatter) throws IOException {
    DirCache dirCache = null;
    ObjectReader reader = repository.newObjectReader();
    List<DiffEntry> diff;
    try {
        dirCache = repository.lockDirCache();
        DirCacheIterator iterA = new DirCacheIterator(dirCache);
        FileTreeIterator iterB = new FileTreeIterator(repository);
        // Seems bug in DiffFormatter when work with working. Disable detect
        // renames by formatter and do it later.
        formatter.setDetectRenames(false);
        diff = formatter.scan(iterA, iterB);
        if (!request.isNoRenames()) {
            // Detect renames.
            RenameDetector renameDetector = createRenameDetector();
            ContentSource.Pair sourcePairReader = new ContentSource.Pair(ContentSource.create(reader),
                    ContentSource.create(iterB));
            renameDetector.addAll(diff);
            diff = renameDetector.compute(sourcePairReader, NullProgressMonitor.INSTANCE);
        }
    } finally {
        reader.close();
        if (dirCache != null) {
            dirCache.unlock();
        }
    }
    return diff;
}

From source file:org.eclipse.che.git.impl.jgit.JGitDiffPage.java

License:Open Source License

/**
 * Show changes between specified revision and index. If
 * <code>commitId == null</code> then view changes between HEAD and index.
 *
 * @param commitId//from   w ww  . j  av  a  2s .  c  om
 *            id of commit, pass <code>null</code> is the same as pass HEAD
 * @param formatter
 *            diff formatter
 * @return list of diff entries
 * @throws IOException
 *             if any i/o errors occurs
 */
private List<DiffEntry> commitToIndex(String commitId, DiffFormatter formatter) throws IOException {
    if (commitId == null) {
        commitId = Constants.HEAD;
    }

    ObjectId commitA = repository.resolve(commitId);
    if (commitA == null) {
        throw new IllegalArgumentException("Invalid commit id " + commitId);
    }
    RevTree treeA;
    try (RevWalk revWalkA = new RevWalk(repository)) {
        treeA = revWalkA.parseTree(commitA);
    }

    DirCache dirCache = null;
    List<DiffEntry> diff;
    try (ObjectReader reader = repository.newObjectReader()) {
        dirCache = repository.lockDirCache();
        CanonicalTreeParser iterA = new CanonicalTreeParser();
        iterA.reset(reader, treeA);
        DirCacheIterator iterB = new DirCacheIterator(dirCache);
        if (!request.isNoRenames()) {
            // Use embedded RenameDetector it works well with index and
            // revision history.
            formatter.setDetectRenames(true);
            int renameLimit = request.getRenameLimit();
            if (renameLimit > 0) {
                formatter.getRenameDetector().setRenameLimit(renameLimit);
            }
        }
        diff = formatter.scan(iterA, iterB);
    } finally {
        if (dirCache != null) {
            dirCache.unlock();
        }
    }
    return diff;
}

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

License:Open Source License

public boolean deleteFile(final IResourceTree tree, final IFile file, final int updateFlags,
        final IProgressMonitor monitor) {
    final boolean force = (updateFlags & IResource.FORCE) == IResource.FORCE;
    if (!force && !tree.isSynchronized(file, IResource.DEPTH_ZERO))
        return false;

    final RepositoryMapping map = RepositoryMapping.getMapping(file);
    if (map == null)
        return false;

    try {/*from   w  w  w  .j av a 2  s  .  c  o m*/
        final DirCache dirc = map.getRepository().lockDirCache();
        final int first = dirc.findEntry(map.getRepoRelativePath(file));
        if (first < 0) {
            dirc.unlock();
            return false;
        }

        final DirCacheBuilder edit = dirc.builder();
        if (first > 0)
            edit.keep(0, first);
        final int next = dirc.nextEntry(first);
        if (next < dirc.getEntryCount())
            edit.keep(next, dirc.getEntryCount() - next);
        if (!edit.commit())
            tree.failed(new Status(IStatus.ERROR, Activator.getPluginId(), 0,
                    CoreText.MoveDeleteHook_operationError, null));
        tree.standardDeleteFile(file, updateFlags, monitor);
    } catch (IOException e) {
        tree.failed(new Status(IStatus.ERROR, Activator.getPluginId(), 0,
                CoreText.MoveDeleteHook_operationError, e));
    }
    return true;
}

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

License:Open Source License

public boolean moveFile(final IResourceTree tree, final IFile srcf, final IFile dstf, final int updateFlags,
        final IProgressMonitor monitor) {
    final boolean force = (updateFlags & IResource.FORCE) == IResource.FORCE;
    if (!force && !tree.isSynchronized(srcf, IResource.DEPTH_ZERO))
        return false;

    final RepositoryMapping srcm = RepositoryMapping.getMapping(srcf);
    if (srcm == null)
        return false;
    final RepositoryMapping dstm = RepositoryMapping.getMapping(dstf);

    try {//w ww. ja v  a 2s .c  o  m
        final DirCache sCache = srcm.getRepository().lockDirCache();
        final String sPath = srcm.getRepoRelativePath(srcf);
        final DirCacheEntry sEnt = sCache.getEntry(sPath);
        if (sEnt == null) {
            sCache.unlock();
            return false;
        }

        final DirCacheEditor sEdit = sCache.editor();
        sEdit.add(new DirCacheEditor.DeletePath(sEnt));
        if (dstm != null && dstm.getRepository() == srcm.getRepository()) {
            final String dPath = srcm.getRepoRelativePath(dstf);
            sEdit.add(new DirCacheEditor.PathEdit(dPath) {
                @Override
                public void apply(final DirCacheEntry dEnt) {
                    dEnt.copyMetaData(sEnt);
                }
            });
        }
        if (!sEdit.commit())
            tree.failed(new Status(IStatus.ERROR, Activator.getPluginId(), 0,
                    CoreText.MoveDeleteHook_operationError, null));

        tree.standardMoveFile(srcf, dstf, updateFlags, monitor);
    } catch (IOException e) {
        tree.failed(new Status(IStatus.ERROR, Activator.getPluginId(), 0,
                CoreText.MoveDeleteHook_operationError, e));
    }
    return true;
}

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();
        return false;
    }//from ww w .java2s.c om

    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.storage.IndexFileRevisionTest.java

License:Open Source License

private void buildIndex(DirCacheEntry... entries) throws IOException {
    DirCache dirCache = repository.lockDirCache();
    DirCacheBuilder builder = dirCache.builder();
    try {//from  ww w  .j ava 2 s  . co  m
        for (DirCacheEntry entry : entries)
            builder.add(entry);
        builder.commit();
    } finally {
        dirCache.unlock();
    }
}

From source file:org.eclipse.egit.core.op.DiscardChangesOperation.java

License:Open Source License

private void discardChange(IResource res, Repository repository) throws IOException {
    String resRelPath = RepositoryMapping.getMapping(res).getRepoRelativePath(res);
    DirCache dc = repository.lockDirCache();
    DirCacheEntry entry = dc.getEntry(resRelPath);
    File file = new File(res.getLocationURI());
    DirCacheCheckout.checkoutEntry(repository, file, entry);
    dc.unlock();
}

From source file:org.eclipse.egit.core.op.ResetOperation.java

License:Open Source License

private void resetIndex() throws TeamException {
    DirCache dc = null;
    try {// w  w w . j  a va  2 s  . c  om
        dc = repository.lockDirCache();
        dc.clear();
        DirCacheBuilder dcb = dc.builder();
        dcb.addTree(new byte[0], 0, repository.newObjectReader(), commit.getTree());
        dcb.commit();
    } catch (IOException e) {
        throw new TeamException(CoreText.ResetOperation_readingIndex, e);
    } finally {
        if (dc != null)
            dc.unlock();
    }
}