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.core.internal.job.RuleUtil.java

License:Open Source License

private static IProject[] getProjects(Repository repository) {
    final IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    List<IProject> result = new ArrayList<IProject>();
    final File parentFile = repository.getWorkTree();
    for (IProject p : projects) {
        IPath projectLocation = p.getLocation();
        if (projectLocation == null)
            continue;
        if (projectLocation.toFile().getAbsolutePath().startsWith(parentFile.getAbsolutePath()))
            result.add(p);//  ww w.j a  v a 2s  .  co m
    }
    return result.toArray(new IProject[result.size()]);
}

From source file:org.eclipse.egit.core.internal.util.ProjectUtil.java

License:Open Source License

/**
 * The method returns all valid projects contained in the given Git
 * repository. A project is considered as valid if the .project file exists.
 * @see ProjectUtil#refreshValidProjects(IProject[], IProgressMonitor)
 * @param repository//from   w w  w. ja  v a 2s.  c o  m
 * @return valid projects
 * @throws CoreException
 */
public static IProject[] getValidProjects(Repository repository) throws CoreException {
    final IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    List<IProject> result = new ArrayList<IProject>();
    final File parentFile = repository.getWorkTree();
    for (IProject p : projects) {
        String projectFilePath = p.getLocation().append(".project").toOSString(); //$NON-NLS-1$
        File projectFile = new File(projectFilePath);
        if (projectFile.exists()) {
            final File file = p.getLocation().toFile();
            if (file.getAbsolutePath().startsWith(parentFile.getAbsolutePath())) {
                result.add(p);
            }
        }
    }
    return result.toArray(new IProject[result.size()]);
}

From source file:org.eclipse.egit.core.internal.util.ResourceUtil.java

License:Open Source License

/**
 * Get the {@link IFile} corresponding to the arguments if it exists.
 *
 * @param repository//from   w  ww  .  j a  va  2s  . c  o  m
 *            the repository of the file
 * @param repoRelativePath
 *            the repository-relative path of the file to search for
 * @return the IFile corresponding to this path, or null
 */
public static IFile getFileForLocation(Repository repository, String repoRelativePath) {
    IPath path = new Path(repository.getWorkTree().getAbsolutePath()).append(repoRelativePath);
    return getFileForLocation(path);
}

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

License:Open Source License

/**
 * Creates a {@link WorkingTreeIterator} for a tree walk starting on the
 * repository work tree folder.//from w w w .ja  v a2s  .  c om
 *
 * @param repository
 * @return <li>a {@link ContainerTreeIterator} if the work tree folder of
 *         the given repository resides in a project shared with Git <li>an
 *         {@link AdaptableFileTreeIterator} otherwise
 */
public static WorkingTreeIterator createInitialIterator(Repository repository) {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IContainer container = findContainer(root, repository.getWorkTree());
    if (container != null)
        return new ContainerTreeIterator(repository, container);
    return new AdaptableFileTreeIterator(repository, root);
}

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

License:Open Source License

private void addIgnore(IProgressMonitor monitor, IResource resource)
        throws UnsupportedEncodingException, CoreException {
    IContainer container = resource.getParent();
    String entry = "/" + resource.getName() + "\n"; //$NON-NLS-1$  //$NON-NLS-2$
    ByteArrayInputStream entryBytes = asStream(entry);

    if (container instanceof IWorkspaceRoot) {
        Repository repository = RepositoryMapping.getMapping(resource.getProject()).getRepository();
        // .gitignore is not accessible as resource
        IPath gitIgnorePath = resource.getLocation().removeLastSegments(1).append(Constants.GITIGNORE_FILENAME);
        IPath repoPath = new Path(repository.getWorkTree().getAbsolutePath());
        if (!repoPath.isPrefixOf(gitIgnorePath)) {
            String message = NLS.bind(CoreText.IgnoreOperation_parentOutsideRepo,
                    resource.getLocation().toOSString(), repoPath.toOSString());
            IStatus status = Activator.error(message, null);
            throw new CoreException(status);
        }//from  ww w  .  j a va2  s  . c o m
        File gitIgnore = new File(gitIgnorePath.toOSString());
        updateGitIgnore(gitIgnore, entry);
        // no resource change event when updating .gitignore outside
        // workspace => trigger manual decorator refresh
        gitignoreOutsideWSChanged = true;
    } else {
        IFile gitignore = container.getFile(new Path(Constants.GITIGNORE_FILENAME));
        IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1);
        if (gitignore.exists())
            gitignore.appendContents(entryBytes, true, true, subMonitor);
        else
            gitignore.create(entryBytes, true, subMonitor);
    }
}

From source file:org.eclipse.egit.core.synchronize.GitResourceVariantTree.java

License:Open Source License

private String getPath(final IResource resource, Repository repo) {
    return Repository.stripWorkDir(repo.getWorkTree(), resource.getLocation().toFile());
}

From source file:org.eclipse.egit.core.synchronize.GitResourceVariantTreeSubscriber.java

License:Open Source License

/**
 * Returns all members of git repository (including those that are not
 * imported into workspace)//  w  ww . j ava  2 s  .  c om
 *
 * @param res
 */
@Override
public IResource[] members(IResource res) throws TeamException {
    if (res.getType() == IResource.FILE || !shouldBeIncluded(res))
        return new IResource[0];

    GitSynchronizeData gsd = gsds.getData(res.getProject());
    Repository repo = gsd.getRepository();
    GitSyncObjectCache repoCache = cache.get(repo);

    Set<IResource> gitMembers = new HashSet<IResource>();
    Map<String, IResource> allMembers = new HashMap<String, IResource>();

    Set<GitSyncObjectCache> gitCachedMembers = new HashSet<GitSyncObjectCache>();
    String path = stripWorkDir(repo.getWorkTree(), res.getLocation().toFile());
    GitSyncObjectCache cachedMembers = repoCache.get(path);
    if (cachedMembers != null) {
        Collection<GitSyncObjectCache> members = cachedMembers.members();
        if (members != null)
            gitCachedMembers.addAll(members);
    }
    try {
        for (IResource member : ((IContainer) res).members())
            allMembers.put(member.getName(), member);

        for (GitSyncObjectCache gitMember : gitCachedMembers) {
            IResource member = allMembers.get(gitMember.getName());
            if (member != null)
                gitMembers.add(member);
        }
    } catch (CoreException e) {
        throw TeamException.asTeamException(e);
    }

    return gitMembers.toArray(new IResource[gitMembers.size()]);
}

From source file:org.eclipse.egit.core.synchronize.GitSyncInfo.java

License:Open Source License

@Override
protected int calculateKind() throws TeamException {
    String localPath;//  w w  w.j  a  v a  2s. c  o  m
    Repository repo = gsd.getRepository();
    if (getLocal().exists()) {
        File local = getLocal().getLocation().toFile();
        localPath = Repository.stripWorkDir(repo.getWorkTree(), local);
    } else if (getRemote() != null)
        localPath = ((GitResourceVariant) getRemote()).getFullPath().toString();
    else if (getBase() != null)
        localPath = ((GitResourceVariant) getBase()).getFullPath().toString();
    else
        // we cannot determinate local path therefore we cannot set proper
        // value for PathFilter, so we use standard calulateKind()
        // implementation
        return super.calculateKind();

    if (localPath.length() == 0)
        return IN_SYNC;

    TreeWalk tw = new TreeWalk(repo);
    tw.setFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilter.create(localPath)));
    tw.setRecursive(true);

    try {
        int srcNth = tw.addTree(gsd.getSrcRevCommit().getTree());
        int dstNth = tw.addTree(gsd.getDstRevCommit().getTree());

        if (tw.next()) {
            return calculateKindImpl(repo, tw, srcNth, dstNth);
        }
    } catch (IOException e) {
        Activator.logError(e.getMessage(), e);
    }

    return IN_SYNC;
}

From source file:org.eclipse.egit.core.test.TestRepository.java

License:Open Source License

/**
 * Creates a test repository from an existing Repository
 *
 * @param repository// w  ww.j a v  a 2 s  .  c o m
 * @throws IOException
 */
public TestRepository(Repository repository) throws IOException {
    this.repository = repository;
    try {
        workdirPrefix = repository.getWorkTree().getCanonicalPath();
    } catch (IOException err) {
        workdirPrefix = repository.getWorkTree().getAbsolutePath();
    }
    workdirPrefix = workdirPrefix.replace('\\', '/');
    if (!workdirPrefix.endsWith("/")) //$NON-NLS-1$
        workdirPrefix += "/"; //$NON-NLS-1$
}

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

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    final GitFlowRepository gfRepo = GitFlowHandlerUtil.getRepository(event);
    if (gfRepo == null) {
        return error(UIText.Handlers_noGitflowRepositoryFound);
    }/*from w  w  w.ja  v  a2s  . c o  m*/

    Repository repository = gfRepo.getRepository();

    final List<Ref> refs = gfRepo.getFeatureBranches();

    FeatureBranchSelectionDialog dialog = new FeatureBranchSelectionDialog(HandlerUtil.getActiveShell(event),
            refs, UIText.FeatureCheckoutHandler_selectFeature, UIText.FeatureCheckoutHandler_localFeatures,
            Constants.R_HEADS + gfRepo.getConfig().getFeaturePrefix(), gfRepo);

    if (dialog.open() != Window.OK) {
        return null;
    }
    final Ref ref = dialog.getSelectedNode();

    try {
        String featureName = gfRepo.getFeatureBranchName(ref);
        // TODO: consider using BranchOperationUI because checkout can take
        // a long time on large repositories
        FeatureCheckoutOperation checkoutOperation = new FeatureCheckoutOperation(gfRepo, featureName);
        JobUtil.scheduleUserWorkspaceJob(checkoutOperation, UIText.FeatureCheckoutHandler_checkingOutFeature,
                JobFamilies.GITFLOW_FAMILY);
        IJobManager jobMan = Job.getJobManager();
        try {
            jobMan.join(GITFLOW_FAMILY, null);
        } catch (OperationCanceledException | InterruptedException e) {
            return error(e.getMessage(), e);
        }

        CheckoutResult result = checkoutOperation.getResult();
        if (!CheckoutResult.Status.OK.equals(result.getStatus())) {
            Shell shell = HandlerUtil.getActiveShell(event);
            if (!handleUncommittedFiles(gfRepo.getRepository(), shell, repository.getWorkTree().getName())) {
                return Status.CANCEL_STATUS;
            } else {
                JobUtil.scheduleUserWorkspaceJob(checkoutOperation,
                        UIText.FeatureCheckoutHandler_checkingOutFeature, JobFamilies.GITFLOW_FAMILY);
            }
        }
    } catch (GitAPIException e) {
        throw new RuntimeException(e);
    }

    return null;
}