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

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

Introduction

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

Prototype

@NonNull
public abstract RefDatabase getRefDatabase();

Source Link

Document

Get the reference database which stores the reference namespace.

Usage

From source file:org.eclipse.egit.ui.internal.history.command.AbstractHistoryCommandHandler.java

License:Open Source License

/**
 * Utility to get a list of Refs from a commit in order to handle ambiguous
 * selections when a Ref is preferred over a commit.
 *
 * @param commit/*  www.  jav  a2  s. c  om*/
 * @param repo
 * @param refPrefix
 *            e.g. "refs/heads/" or ""
 * @return a list of RefNodes
 */
protected List<RefNode> getRefNodes(RevCommit commit, Repository repo, String refPrefix) {
    List<Ref> availableBranches = new ArrayList<Ref>();
    List<RefNode> nodes = new ArrayList<RefNode>();
    try {
        Map<String, Ref> branches = repo.getRefDatabase().getRefs(refPrefix);
        for (Ref branch : branches.values()) {
            if (branch.getLeaf().getObjectId().equals(commit.getId()))
                availableBranches.add(branch);
        }
        RepositoryNode repoNode = new RepositoryNode(null, repo);
        for (Ref ref : availableBranches)
            nodes.add(new RefNode(repoNode, repo, ref));

    } catch (IOException e) {
        // ignore here
    }
    return nodes;
}

From source file:org.eclipse.egit.ui.internal.history.command.CheckoutCommitHandler.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    PlotCommit commit = (PlotCommit) getSelection(getPage()).getFirstElement();
    Repository repo = getRepository(event);
    List<Ref> availableBranches = new ArrayList<Ref>();

    final BranchOperation op;

    try {/*from   w w  w .ja  v  a2  s . co m*/
        Map<String, Ref> localBranches = repo.getRefDatabase().getRefs(Constants.R_HEADS);
        for (Ref branch : localBranches.values()) {
            if (branch.getLeaf().getObjectId().equals(commit.getId())) {
                availableBranches.add(branch);
            }
        }
    } catch (IOException e) {
        // ignore here
    }

    if (availableBranches.isEmpty())
        op = new BranchOperation(repo, commit.getId());
    else if (availableBranches.size() == 1)
        op = new BranchOperation(repo, availableBranches.get(0).getName());
    else {
        List<RefNode> nodes = new ArrayList<RefNode>();
        RepositoryNode repoNode = new RepositoryNode(null, repo);
        for (Ref ref : availableBranches) {
            nodes.add(new RefNode(repoNode, repo, ref));
        }
        BranchMessageDialog dlg = new BranchMessageDialog(HandlerUtil.getActiveShellChecked(event), nodes);
        if (dlg.open() == Window.OK) {
            op = new BranchOperation(repo, dlg.getSelectedNode().getObject().getName());
        } else {
            op = null;
        }
    }

    if (op == null)
        return null;

    // for the sake of UI responsiveness, let's start a job
    Job job = new Job(NLS.bind(UIText.RepositoriesView_CheckingOutMessage, commit.getId().name())) {

        @Override
        protected IStatus run(IProgressMonitor monitor) {

            IWorkspaceRunnable wsr = new IWorkspaceRunnable() {

                public void run(IProgressMonitor myMonitor) throws CoreException {
                    op.execute(myMonitor);
                }
            };

            try {
                ResourcesPlugin.getWorkspace().run(wsr, ResourcesPlugin.getWorkspace().getRoot(),
                        IWorkspace.AVOID_UPDATE, monitor);
            } catch (CoreException e1) {
                return Activator.createErrorStatus(e1.getMessage(), e1);
            }

            return Status.OK_STATUS;
        }

        @Override
        public boolean belongsTo(Object family) {
            if (family.equals(JobFamilies.CHECKOUT))
                return true;
            return super.belongsTo(family);
        }
    };

    job.setUser(true);
    job.schedule();
    return null;
}

From source file:org.eclipse.egit.ui.internal.repository.RepositoriesViewContentProvider.java

License:Open Source License

public Object[] getChildren(Object parentElement) {

    RepositoryTreeNode node = (RepositoryTreeNode) parentElement;
    Repository repo = node.getRepository();

    switch (node.getType()) {

    case BRANCHES: {
        List<RepositoryTreeNode> nodes = new ArrayList<RepositoryTreeNode>();
        nodes.add(new LocalNode(node, repo));
        nodes.add(new RemoteTrackingNode(node, repo));
        return nodes.toArray();
    }//from   w  w w .j a  v a  2 s  .  co  m

    case LOCAL: {
        if (branchHierarchyMode) {
            BranchHierarchyNode hierNode = new BranchHierarchyNode(node, repo, new Path(Constants.R_HEADS));
            List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>();
            try {
                for (IPath path : hierNode.getChildPaths()) {
                    children.add(new BranchHierarchyNode(node, node.getRepository(), path));
                }
                for (Ref ref : hierNode.getChildRefs()) {
                    children.add(new RefNode(node, node.getRepository(), ref));
                }
            } catch (IOException e) {
                return handleException(e, node);
            }
            return children.toArray();
        } else {
            List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>();
            try {
                for (Entry<String, Ref> refEntry : repo.getRefDatabase().getRefs(Constants.R_HEADS)
                        .entrySet()) {
                    if (!refEntry.getValue().isSymbolic())
                        refs.add(new RefNode(node, repo, refEntry.getValue()));
                }
            } catch (IOException e) {
                return handleException(e, node);
            }
            return refs.toArray();
        }
    }

    case REMOTETRACKING: {
        if (branchHierarchyMode) {
            BranchHierarchyNode hierNode = new BranchHierarchyNode(node, repo, new Path(Constants.R_REMOTES));
            List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>();
            try {
                for (IPath path : hierNode.getChildPaths()) {
                    children.add(new BranchHierarchyNode(node, node.getRepository(), path));
                }
                for (Ref ref : hierNode.getChildRefs()) {
                    children.add(new RefNode(node, node.getRepository(), ref));
                }
            } catch (IOException e) {
                return handleException(e, node);
            }
            return children.toArray();
        } else {
            List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>();
            try {
                for (Entry<String, Ref> refEntry : repo.getRefDatabase().getRefs(Constants.R_REMOTES)
                        .entrySet()) {
                    if (!refEntry.getValue().isSymbolic())
                        refs.add(new RefNode(node, repo, refEntry.getValue()));
                }
            } catch (IOException e) {
                return handleException(e, node);
            }

            return refs.toArray();
        }
    }

    case BRANCHHIERARCHY: {
        BranchHierarchyNode hierNode = (BranchHierarchyNode) node;
        List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>();
        try {
            for (IPath path : hierNode.getChildPaths()) {
                children.add(new BranchHierarchyNode(node, node.getRepository(), path));
            }
            for (Ref ref : hierNode.getChildRefs()) {
                children.add(new RefNode(node, node.getRepository(), ref));
            }
        } catch (IOException e) {
            return handleException(e, node);
        }
        return children.toArray();
    }

    case TAGS: {
        List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>();

        try {
            for (Entry<String, Ref> refEntry : repo.getRefDatabase().getRefs(Constants.R_TAGS).entrySet()) {
                refs.add(new TagNode(node, repo, refEntry.getValue()));
            }
        } catch (IOException e) {
            return handleException(e, node);
        }

        return refs.toArray();
    }

    case ADDITIONALREFS: {
        List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>();
        try {
            for (Entry<String, Ref> refEntry : repo.getRefDatabase().getRefs(RefDatabase.ALL).entrySet()) {
                String name = refEntry.getKey();
                if (!(name.startsWith(Constants.R_HEADS) || name.startsWith(Constants.R_TAGS)
                        || name.startsWith(Constants.R_REMOTES)))
                    refs.add(new AdditionalRefNode(node, repo, refEntry.getValue()));
            }
            for (Ref r : repo.getRefDatabase().getAdditionalRefs())
                refs.add(new AdditionalRefNode(node, repo, r));
        } catch (IOException e) {
            return handleException(e, node);
        }
        return refs.toArray();
    }

    case REMOTES: {
        List<RepositoryTreeNode<String>> remotes = new ArrayList<RepositoryTreeNode<String>>();

        Repository rep = node.getRepository();

        Set<String> configNames = rep.getConfig().getSubsections(RepositoriesView.REMOTE);

        for (String configName : configNames) {
            remotes.add(new RemoteNode(node, repo, configName));
        }

        return remotes.toArray();
    }

    case REPO: {

        List<RepositoryTreeNode<? extends Object>> nodeList = new ArrayList<RepositoryTreeNode<? extends Object>>();

        nodeList.add(new BranchesNode(node, repo));
        nodeList.add(new TagsNode(node, repo));
        nodeList.add(new AdditionalRefsNode(node, repo));
        nodeList.add(new WorkingDirNode(node, repo));
        nodeList.add(new RemotesNode(node, repo));

        return nodeList.toArray();
    }

    case WORKINGDIR: {
        List<RepositoryTreeNode<File>> children = new ArrayList<RepositoryTreeNode<File>>();

        if (node.getRepository().isBare())
            return children.toArray();
        File workingDir = repo.getWorkTree();
        if (workingDir == null || !workingDir.exists())
            return children.toArray();

        File[] childFiles = workingDir.listFiles();
        Arrays.sort(childFiles, new Comparator<File>() {
            public int compare(File o1, File o2) {
                if (o1.isDirectory()) {
                    if (o2.isDirectory()) {
                        return o1.compareTo(o2);
                    }
                    return -1;
                } else if (o2.isDirectory()) {
                    return 1;
                }
                return o1.compareTo(o2);
            }
        });
        for (File file : childFiles) {
            if (file.isDirectory()) {
                children.add(new FolderNode(node, repo, file));
            } else {
                children.add(new FileNode(node, repo, file));
            }
        }

        return children.toArray();
    }

    case FOLDER: {
        List<RepositoryTreeNode<File>> children = new ArrayList<RepositoryTreeNode<File>>();

        File parent = ((File) node.getObject());

        File[] childFiles = parent.listFiles();
        Arrays.sort(childFiles, new Comparator<File>() {
            public int compare(File o1, File o2) {
                if (o1.isDirectory()) {
                    if (o2.isDirectory()) {
                        return o1.compareTo(o2);
                    }
                    return -1;
                } else if (o2.isDirectory()) {
                    return 1;
                }
                return o1.compareTo(o2);
            }
        });
        for (File file : childFiles) {
            if (file.isDirectory()) {
                children.add(new FolderNode(node, repo, file));
            } else {
                children.add(new FileNode(node, repo, file));
            }
        }

        return children.toArray();
    }

    case REMOTE: {

        List<RepositoryTreeNode<String>> children = new ArrayList<RepositoryTreeNode<String>>();

        String remoteName = (String) node.getObject();
        RemoteConfig rc;
        try {
            rc = new RemoteConfig(node.getRepository().getConfig(), remoteName);
        } catch (URISyntaxException e) {
            return handleException(e, node);
        }

        if (!rc.getURIs().isEmpty())
            children.add(new FetchNode(node, node.getRepository(), rc.getURIs().get(0).toPrivateString()));

        int uriCount = rc.getPushURIs().size();
        if (uriCount == 0 && !rc.getURIs().isEmpty())
            uriCount++;

        // show push if either a fetch or push URI is specified and
        // at least one push specification
        if (uriCount > 0 && !rc.getPushRefSpecs().isEmpty()) {
            URIish firstUri;
            if (!rc.getPushURIs().isEmpty())
                firstUri = rc.getPushURIs().get(0);
            else
                firstUri = rc.getURIs().get(0);

            if (uriCount == 1)
                children.add(new PushNode(node, node.getRepository(), firstUri.toPrivateString()));
            else
                children.add(new PushNode(node, node.getRepository(), firstUri.toPrivateString() + "...")); //$NON-NLS-1$
        }
        return children.toArray();

    }

    case FILE:
        // fall through
    case REF:
        // fall through
    case PUSH:
        // fall through
    case TAG:
        // fall through
    case FETCH:
        // fall through
    case ERROR:
        // fall through
    case ADDITIONALREF:
        return null;

    }

    return null;

}

From source file:org.eclipse.egit.ui.internal.repository.RepositoriesViewContentProvider.java

License:Open Source License

public boolean hasChildren(Object element) {
    // for some of the nodes we can optimize this call
    RepositoryTreeNode node = (RepositoryTreeNode) element;
    Repository repo = node.getRepository();
    switch (node.getType()) {
    case BRANCHES:
        return true;
    case REPO:/*w ww .j a  va  2s . c  o m*/
        return true;
    case ADDITIONALREFS:
        return true;
    case TAGS:
        try {
            return !repo.getRefDatabase().getRefs(Constants.R_TAGS).isEmpty();
        } catch (IOException e) {
            return true;
        }
    case WORKINGDIR:
        if (node.getRepository().isBare())
            return false;
        File workingDir = repo.getWorkTree();
        if (workingDir == null || !workingDir.exists())
            return false;
        return workingDir.listFiles().length > 0;
    default:
        Object[] children = getChildren(element);
        return children != null && children.length > 0;
    }
}

From source file:org.eclipse.egit.ui.internal.search.CommitSearchQuery.java

License:Open Source License

private void walkRepository(Repository repository, Pattern pattern, IProgressMonitor monitor)
        throws IOException {
    RevWalk walk = new RevWalk(repository);
    try {/*  w  w w. j av a2  s .co m*/
        walk.setRetainBody(true);
        List<RevCommit> commits = new LinkedList<RevCommit>();
        if (this.settings.isAllBranches()) {
            for (Ref ref : repository.getRefDatabase().getRefs(Constants.R_HEADS).values())
                if (!ref.isSymbolic())
                    commits.add(walk.parseCommit(ref.getObjectId()));
            for (Ref ref : repository.getRefDatabase().getRefs(Constants.R_REMOTES).values())
                if (!ref.isSymbolic())
                    commits.add(walk.parseCommit(ref.getObjectId()));
        } else {
            ObjectId headCommit = repository.resolve(Constants.HEAD);
            if (headCommit != null)
                commits.add(walk.parseCommit(headCommit));
        }

        if (!commits.isEmpty()) {
            walk.markStart(commits);
            for (RevCommit commit : walk) {
                if (monitor.isCanceled())
                    throw new OperationCanceledException();
                for (SearchMatcher matcher : this.matchers)
                    if (matcher.matches(pattern, commit)) {
                        result.addResult(new RepositoryCommit(repository, commit));
                        break;
                    }
            }
        }
    } finally {
        walk.dispose();
    }
}

From source file:org.eclipse.egit.ui.RepositoryUtil.java

License:Open Source License

/**
 * Tries to map a commit to a symbolic reference.
 * <p>/*ww w . j  a  v  a 2 s .c  o m*/
 * This value will be cached for the given commit ID unless refresh is
 * specified. The return value will be the full name, e.g.
 * "refs/remotes/someBranch", "refs/tags/v.1.0"
 * <p>
 * Since this mapping is not unique, the following precedence rules are
 * used:
 * <ul>
 * <li>Tags take precedence over branches</li>
 * <li>Local branches take preference over remote branches</li>
 * <li>Newer references take precedence over older ones where time stamps
 * are available</li>
 * <li>If there are still ambiguities, the reference name with the highest
 * lexicographic value will be returned</li>
 * </ul>
 *
 * @param repository
 *            the {@link Repository}
 * @param commitId
 *            a commit
 * @param refresh
 *            if true, the cache will be invalidated
 * @return the symbolic reference, or <code>null</code> if no such reference
 *         can be found
 */
public String mapCommitToRef(Repository repository, String commitId, boolean refresh) {

    synchronized (commitMappingCache) {

        if (!ObjectId.isId(commitId)) {
            return null;
        }

        Map<String, String> cacheEntry = commitMappingCache.get(repository.getDirectory().toString());
        if (!refresh && cacheEntry != null && cacheEntry.containsKey(commitId)) {
            // this may be null in fact
            return cacheEntry.get(commitId);
        }
        if (cacheEntry == null) {
            cacheEntry = new HashMap<String, String>();
            commitMappingCache.put(repository.getDirectory().getPath(), cacheEntry);
        } else {
            cacheEntry.clear();
        }

        Map<String, Date> tagMap = new HashMap<String, Date>();
        try {
            Map<String, Ref> tags = repository.getRefDatabase().getRefs(Constants.R_TAGS);
            for (Ref tagRef : tags.values()) {
                Tag tag = repository.mapTag(tagRef.getName());
                if (tag.getObjId().name().equals(commitId)) {
                    Date timestamp;
                    if (tag.getTagger() != null) {
                        timestamp = tag.getTagger().getWhen();
                    } else {
                        timestamp = null;
                    }
                    tagMap.put(tagRef.getName(), timestamp);
                }
            }
        } catch (IOException e) {
            // ignore here
        }

        String cacheValue = null;

        if (!tagMap.isEmpty()) {
            // we try to obtain the "latest" tag
            Date compareDate = new Date(0);
            for (Map.Entry<String, Date> tagEntry : tagMap.entrySet()) {
                if (tagEntry.getValue() != null && tagEntry.getValue().after(compareDate)) {
                    compareDate = tagEntry.getValue();
                    cacheValue = tagEntry.getKey();
                }
            }
            // if we don't have time stamps, we sort
            if (cacheValue == null) {
                String compareString = ""; //$NON-NLS-1$
                for (String tagName : tagMap.keySet()) {
                    if (tagName.compareTo(compareString) >= 0) {
                        cacheValue = tagName;
                        compareString = tagName;
                    }
                }
            }
        }

        if (cacheValue == null) {
            // we didnt't find a tag, so let's look for local branches
            Set<String> branchNames = new TreeSet<String>();
            // put this into a sorted set
            try {
                Map<String, Ref> remoteBranches = repository.getRefDatabase().getRefs(Constants.R_HEADS);
                for (Ref branch : remoteBranches.values()) {
                    if (branch.getObjectId().name().equals(commitId)) {
                        branchNames.add(branch.getName());
                    }
                }
            } catch (IOException e) {
                // ignore here
            }
            if (!branchNames.isEmpty()) {
                // get the last (sorted) entry
                cacheValue = branchNames.toArray(new String[branchNames.size()])[branchNames.size() - 1];
            }
        }

        if (cacheValue == null) {
            // last try: remote branches
            Set<String> branchNames = new TreeSet<String>();
            // put this into a sorted set
            try {
                Map<String, Ref> remoteBranches = repository.getRefDatabase().getRefs(Constants.R_REMOTES);
                for (Ref branch : remoteBranches.values()) {
                    if (branch.getObjectId().name().equals(commitId)) {
                        branchNames.add(branch.getName());
                    }
                }
                if (!branchNames.isEmpty()) {
                    // get the last (sorted) entry
                    cacheValue = branchNames.toArray(new String[branchNames.size()])[branchNames.size() - 1];
                }
            } catch (IOException e) {
                // ignore here
            }
        }
        cacheEntry.put(commitId, cacheValue);
        return cacheValue;
    }
}

From source file:org.eclipse.orion.server.git.servlets.GitRemoteHandlerV1.java

License:Open Source License

private boolean handleGet(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
    Path p = new Path(path);
    // FIXME: what if a remote or branch is named "file"?
    if (p.segment(0).equals("file")) { //$NON-NLS-1$
        // /git/remote/file/{path}
        File gitDir = GitUtils.getGitDir(p);
        Repository db = new FileRepository(gitDir);
        Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
        JSONObject result = new JSONObject();
        JSONArray children = new JSONArray();
        URI baseLocation = getURI(request);
        for (String configName : configNames) {
            JSONObject o = new JSONObject();
            o.put(ProtocolConstants.KEY_NAME, configName);
            o.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
            o.put(GitConstants.KEY_URL, db.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION,
                    configName, "url" /*RemoteConfig.KEY_URL*/));
            String pushUrl = null;
            if ((pushUrl = db.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, configName,
                    "pushurl" /*RemoteConfig.KEY_PUSHURL*/)) != null)
                o.put(GitConstants.KEY_PUSH_URL, pushUrl);
            o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_2
                    .baseToRemoteLocation(baseLocation, configName, "" /* no branch name */)); //$NON-NLS-1$
            children.put(o);//  ww  w  .  j  av  a 2s . c o m
        }
        result.put(ProtocolConstants.KEY_CHILDREN, children);
        OrionServlet.writeJSONResponse(request, response, result);
        return true;
    } else if (p.segment(1).equals("file")) { //$NON-NLS-1$
        // /git/remote/{remote}/file/{path}
        File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
        Repository db = new FileRepository(gitDir);
        Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
        JSONObject result = new JSONObject();
        URI baseLocation = getURI(request);

        for (String configName : configNames) {
            if (configName.equals(p.segment(0))) {
                result.put(ProtocolConstants.KEY_NAME, configName);
                result.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
                result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3
                        .baseToRemoteLocation(baseLocation, p.segment(0), "" /* no branch name */)); //$NON-NLS-1$

                JSONArray children = new JSONArray();
                List<Ref> refs = new ArrayList<Ref>();
                for (Entry<String, Ref> refEntry : db.getRefDatabase()
                        .getRefs(Constants.R_REMOTES + p.uptoSegment(1)).entrySet()) {
                    if (!refEntry.getValue().isSymbolic()) {
                        Ref ref = refEntry.getValue();
                        String name = ref.getName();
                        name = Repository.shortenRefName(name)
                                .substring(Constants.DEFAULT_REMOTE_NAME.length() + 1);
                        if (db.getBranch().equals(name)) {
                            refs.add(0, ref);
                        } else {
                            refs.add(ref);
                        }
                    }
                }
                for (Ref ref : refs) {
                    JSONObject o = new JSONObject();
                    String name = ref.getName();
                    o.put(ProtocolConstants.KEY_NAME, name.substring(Constants.R_REMOTES.length()));
                    o.put(ProtocolConstants.KEY_FULL_NAME, name);
                    o.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
                    o.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
                    // see bug 342602
                    // o.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
                    o.put(ProtocolConstants.KEY_LOCATION,
                            BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation,
                                    "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
                    o.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation,
                            ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_3));
                    o.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation,
                            Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_3));
                    o.put(GitConstants.KEY_CLONE,
                            BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE));
                    o.put(GitConstants.KEY_BRANCH, BaseToBranchConverter.getBranchLocation(baseLocation,
                            BaseToBranchConverter.REMOTE));
                    o.put(GitConstants.KEY_INDEX,
                            BaseToIndexConverter.getIndexLocation(baseLocation, BaseToIndexConverter.REMOTE));
                    children.put(o);
                }
                result.put(ProtocolConstants.KEY_CHILDREN, children);
                OrionServlet.writeJSONResponse(request, response, result);
                return true;
            }
        }
        String msg = NLS.bind("Couldn't find remote : {0}", p.segment(0));
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
    } else if (p.segment(2).equals("file")) { //$NON-NLS-1$
        // /git/remote/{remote}/{branch}/file/{path}
        File gitDir = GitUtils.getGitDir(p.removeFirstSegments(2));
        Repository db = new FileRepository(gitDir);
        Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
        URI baseLocation = getURI(request);
        for (String configName : configNames) {
            if (configName.equals(p.segment(0))) {
                for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES)
                        .entrySet()) {
                    Ref ref = refEntry.getValue();
                    String name = ref.getName();
                    if (!ref.isSymbolic()
                            && name.equals(Constants.R_REMOTES + p.uptoSegment(2).removeTrailingSeparator())) {
                        JSONObject result = new JSONObject();
                        result.put(ProtocolConstants.KEY_NAME, name.substring(Constants.R_REMOTES.length()));
                        result.put(ProtocolConstants.KEY_FULL_NAME, name);
                        result.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
                        result.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
                        // see bug 342602
                        // result.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
                        result.put(ProtocolConstants.KEY_LOCATION,
                                BaseToRemoteConverter.REMOVE_FIRST_4.baseToRemoteLocation(baseLocation,
                                        "" /*short name is {remote}/{branch}*/, //$NON-NLS-1$
                                        Repository.shortenRefName(name)));
                        result.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(
                                baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_4));
                        result.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation,
                                Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_4));
                        result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation,
                                BaseToCloneConverter.REMOTE_BRANCH));
                        OrionServlet.writeJSONResponse(request, response, result);
                        return true;
                    }
                }
            }
        }
        JSONObject errorData = new JSONObject();
        errorData.put(GitConstants.KEY_CLONE,
                BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE_BRANCH));

        return statusHandler
                .handleRequest(request, response,
                        new ServerStatus(
                                new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE,
                                        "No remote branch found: "
                                                + p.uptoSegment(2).removeTrailingSeparator()),
                                HttpServletResponse.SC_NOT_FOUND, errorData));
    }
    return statusHandler.handleRequest(request, response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                    "Bad request, \"/git/remote/{remote}/{branch}/file/{path}\" expected", null));
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

public void deleteRepository(ServiceInvocationContext context, List<PathFragment> selectedNode) {
    Repository repository = (Repository) GenericTreeStatefulService.getNodeByPathFor(selectedNode, null);
    GenericTreeStatefulService service = GenericTreeStatefulService.getServiceFromPathWithRoot(selectedNode);
    NodeInfo repositoryNodeInfo = service.getVisibleNodes().get(repository);

    ProgressMonitor monitor = ProgressMonitor.create(
            GitPlugin.getInstance().getMessage("git.deleteRepo.monitor.title"),
            context.getCommunicationChannel());

    try {//w ww  .  ja  va 2 s .co m
        monitor.beginTask(GitPlugin.getInstance().getMessage("git.deleteRepo.monitor.message",
                new Object[] { GitPlugin.getInstance().getUtils().getRepositoryName(repository) }), 2);

        repository.getObjectDatabase().close();
        repository.getRefDatabase().close();

        // delete repositories from cache
        File[] children = repository.getDirectory().getParentFile().getParentFile().listFiles();
        for (File child : children) {
            Repository repo = GitPlugin.getInstance().getUtils().getRepository(child);
            RepositoryCache.close(repo);
        }
        monitor.worked(1);

        // delete repository files
        File repoFile = repository.getDirectory().getParentFile().getParentFile();
        if (GitUtils.GIT_REPOSITORIES_NAME.equals(repoFile.getParentFile().getName())) {
            GitPlugin.getInstance().getUtils().delete(repoFile);
        }
        monitor.worked(1);

        dispatchContentUpdate(repositoryNodeInfo.getParent().getNode());
    } catch (Exception e) {
        logger.debug(GitPlugin.getInstance().getMessage("git.deleteRepo.error"), e);
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        GitPlugin.getInstance().getMessage("git.deleteRepo.error"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
    } finally {
        monitor.done();
    }
}

From source file:org.flowerplatform.web.git.history.remote.GitHistoryStatefulService.java

License:Open Source License

private void setupWalk(WebWalk walk, Repository repo, String path) throws IOException {
    walk.addAdditionalRefs(repo.getRefDatabase().getAdditionalRefs());
    walk.addAdditionalRefs(repo.getRefDatabase().getRefs(Constants.R_NOTES).values());

    walk.sort(RevSort.COMMIT_TIME_DESC, true);
    walk.sort(RevSort.BOUNDARY, true);/*from w w w.j  a va2s  .  com*/
    walk.setRetainBody(false);

    setWalkStartPoints(walk, repo, walk.parseCommit(repo.resolve(Constants.HEAD)));

    createFileWalker(walk, repo, path);

}

From source file:org.flowerplatform.web.git.history.remote.GitHistoryStatefulService.java

License:Open Source License

private List<Ref> getBranches(Repository repo) throws IOException {
    List<Ref> ref = new ArrayList<Ref>();

    ref.addAll(repo.getRefDatabase().getRefs(Constants.R_HEADS).values());
    ref.addAll(repo.getRefDatabase().getRefs(Constants.R_REMOTES).values());

    return ref;//from   w w  w. j av a 2s  .  c  om
}