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

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

Introduction

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

Prototype

@NonNull
public File getWorkTree() throws NoWorkTreeException 

Source Link

Document

Get the root directory of the working tree, where files are checked out for viewing and editing.

Usage

From source file:org.eclipse.egit.ui.common.LocalRepositoryTestCase.java

License:Open Source License

protected static File createProjectAndCommitToRepository() throws Exception {

    File gitDir = new File(new File(testDirectory, REPO1), Constants.DOT_GIT);
    gitDir.mkdir();//from w  ww.  j ava  2  s .c  om
    Repository myRepository = new FileRepository(gitDir);
    myRepository.create();

    // we need to commit into master first
    IProject firstProject = ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ1);

    if (firstProject.exists())
        firstProject.delete(true, null);
    IProjectDescription desc = ResourcesPlugin.getWorkspace().newProjectDescription(PROJ1);
    desc.setLocation(new Path(new File(myRepository.getWorkTree(), PROJ1).getPath()));
    firstProject.create(desc, null);
    firstProject.open(null);

    IFolder folder = firstProject.getFolder(FOLDER);
    folder.create(false, true, null);
    IFile textFile = folder.getFile(FILE1);
    textFile.create(new ByteArrayInputStream("Hello, world".getBytes(firstProject.getDefaultCharset())), false,
            null);
    IFile textFile2 = folder.getFile(FILE2);
    textFile2.create(new ByteArrayInputStream("Some more content".getBytes(firstProject.getDefaultCharset())),
            false, null);

    new ConnectProviderOperation(firstProject, gitDir).execute(null);

    IProject secondPoject = ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ2);

    if (secondPoject.exists())
        secondPoject.delete(true, null);

    desc = ResourcesPlugin.getWorkspace().newProjectDescription(PROJ2);
    desc.setLocation(new Path(new File(myRepository.getWorkTree(), PROJ2).getPath()));
    secondPoject.create(desc, null);
    secondPoject.open(null);

    IFolder secondfolder = secondPoject.getFolder(FOLDER);
    secondfolder.create(false, true, null);
    IFile secondtextFile = secondfolder.getFile(FILE1);
    secondtextFile.create(new ByteArrayInputStream("Hello, world".getBytes(firstProject.getDefaultCharset())),
            false, null);
    IFile secondtextFile2 = secondfolder.getFile(FILE2);
    secondtextFile2.create(
            new ByteArrayInputStream("Some more content".getBytes(firstProject.getDefaultCharset())), false,
            null);
    // TODO we should be able to hide the .project
    // IFile gitignore = secondPoject.getFile(".gitignore");
    // gitignore.create(new ByteArrayInputStream("/.project\n"
    // .getBytes(firstProject.getDefaultCharset())), false, null);

    new ConnectProviderOperation(secondPoject, gitDir).execute(null);

    IFile[] commitables = new IFile[] { firstProject.getFile(".project"), textFile, textFile2, secondtextFile,
            secondtextFile2 };
    ArrayList<IFile> untracked = new ArrayList<IFile>();
    untracked.addAll(Arrays.asList(commitables));
    // commit to stable
    CommitOperation op = new CommitOperation(commitables, new ArrayList<IFile>(), untracked,
            TestUtil.TESTAUTHOR, TestUtil.TESTCOMMITTER, "Initial commit");
    op.execute(null);

    // now create a stable branch (from master)
    createStableBranch(myRepository);
    // and check in some stuff into master again
    touchAndSubmit(null);
    return gitDir;
}

From source file:org.eclipse.egit.ui.common.LocalRepositoryTestCase.java

License:Open Source License

protected void shareProjects(File repositoryDir) throws Exception {
    Repository myRepository = lookupRepository(repositoryDir);
    FilenameFilter projectFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.equals(".project");
        }//  w  w  w . j av a  2s  . c o  m
    };
    for (File file : myRepository.getWorkTree().listFiles()) {
        if (file.isDirectory()) {
            if (file.list(projectFilter).length > 0) {
                IProjectDescription desc = ResourcesPlugin.getWorkspace().newProjectDescription(file.getName());
                desc.setLocation(new Path(file.getPath()));
                IProject prj = ResourcesPlugin.getWorkspace().getRoot().getProject(file.getName());
                prj.create(desc, null);
                prj.open(null);

                new ConnectProviderOperation(prj, myRepository.getDirectory()).execute(null);
            }
        }
    }
}

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

License:Open Source License

private static Collection<IContributionItem> createSpecificOursTheirsItems(Repository repository, String path) {

    Collection<IPath> paths = Collections
            .<IPath>singleton(new Path(new File(repository.getWorkTree(), path).getAbsolutePath()));
    List<IContributionItem> result = new ArrayList<>();

    try {//  w w w. ja  v  a2 s. c  o m
        ConflictCommits conflictCommits = RevUtils.getConflictCommits(repository, path);
        RevCommit ourCommit = conflictCommits.getOurCommit();
        RevCommit theirCommit = conflictCommits.getTheirCommit();

        if (ourCommit != null)
            result.add(createOursItem(
                    formatCommit(UIText.ReplaceWithOursTheirsMenu_OursWithCommitLabel, ourCommit), paths));
        else
            result.add(createOursItem(UIText.ReplaceWithOursTheirsMenu_OursWithoutCommitLabel, paths));

        if (theirCommit != null)
            result.add(createTheirsItem(
                    formatCommit(UIText.ReplaceWithOursTheirsMenu_TheirsWithCommitLabel, theirCommit), paths));
        else
            result.add(createTheirsItem(UIText.ReplaceWithOursTheirsMenu_TheirsWithoutCommitLabel, paths));

        return result;
    } catch (IOException e) {
        Activator.logError(UIText.ReplaceWithOursTheirsMenu_CalculatingOursTheirsCommitsError, e);
        return createUnspecificOursTheirsItems(paths);
    }
}

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

License:Open Source License

private static Collection<IContributionItem> createStashItems(Repository repository) {
    if (repository == null)
        return Collections.singleton(createNoStashedChangesItem());

    try {//from   w  ww .j  ava 2  s  . c om
        Collection<RevCommit> stashCommits = Git.wrap(repository).stashList().call();

        if (stashCommits.isEmpty())
            return Collections.singleton(createNoStashedChangesItem());

        List<IContributionItem> items = new ArrayList<>(stashCommits.size());

        int index = 0;
        for (final RevCommit stashCommit : stashCommits)
            items.add(createStashItem(repository, stashCommit, index++));

        return items;
    } catch (GitAPIException e) {
        String repoName = repository.getWorkTree().getName();
        String message = MessageFormat.format(UIText.StashesMenu_StashListError, repoName);
        Activator.logError(message, e);
        return Collections.singleton(createNoStashedChangesItem());
    }
}

From source file:org.eclipse.egit.ui.internal.branch.BranchResultDialog.java

License:Open Source License

/**
 * @param result/*  w w  w.j a v  a 2  s.  co  m*/
 *            the result to show
 * @param repository
 * @param target
 *            the target (branch name or commit id)
 */
public static void show(final CheckoutResult result, final Repository repository, final String target) {
    BranchResultDialog.target = target;
    if (result.getStatus() == CheckoutResult.Status.CONFLICTS)
        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
            public void run() {
                Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                new BranchResultDialog(shell, repository, result, target).open();
            }
        });
    else if (result.getStatus() == CheckoutResult.Status.NONDELETED) {
        // double-check if the files are still there
        boolean show = false;
        List<String> pathList = result.getUndeletedList();
        for (String path : pathList)
            if (new File(repository.getWorkTree(), path).exists()) {
                show = true;
                break;
            }
        if (!show)
            return;
        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
            public void run() {
                Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                new NonDeletedFilesDialog(shell, repository, result.getUndeletedList()).open();
            }
        });
    } else if (result.getStatus() == CheckoutResult.Status.OK) {
        try {
            if (ObjectId.isId(repository.getFullBranch()))
                showDetachedHeadWarning();
        } catch (IOException e) {
            Activator.logError(e.getMessage(), e);
        }
    }
}

From source file:org.eclipse.egit.ui.internal.clone.AbstractGitCloneWizard.java

License:Open Source License

private void importProjects(final Repository repository, final IWorkingSet[] sets) {
    String repoName = Activator.getDefault().getRepositoryUtil().getRepositoryName(repository);
    Job importJob = new Job(MessageFormat.format(UIText.GitCloneWizard_jobImportProjects, repoName)) {

        protected IStatus run(IProgressMonitor monitor) {
            List<File> files = new ArrayList<File>();
            ProjectUtil.findProjectFiles(files, repository.getWorkTree(), true, monitor);
            if (files.isEmpty())
                return Status.OK_STATUS;

            Set<ProjectRecord> records = new LinkedHashSet<ProjectRecord>();
            for (File file : files)
                records.add(new ProjectRecord(file));
            try {
                ProjectUtils.createProjects(records, repository, sets, monitor);
            } catch (InvocationTargetException e) {
                Activator.logError(e.getLocalizedMessage(), e);
            } catch (InterruptedException e) {
                Activator.logError(e.getLocalizedMessage(), e);
            }/*from w w  w  .  ja  v  a 2s  .c  o m*/
            return Status.OK_STATUS;
        }
    };
    importJob.schedule();
}

From source file:org.eclipse.egit.ui.internal.clone.SmartImportGitWizard.java

License:Open Source License

@Override
public void pageChanged(PageChangedEvent event) {
    SmartImportRootWizardPage selectRootPage = (SmartImportRootWizardPage) this.easymportWizard.getPages()[0];
    if (event.getSelectedPage() == selectRootPage) {
        Repository existingRepo = selectRepoPage.getRepository();
        if (existingRepo != null) {
            selectRootPage.setInitialImportRoot(existingRepo.getWorkTree());
        } else if (needToCloneRepository()) {
            // asynchronous clone, set root later.
            doClone(selectRootPage);//ww w.  j av  a  2  s.  c  o  m
        }
    }
}

From source file:org.eclipse.egit.ui.internal.commit.DiffViewer.java

License:Open Source License

/**
 * Shows a two-way diff between the old and new versions of a
 * {@link FileDiff} in a compare editor.
 *
 * @param repository//from   www  .  j  a v a 2s  .  c o  m
 *            the {@link FileDiff} belongs to
 * @param d
 *            the {@link FileDiff} to show
 */
public static void showTwoWayFileDiff(Repository repository, FileDiff d) {
    String np = d.getNewPath();
    String op = d.getOldPath();
    RevCommit c = d.getCommit();
    ObjectId[] blobs = d.getBlobs();

    // extract commits
    final RevCommit oldCommit;
    final ObjectId oldObjectId;
    if (!d.getChange().equals(ChangeType.ADD)) {
        oldCommit = c.getParent(0);
        oldObjectId = blobs[0];
    } else {
        // Initial import
        oldCommit = null;
        oldObjectId = null;
    }

    final RevCommit newCommit;
    final ObjectId newObjectId;
    if (d.getChange().equals(ChangeType.DELETE)) {
        newCommit = null;
        newObjectId = null;
    } else {
        newCommit = c;
        newObjectId = blobs[blobs.length - 1];
    }
    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    IWorkbenchPage page = window.getActivePage();
    if (oldCommit != null && newCommit != null && repository != null) {
        IFile file = np != null ? ResourceUtil.getFileForLocation(repository, np, false) : null;
        try {
            if (file != null) {
                CompareUtils.compare(file, repository, np, op, newCommit.getName(), oldCommit.getName(), false,
                        page);
            } else {
                IPath location = new Path(repository.getWorkTree().getAbsolutePath()).append(np);
                CompareUtils.compare(location, repository, newCommit.getName(), oldCommit.getName(), false,
                        page);
            }
        } catch (IOException e) {
            Activator.handleError(UIText.GitHistoryPage_openFailed, e, true);
        }
        return;
    }

    // still happens on initial commits
    final ITypedElement oldSide = createTypedElement(repository, op, oldCommit, oldObjectId);
    final ITypedElement newSide = createTypedElement(repository, np, newCommit, newObjectId);
    CompareUtils.openInCompare(page, new GitCompareFileRevisionEditorInput(newSide, oldSide, null));
}

From source file:org.eclipse.egit.ui.internal.decorators.DecoratableResourceMapping.java

License:Open Source License

private String makeRepoRelative(Repository repository, IResource res) {
    return stripWorkDir(repository.getWorkTree(), res.getLocation().toFile());
}

From source file:org.eclipse.egit.ui.internal.dialogs.CompareTreeView.java

License:Open Source License

private IPath getRepositoryPath() {
    Repository repo = getRepository();
    if (repo != null)
        return new Path(repo.getWorkTree().getAbsolutePath());

    return null;/* w w  w  .ja v  a  2s  . c  o  m*/
}