List of usage examples for org.eclipse.jgit.api Git branchList
public ListBranchCommand branchList()
From source file:org.eclipse.orion.server.git.servlets.GitCommitHandlerV1.java
License:Open Source License
private boolean handleGetCommitLog(HttpServletRequest request, HttpServletResponse response, Repository db, String refIdsRange, String path) throws AmbiguousObjectException, IOException, ServletException, JSONException, URISyntaxException, CoreException { int page = request.getParameter("page") != null ? new Integer(request.getParameter("page")).intValue() : 0; //$NON-NLS-1$ //$NON-NLS-2$ int pageSize = request.getParameter("pageSize") != null //$NON-NLS-1$ ? new Integer(request.getParameter("pageSize")).intValue() //$NON-NLS-1$ : PAGE_SIZE;/* w ww .j a v a 2 s . co m*/ ObjectId toObjectId = null; ObjectId fromObjectId = null; Ref toRefId = null; Ref fromRefId = null; Git git = new Git(db); LogCommand log = git.log(); if (refIdsRange != null) { // git log <since>..<until> if (refIdsRange.contains("..")) { //$NON-NLS-1$ String[] commits = refIdsRange.split("\\.\\."); //$NON-NLS-1$ if (commits.length != 2) { String msg = NLS.bind("Failed to generate commit log for ref {0}", refIdsRange); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } fromObjectId = db.resolve(commits[0]); fromRefId = db.getRef(commits[0]); if (fromObjectId == null) { String msg = NLS.bind("Failed to generate commit log for ref {0}", commits[0]); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } toObjectId = db.resolve(commits[1]); toRefId = db.getRef(commits[1]); if (toObjectId == null) { String msg = NLS.bind("No ref or commit found: {0}", commits[1]); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } } else { toObjectId = db.resolve(refIdsRange); toRefId = db.getRef(refIdsRange); if (toObjectId == null) { String msg = NLS.bind("No ref or commit found: {0}", refIdsRange); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } } // set the commit range log.add(toObjectId); if (fromObjectId != null) log.not(fromObjectId); } else { // git log --all // workaround for git log --all - see bug 353310 List<Ref> branches = git.branchList().setListMode(ListMode.ALL).call(); for (Ref branch : branches) { log.add(branch.getObjectId()); } } // set the path filter TreeFilter filter = null; boolean isRoot = true; if (path != null && !"".equals(path)) { //$NON-NLS-1$ filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(path)), TreeFilter.ANY_DIFF); log.addPath(path); isRoot = false; } try { Iterable<RevCommit> commits = log.call(); Map<ObjectId, JSONArray> commitToBranchMap = getCommitToBranchMap(db); JSONObject result = toJSON(db, OrionServlet.getURI(request), commits, commitToBranchMap, page, pageSize, filter, isRoot); result.put(GitConstants.KEY_REPOSITORY_PATH, isRoot ? "" : path); //$NON-NLS-1$ if (refIdsRange == null) result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.COMMIT)); else result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.COMMIT_REFRANGE)); if (toRefId != null) { result.put(GitConstants.KEY_REMOTE, BaseToRemoteConverter.getRemoteBranchLocation(getURI(request), Repository.shortenRefName(toRefId.getName()), db, BaseToRemoteConverter.REMOVE_FIRST_3)); String refTargetName = toRefId.getTarget().getName(); if (refTargetName.startsWith(Constants.R_HEADS)) { // this is a branch result.put(GitConstants.KEY_LOG_TO_REF, BranchToJSONConverter.toJSON(toRefId.getTarget(), db, getURI(request), 3)); } } if (fromRefId != null) { String refTargetName = fromRefId.getTarget().getName(); if (refTargetName.startsWith(Constants.R_HEADS)) { // this is a branch result.put(GitConstants.KEY_LOG_FROM_REF, BranchToJSONConverter.toJSON(fromRefId.getTarget(), db, getURI(request), 3)); } } OrionServlet.writeJSONResponse(request, response, result); return true; } catch (NoHeadException e) { String msg = NLS.bind("No HEAD reference found when generating log for ref {0}", refIdsRange); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); } catch (JGitInternalException e) { String msg = NLS.bind("An internal error occured when generating log for ref {0}", refIdsRange); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); } }
From source file:org.eclipse.orion.server.git.servlets.GitCommitHandlerV1.java
License:Open Source License
private static Map<ObjectId, JSONArray> getCommitToBranchMap(Repository db) throws JSONException { HashMap<ObjectId, JSONArray> commitToBranch = new HashMap<ObjectId, JSONArray>(); Git git = new Git(db); List<Ref> branchRefs = git.branchList().setListMode(ListMode.ALL).call(); for (Ref branchRef : branchRefs) { ObjectId commitId = branchRef.getLeaf().getObjectId(); JSONObject branch = new JSONObject(); branch.put(ProtocolConstants.KEY_FULL_NAME, branchRef.getName()); JSONArray branchesArray = commitToBranch.get(commitId); if (branchesArray != null) { branchesArray.put(branch);/*from w ww. j a v a 2s. c om*/ } else { branchesArray = new JSONArray(); branchesArray.put(branch); commitToBranch.put(commitId, branchesArray); } } return commitToBranch; }
From source file:org.eclipse.orion.server.tests.servlets.git.GitRemoteTest.java
License:Open Source License
@Test public void testGetRemoteBranches() throws Exception { // clone a repo URI workspaceLocation = createWorkspace(getMethodName()); JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null); IPath clonePath = new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute(); JSONObject clone = clone(clonePath); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION); String branchesLocation = clone.getString(GitConstants.KEY_BRANCH); // get project metadata WebRequest request = getGetFilesRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project = new JSONObject(response.getText()); JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT); assertNotNull(gitSection);// w w w .ja va 2s . co m String gitRemoteUri = gitSection.optString(GitConstants.KEY_REMOTE, null); assertNotNull(gitRemoteUri); Repository db1 = getRepositoryForContentLocation(cloneContentLocation); Git git = new Git(db1); int localBefore = git.branchList().call().size(); int remoteBefore = git.branchList().setListMode(ListMode.REMOTE).call().size(); int allBefore = git.branchList().setListMode(ListMode.ALL).call().size(); branch(branchesLocation, "a"); assertEquals(1, git.branchList().call().size() - localBefore); assertEquals(0, git.branchList().setListMode(ListMode.REMOTE).call().size() - remoteBefore); assertEquals(1, git.branchList().setListMode(ListMode.ALL).call().size() - allBefore); // push all // TODO: replace with REST API when bug 339115 is fixed git.push().setPushAll().call(); assertEquals(1, git.branchList().call().size() - localBefore); assertEquals(1, git.branchList().setListMode(ListMode.REMOTE).call().size() - remoteBefore); assertEquals(2, git.branchList().setListMode(ListMode.ALL).call().size() - allBefore); checkoutBranch(cloneLocation, Constants.MASTER); JSONObject remoteBranch = getRemoteBranch(gitRemoteUri, 2, 0, Constants.MASTER); assertNotNull(remoteBranch); checkoutBranch(cloneLocation, "a"); remoteBranch = getRemoteBranch(gitRemoteUri, 2, 0, "a"); assertNotNull(remoteBranch); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitTest.java
License:Open Source License
static void assertBranchExist(Git git, String branch) { List<Ref> list = git.branchList().call(); for (Ref ref : list) { if (ref.getName().equals(Constants.R_HEADS + branch)) { return; // found }/* w ww . j a v a 2s . c o m*/ } fail("branch '" + branch + "' doesn't exist locally"); }
From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java
License:Open Source License
private String getCheckoutBranch(Git git) throws IOException, GitAPIException { ListBranchCommand branchList = git.branchList(); branchList.setListMode(ListMode.REMOTE); List<Ref> branches = branchList.call(); String formatVersion = FORMAT_VERSION.substring(FORMAT_PREFIX.length()); int version = Integer.parseInt(formatVersion); return getCheckoutBranch(branches, version); }
From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java
License:Open Source License
private boolean branchExistsLocally(Git git, String remoteBranch) throws GitAPIException { List<Ref> branches = git.branchList().call(); Collection<String> branchNames = Collections2.transform(branches, new Function<Ref, String>() { @Override//w ww . j a va2 s. com public String apply(Ref input) { return input.getName(); } }); return branchNames.contains(remoteBranch); }
From source file:org.enterprisedomain.classmaker.impl.ContributionImpl.java
License:Apache License
/** * <!-- begin-user-doc --> <!-- end-user-doc --> * /* ww w. ja v a 2 s . com*/ * @generated NOT */ public String initialize(boolean commit) { @SuppressWarnings("unchecked") SCMOperator<Git> operator = (SCMOperator<Git>) getWorkspace().getSCMRegistry().get(getProjectName()); setName(getProjectName()); try { Git git = operator.getRepositorySCM(); // if (git == null) // return ""; String currentBranch = git.getRepository().getBranch(); ListBranchCommand listBranches = git.branchList(); List<Ref> branches = listBranches.call(); Iterator<Ref> it = branches.iterator(); Ref branch = null; long timestamp = -1; String commitId = ""; do { Version version = null; if (it.hasNext()) { branch = it.next(); String[] name = branch.getName().split("/"); //$NON-NLS-1$ try { version = operator.decodeVersion(name[name.length - 1]); ReflogCommand reflog = git.reflog(); reflog.setRef(branch.getName().toString()); Collection<ReflogEntry> refs = reflog.call(); for (ReflogEntry ref : refs) if (ref.getNewId().equals(branch.getObjectId())) { timestamp = operator.decodeTimestamp(ref.getComment()); if (timestamp == -1) timestamp = operator.decodeTimestamp(version.getQualifier()); } } catch (IllegalArgumentException e) { continue; } } if (version != null && !getRevisions().containsKey(version)) { Revision newRevision = newBareRevision(version); newRevision.setTimestamp(timestamp); newRevision.setProject(this); doNewRevision(newRevision); commitId = newRevision.initialize(commit); } } while (it.hasNext()); if (!getRevisions().isEmpty() && getVersion().equals(Version.emptyVersion)) setVersion(ListUtil.getLast(getRevisions()).getKey()); else if (!getVersion().equals(Version.emptyVersion)) checkout(getVersion(), timestamp); if (currentBranch.equals(SCMOperator.MASTER_BRANCH)) checkout(getVersion(), timestamp); getWorkspace().getResourceSet().eAdapters().add(resourceAdapter); addResourceChangeListener(getResourceReloadListener()); return commitId; } catch (Exception e) { ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e)); return null; } finally { try { operator.ungetRepositorySCM(); } catch (Exception e) { ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e)); } } }
From source file:org.exist.git.xquery.BranchList.java
License:Open Source License
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try {/*from ww w .ja va 2 s . co m*/ String localPath = args[0].getStringValue(); if (!(localPath.endsWith("/"))) localPath += File.separator; Git git = Git.open(new Resource(localPath), FS); Sequence result = new ValueSequence(); List<Ref> list = git.branchList().call(); for (Ref ref : list) { result.add(new StringValue(ref.getName())); } return result; } catch (Throwable e) { throw new XPathException(this, Module.EXGIT001, e); } }
From source file:org.fedoraproject.eclipse.packager.git.FedoraPackagerGitCloneOperation.java
License:Open Source License
/** * Create local branches based on existing remotes (uses the JGit API). * /* w w w .jav a 2s.c o m*/ * @param monitor * @throws CoreException */ private void createLocalBranches(Git git, IProgressMonitor monitor) throws CoreException { monitor.beginTask(FedoraPackagerGitText.FedoraPackagerGitCloneWizard_createLocalBranchesJob, IProgressMonitor.UNKNOWN); try { // get a list of remote branches ListBranchCommand branchList = git.branchList(); branchList.setListMode(ListMode.REMOTE); // want all remote branches List<Ref> remoteRefs = branchList.call(); for (Ref remoteRef : remoteRefs) { String name = remoteRef.getName(); int index = (Constants.R_REMOTES + "origin/").length(); //$NON-NLS-1$ // Remove "refs/remotes/origin/" part in branch name name = name.substring(index); // Use "f14"-like branch naming if (name.endsWith("/" + Constants.MASTER)) { //$NON-NLS-1$ index = name.indexOf("/" + Constants.MASTER); //$NON-NLS-1$ name = name.substring(0, index); } // Create all remote branches, except "master" if (!name.equals(Constants.MASTER)) { CreateBranchCommand branchCreateCmd = git.branchCreate(); branchCreateCmd.setName(name); // Need to set starting point this way in order for tracking // to work properly. See: https://bugs.eclipse.org/bugs/show_bug.cgi?id=333899 branchCreateCmd.setStartPoint(remoteRef.getName()); // Add remote tracking config in order to not confuse // fedpkg branchCreateCmd.setUpstreamMode(SetupUpstreamMode.TRACK); branchCreateCmd.call(); } } } catch (JGitInternalException e) { e.printStackTrace(); } catch (RefAlreadyExistsException e) { e.printStackTrace(); } catch (RefNotFoundException e) { e.printStackTrace(); } catch (InvalidRefNameException e) { e.printStackTrace(); } }
From source file:org.fedoraproject.eclipse.packager.git.GitUtils.java
License:Open Source License
/** * Create local branches based on existing remotes (uses the JGit API). * * @param git//from ww w.j a v a 2 s. c o m * @param monitor * @throws CoreException */ public static void createLocalBranches(Git git, IProgressMonitor monitor) throws CoreException { monitor.beginTask(FedoraPackagerGitText.FedoraPackagerGitCloneWizard_createLocalBranchesJob, IProgressMonitor.UNKNOWN); try { // get a list of remote branches ListBranchCommand branchList = git.branchList(); branchList.setListMode(ListMode.REMOTE); // want all remote branches List<Ref> remoteRefs = branchList.call(); for (Ref remoteRef : remoteRefs) { String name = remoteRef.getName(); int index = (Constants.R_REMOTES + "origin/").length(); //$NON-NLS-1$ // Remove "refs/remotes/origin/" part in branch name name = name.substring(index); // Use "f14"-like branch naming if (name.endsWith("/" + Constants.MASTER)) { //$NON-NLS-1$ index = name.indexOf("/" + Constants.MASTER); //$NON-NLS-1$ name = name.substring(0, index); } // Create all remote branches, except "master" if (!name.equals(Constants.MASTER)) { CreateBranchCommand branchCreateCmd = git.branchCreate(); branchCreateCmd.setName(name); // Need to set starting point this way in order for tracking // to work properly. See: // https://bugs.eclipse.org/bugs/show_bug.cgi?id=333899 branchCreateCmd.setStartPoint(remoteRef.getName()); // Add remote tracking config in order to not confuse // fedpkg branchCreateCmd.setUpstreamMode(SetupUpstreamMode.TRACK); if (monitor.isCanceled()) { throw new OperationCanceledException(); } branchCreateCmd.call(); } } } catch (JGitInternalException e) { e.printStackTrace(); } catch (RefAlreadyExistsException e) { e.printStackTrace(); } catch (RefNotFoundException e) { e.printStackTrace(); } catch (InvalidRefNameException e) { e.printStackTrace(); } }