Example usage for org.eclipse.jgit.lib Repository lockDirCache

List of usage examples for org.eclipse.jgit.lib Repository lockDirCache

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository lockDirCache.

Prototype

@NonNull
public DirCache lockDirCache() throws NoWorkTreeException, CorruptObjectException, IOException 

Source Link

Document

Create a new in-core index representation, lock it, and read from disk.

Usage

From source file:com.bacoder.scmtools.git.internal.CloneAndProcessCommand.java

License:Apache License

@Override
protected void doCheckout(final Repository repository, RevCommit commit)
        throws MissingObjectException, IncorrectObjectTypeException, IOException, GitAPIException {
    DirCache dirCache;/* w  w w. j a  va  2s .  c  o m*/
    if (isInMemory()) {
        dirCache = new InMemoryDirCache(repository.getIndexFile(), repository.getFS());
        dirCache.setRepository(repository);
    } else {
        dirCache = repository.lockDirCache();
    }
    CloneAndProcessDirCacheCheckout checkout = new CloneAndProcessDirCacheCheckout(repository, dirCache,
            commit.getTree(), pathPrefix);
    checkout.setProcessor(processor);
    checkout.checkout();

    submodulesConfig = checkout.getSubmodulesConfig();
    if (cloneSubmodules) {
        cloneSubmodules(repository);
    }
}

From source file:com.google.gerrit.server.git.SubmoduleOpTest.java

License:Apache License

/**
 * It adds an entry to index.// w  w w.ja v a2 s. c o m
 *
 * @param path The entry path.
 * @param fileMode The entry file mode.
 * @param objectId The ObjectId value of the entry.
 * @param repository The repository instance.
 * @throws IOException If an I/O exception occurs.
 */
private void addEntryToIndex(final String path, final FileMode fileMode, final AnyObjectId objectId,
        final Repository repository) throws IOException {
    final DirCacheEntry e = new DirCacheEntry(path);
    e.setFileMode(fileMode);
    e.setObjectId(objectId);

    final DirCacheBuilder dirCacheBuilder = repository.lockDirCache().builder();
    dirCacheBuilder.add(e);
    dirCacheBuilder.commit();
}

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

License:Open Source License

@Test
public void testMoveFileWithConflictsShouldBeCanceled() throws Exception {
    TestProject project = initRepoInsideProjectInsideWorkspace();
    String filePath = "file.txt";
    IFile file = testUtils.addFileToProject(project.getProject(), filePath, "some text");

    Repository repo = testRepository.getRepository();
    DirCache index = repo.lockDirCache();
    DirCacheBuilder builder = index.builder();
    addUnmergedEntry(filePath, builder);
    builder.commit();//from   ww w .j a  v  a  2s  .c o  m

    try {
        file.move(new Path("destination.txt"), false, null);
        fail("Expected move of file with conflicts to fail.");
    } catch (CoreException e) {
        IStatus status = e.getStatus();
        assertNotNull(status);
        assertEquals(IStatus.WARNING, status.getSeverity());
    }

    assertTrue("File should still exist at old location", file.exists());
    DirCache indexAfter = repo.readDirCache();
    DirCacheEntry entry = indexAfter.getEntry(filePath);
    assertEquals("Expected entry to still be in non-zero (conflict) stage", DirCacheEntry.STAGE_1,
            entry.getStage());
}

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

License:Open Source License

@Test
public void testMoveFolderWithFileWithConflictsShouldBeCanceled() throws Exception {
    TestProject project = initRepoInsideProjectInsideWorkspace();
    String filePath = "folder/file.txt";
    IFile file = testUtils.addFileToProject(project.getProject(), filePath, "some text");

    Repository repo = testRepository.getRepository();
    DirCache index = repo.lockDirCache();
    DirCacheBuilder builder = index.builder();
    addUnmergedEntry(filePath, builder);
    builder.commit();//from  w w w  .j a  v a  2 s  . c  o  m

    try {
        project.getProject().getFolder("folder").move(project.getProject().getFolder("newfolder").getFullPath(),
                false, null);
        fail("Expected move of folder with file with conflicts to fail.");
    } catch (CoreException e) {
        IStatus status = e.getStatus();
        assertNotNull(status);
        assertEquals(IStatus.WARNING, status.getSeverity());
    }

    assertTrue("File should still exist at old location", file.exists());
    DirCache indexAfter = repo.readDirCache();
    DirCacheEntry entry = indexAfter.getEntry(filePath);
    assertEquals("Expected entry to still be in non-zero (conflict) stage", DirCacheEntry.STAGE_1,
            entry.getStage());
}

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

License:Open Source License

private void assumeValid(final IResource resource) throws CoreException {
    final IProject proj = resource.getProject();
    final GitProjectData pd = GitProjectData.get(proj);
    if (pd == null)
        return;/*from  w  ww .j  a  va2 s.  co m*/
    final RepositoryMapping rm = pd.getRepositoryMapping(resource);
    if (rm == null)
        return;
    final Repository db = rm.getRepository();

    DirCache cache = caches.get(db);
    if (cache == null) {
        try {
            cache = db.lockDirCache();
        } catch (IOException err) {
            throw new CoreException(Activator.error(CoreText.UntrackOperation_failed, err));
        }
        caches.put(db, cache);
        mappings.put(rm, rm);
    }

    final String path = rm.getRepoRelativePath(resource);
    if (resource instanceof IContainer) {
        for (final DirCacheEntry ent : cache.getEntriesWithin(path))
            ent.setAssumeValid(assumeUnchanged);
    } else {
        final DirCacheEntry ent = cache.getEntry(path);
        if (ent != null)
            ent.setAssumeValid(assumeUnchanged);
    }
}

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  w  ww  . j ava 2s .  c  o m
}

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

License:Open Source License

private void remove(final IResource path) throws CoreException {
    final IProject proj = path.getProject();
    final GitProjectData pd = GitProjectData.get(proj);
    if (pd == null)
        return;//from   w w w. ja  v a2s.co  m
    final RepositoryMapping rm = pd.getRepositoryMapping(path);
    if (rm == null)
        return;
    final Repository db = rm.getRepository();

    DirCacheEditor e = edits.get(db);
    if (e == null) {
        try {
            e = db.lockDirCache().editor();
        } catch (IOException err) {
            throw new CoreException(Activator.error(CoreText.UntrackOperation_failed, err));
        }
        edits.put(db, e);
        mappings.put(rm, rm);
    }

    if (path instanceof IContainer)
        e.add(new DirCacheEditor.DeleteTree(rm.getRepoRelativePath(path)));
    else
        e.add(new DirCacheEditor.DeletePath(rm.getRepoRelativePath(path)));
}

From source file:org.eclipse.egit.ui.internal.actions.CompareWithIndexActionHandler.java

License:Open Source License

private ITypedElement getHeadTypedElement(final IFile baseFile) throws IOException {
    final RepositoryMapping mapping = RepositoryMapping.getMapping(baseFile.getProject());
    final Repository repository = mapping.getRepository();
    final String gitPath = mapping.getRepoRelativePath(baseFile);

    DirCache dc = repository.lockDirCache();
    final DirCacheEntry entry = dc.getEntry(gitPath);
    dc.unlock();//from  w ww.  java2s  .co m
    if (entry == null) {
        // the file cannot be found in the index
        return new GitCompareFileRevisionEditorInput.EmptyTypedElement(
                NLS.bind(UIText.CompareWithIndexAction_FileNotInIndex, baseFile.getName()));
    }

    IFileRevision nextFile = GitFileRevision.inIndex(repository, gitPath);
    final EditableRevision next = new EditableRevision(nextFile);

    IContentChangeListener listener = new IContentChangeListener() {
        public void contentChanged(IContentChangeNotifier source) {
            final byte[] newContent = next.getModifiedContent();
            DirCache cache = null;
            try {
                cache = repository.lockDirCache();
                DirCacheEditor editor = cache.editor();
                editor.add(new PathEdit(gitPath) {
                    @Override
                    public void apply(DirCacheEntry ent) {
                        ent.copyMetaData(entry);

                        ObjectInserter inserter = repository.newObjectInserter();
                        ent.copyMetaData(entry);
                        ent.setLength(newContent.length);
                        ent.setLastModified(System.currentTimeMillis());
                        InputStream in = new ByteArrayInputStream(newContent);
                        try {
                            ent.setObjectId(inserter.insert(Constants.OBJ_BLOB, newContent.length, in));
                            inserter.flush();
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        } finally {
                            try {
                                in.close();
                            } catch (IOException e) {
                                // ignore here
                            }
                        }
                    }
                });
                try {
                    editor.commit();
                } catch (RuntimeException e) {
                    if (e.getCause() instanceof IOException)
                        throw (IOException) e.getCause();
                    else
                        throw e;
                }

            } catch (IOException e) {
                Activator.handleError(UIText.CompareWithIndexAction_errorOnAddToIndex, e, true);
            } finally {
                if (cache != null)
                    cache.unlock();
            }
        }
    };

    next.addContentChangeListener(listener);
    return next;
}

From source file:org.eclipse.egit.ui.internal.CompareUtils.java

License:Open Source License

/**
 * Creates {@link ITypedElement} of file that was cached
 *
 * @param gitPath/*www. j  av  a 2 s.c om*/
 * @param db
 * @return {@link ITypedElement} instance for given cached file or
 *         {@code null} if file isn't cached
 */
public static ITypedElement getFileCachedRevisionTypedElement(String gitPath, Repository db) {
    try {
        DirCache dc = db.lockDirCache();
        DirCacheEntry entry = dc.getEntry(gitPath);
        dc.unlock();

        // check if file is staged
        if (entry != null) {
            return new FileRevisionTypedElement(GitFileRevision.inIndex(db, gitPath));
        }
    } catch (IOException e) {
        Activator.error(NLS.bind(UIText.GitHistoryPage_errorLookingUpPath, gitPath), e);
    }

    return new GitCompareFileRevisionEditorInput.EmptyTypedElement(NLS.bind(
            UIText.CompareWithIndexAction_FileNotInIndex, gitPath.substring(gitPath.lastIndexOf("/")) + 1)); //$NON-NLS-1$
}

From source file:org.eclipse.egit.ui.wizards.clone.GitCloneWizardTestBase.java

License:Open Source License

protected void cloneRepo(File destRepo, RepoRemoteBranchesPage remoteBranches) throws Exception {
    remoteBranches.assertRemoteBranches(SampleTestRepository.FIX, Constants.MASTER);
    remoteBranches.selectBranches(SampleTestRepository.FIX, Constants.MASTER);

    WorkingCopyPage workingCopy = remoteBranches.nextToWorkingCopy();
    workingCopy.setDirectory(destRepo.toString());

    workingCopy.assertDirectory(destRepo.toString());
    workingCopy.assertBranch(Constants.MASTER);
    workingCopy.assertRemoteName(Constants.DEFAULT_REMOTE_NAME);
    workingCopy.waitForCreate();/*from ww w. j  a v a  2s  .c  om*/

    // Some random sampling to see we got something. We do not test
    // the integrity of the repository here. Only a few basic properties
    // we'd expect from a clone made this way, that would possibly
    // not hold true given other parameters in the GUI.
    Repository repository = new FileRepository(new File(destRepo, Constants.DOT_GIT));
    // we always have an origin/master
    assertNotNull(repository.resolve("origin/master"));
    // and a local master initialized from origin/master (default!)
    assertEquals(repository.resolve("master"), repository.resolve("origin/master"));
    // A well known tag
    assertNotNull(repository.resolve(Constants.R_TAGS + SampleTestRepository.v1_0_name).name());
    // lots of refs
    int refs = repository.getAllRefs().size();
    assertTrue(refs >= 4);
    // and a known file in the working dir
    assertTrue(new File(destRepo, SampleTestRepository.A_txt_name).exists());
    DirCacheEntry fileEntry = null;
    DirCache dc = repository.lockDirCache();
    fileEntry = dc.getEntry(SampleTestRepository.A_txt_name);
    dc.unlock();
    // check that we have the file in the index
    assertNotNull(fileEntry);
    // No project has been imported
    assertEquals(0, ResourcesPlugin.getWorkspace().getRoot().getProjects().length);
}