List of usage examples for org.eclipse.jgit.lib Repository shortenRefName
@NonNull public static String shortenRefName(String refName)
From source file:org.fedoraproject.eclipse.packager.git.FpGitProjectBits.java
License:Open Source License
/** * Determine if Git tag exists.//from ww w. ja v a 2s . c o m * * See {@link IFpProjectBits#isVcsTagged(IProjectRoot, String)} */ @Override public boolean isVcsTagged(IProjectRoot fedoraProjectRoot, String tag) { if (!isInitialized()) { return false; // If we are not initialized we can't go any further! } // Look at tags and see if we can find the tag in question. Map<String, Ref> remotes = this.git.getRepository().getTags(); if (remotes != null) { Set<String> keyset = remotes.keySet(); String currentTag; for (String key : keyset) { // use shortenRefName() to get rid of refs/*/ prefix currentTag = Repository.shortenRefName(remotes.get(key).getName()); if (tag.equals(currentTag)) { return true; // tag found } } } return false; }
From source file:org.fedoraproject.eclipse.packager.tests.FedoraPackagerGitCloneOperationTest.java
License:Open Source License
/** * Fedora Git clones create local branches. Test for that. * //from w w w.j a v a 2s . c om * @throws Exception */ @Test public void canCloneFromFedoraGit() { final FedoraPackagerGitCloneOperation cloneOp = new FedoraPackagerGitCloneOperation(); final String fedoraPackager = "eclipse-fedorapackager"; Job cloneJob = new Job("Clone Me!") { @Override protected IStatus run(IProgressMonitor monitor) { try { git = cloneOp.setPackageName(fedoraPackager) .setCloneURI(GitUtils.getFullGitURL(GitUtils.getAnonymousGitBaseUrl(), fedoraPackager)) .run(monitor); } catch (IllegalStateException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (CoreException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } return null; } }; cloneJob.schedule(); try { cloneJob.join(); // wait for it to finish } catch (InterruptedException e) { e.printStackTrace(); } assertNotNull(git); ListBranchCommand ls = git.branchList(); // should have created a local branch called "f14" boolean f14Found = false; for (Ref ref : ls.call()) { if (Repository.shortenRefName(ref.getName()).equals("f14")) { f14Found = true; break; } } assertTrue(f14Found); }
From source file:org.fedoraproject.eclipse.packager.tests.utils.git.GitTestProject.java
License:Open Source License
/** * Checkouts branch//from w w w. j a v a 2s . c o m * * @param refName * full name of branch * @throws CoreException * @throws InvalidRefNameException * @throws RefNotFoundException * @throws RefAlreadyExistsException * @throws JGitInternalException */ public void checkoutBranch(String branchName) throws JGitInternalException, RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, CoreException { boolean branchExists = false; ListBranchCommand lsBranchCmd = this.git.branchList(); for (Ref branch : lsBranchCmd.call()) { if (Repository.shortenRefName(branch.getName()).equals(branchName)) { branchExists = true; break; // short circuit } } if (!branchExists) { System.err.println("Branch: '" + branchName + "' does not exist!"); return; } CheckoutCommand checkoutCmd = this.git.checkout(); checkoutCmd.setName(Constants.R_HEADS + branchName); checkoutCmd.call(); // refresh after checkout project.refreshLocal(IResource.DEPTH_INFINITE, null); }
From source file:org.flowerplatform.web.git.explorer.RefNodeDataProvider.java
License:Open Source License
@Override public boolean populateTreeNode(Object source, TreeNode destination, GenericTreeContext context) { RefNode refNode = (RefNode) source;// www . j av a 2s . com String nodeType = destination.getPathFragment().getType(); String refShortName = Repository.shortenRefName(refNode.getRef().getName()); if (GitNodeType.NODE_TYPE_LOCAL_BRANCH.equals(destination.getPathFragment().getType())) { // add additional information like working directory name File mainRepoFile = refNode.getRepository().getDirectory().getParentFile(); File wdirFile = new File(mainRepoFile.getParentFile(), GitUtils.WORKING_DIRECTORY_PREFIX + refShortName); destination.setLabel(String.format("%s [%s]", refShortName, wdirFile.getName())); } else { destination.setLabel(refShortName); } String icon; if (GitNodeType.NODE_TYPE_TAG.equals(nodeType)) { icon = "images/full/obj16/annotated-tag.gif"; } else { icon = "images/full/obj16/branch_obj.gif"; } destination.setIcon(GitPlugin.getInstance().getResourceUrl(icon)); return true; }
From source file:org.flowerplatform.web.git.GitService.java
License:Open Source License
@RemoteInvocation public List<Object> getBranches(ServiceInvocationContext context, String repositoryUrl) { tlCommand.set((InvokeServiceMethodServerCommand) context.getCommand()); Repository db = null;//from w w w. j a v a 2 s . c o m try { URIish uri = new URIish(repositoryUrl.trim()); db = new FileRepository(new File("/tmp")); Git git = new Git(db); LsRemoteCommand rc = git.lsRemote(); rc.setRemote(uri.toString()).setTimeout(30); Collection<Ref> remoteRefs = rc.call(); List<GitRef> branches = new ArrayList<GitRef>(); Ref idHEAD = null; for (Ref r : remoteRefs) { if (r.getName().equals(Constants.HEAD)) { idHEAD = r; } } Ref head = null; boolean headIsMaster = false; String masterBranchRef = Constants.R_HEADS + Constants.MASTER; for (Ref r : remoteRefs) { String n = r.getName(); if (!n.startsWith(Constants.R_HEADS)) continue; branches.add(new GitRef(n, Repository.shortenRefName(n))); if (idHEAD == null || headIsMaster) continue; if (r.getObjectId().equals(idHEAD.getObjectId())) { headIsMaster = masterBranchRef.equals(r.getName()); if (head == null || headIsMaster) head = r; } } Collections.sort(branches, new Comparator<GitRef>() { public int compare(GitRef r1, GitRef r2) { return r1.getShortName().compareTo(r2.getShortName()); } }); if (idHEAD != null && head == null) { head = idHEAD; branches.add(0, new GitRef(idHEAD.getName(), Repository.shortenRefName(idHEAD.getName()))); } GitRef headRef = head != null ? new GitRef(head.getName(), Repository.shortenRefName(head.getName())) : null; return Arrays.asList(new Object[] { branches, headRef }); } catch (JGitInternalException | GitAPIException e) { context.getCommunicationChannel() .appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance().getMessage("git.cloneWizard.branch.cannotListBranches") + "\n" + e.getCause().getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR)); } catch (IOException e) { context.getCommunicationChannel().appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance().getMessage("git.cloneWizard.branch.cannotCreateTempRepo"), DisplaySimpleMessageClientCommand.ICON_ERROR)); } catch (URISyntaxException e) { context.getCommunicationChannel().appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), e.getReason(), DisplaySimpleMessageClientCommand.ICON_ERROR)); } catch (Exception e) { if (GitPlugin.getInstance().getUtils().isAuthentificationException(e)) { openLoginWindow(); return null; } logger.debug(CommonPlugin.getInstance().getMessage("error"), e); } finally { if (db != null) { db.close(); } } return null; }
From source file:org.flowerplatform.web.git.GitService.java
License:Open Source License
@RemoteInvocation public boolean pull(ServiceInvocationContext context, List<PathFragment> path) { tlCommand.set((InvokeServiceMethodServerCommand) context.getCommand()); try {//from w w w . j av a 2 s . c om RefNode refNode = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null); GenericTreeStatefulService service = GenericTreeStatefulService.getServiceFromPathWithRoot(path); NodeInfo refNodeInfo = service.getVisibleNodes().get(refNode); Repository repository = getRepository(refNodeInfo); if (repository == null) { context.getCommunicationChannel() .appendOrSendCommand(new DisplaySimpleMessageClientCommand( CommonPlugin.getInstance().getMessage("error"), "Cannot find repository for node " + refNode, DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } File mainRepoFile = repository.getDirectory().getParentFile(); File wdirFile = new File(mainRepoFile.getParentFile(), GitUtils.WORKING_DIRECTORY_PREFIX + Repository.shortenRefName(refNode.getRef().getName())); if (!wdirFile.exists()) { return false; } new PullOperation(refNode.getRef(), GitPlugin.getInstance().getUtils().getRepository(wdirFile), context.getCommunicationChannel()).execute(); return true; } catch (Exception e) { context.getCommunicationChannel().appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } }
From source file:org.flowerplatform.web.git.GitService.java
License:Open Source License
@RemoteInvocation public ConfigBranchPageDto getConfigBranchData(ServiceInvocationContext context, List<PathFragment> path) { try {/*ww w .j a v a 2 s . c o m*/ RefNode node = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null); Repository repository = node.getRepository(); StoredConfig config = repository.getConfig(); ConfigBranchPageDto dto = new ConfigBranchPageDto(); Ref branch = (Ref) node.getRef(); dto.setRef(new GitRef(branch.getName(), Repository.shortenRefName(branch.getName()))); List<RemoteConfig> remotes = getAllRemotes(context, path); String branchName = branch.getName().substring(Constants.R_HEADS.length()); String branchConfig = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_MERGE); String remoteConfig = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE); if (remoteConfig == null) { remoteConfig = ""; } if (remotes != null) { dto.setRemotes(remotes); for (RemoteConfig remote : remotes) { if (remote.getName().equals(remoteConfig)) { List<Object> branches = getBranches(context, remote.getUri()); if (branches != null) { @SuppressWarnings("unchecked") List<GitRef> refs = (List<GitRef>) branches.get(0); for (GitRef ref : refs) { if (ref.getName().equals(branchConfig)) { dto.setSelectedRef(ref); break; } } dto.setRefs(refs); } dto.setSelectedRemote(remote); break; } } } boolean rebaseFlag = config.getBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REBASE, false); dto.setRebase(rebaseFlag); return dto; } catch (Exception e) { logger.debug(CommonPlugin.getInstance().getMessage("error"), path, e); context.getCommunicationChannel().appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR)); return null; } }
From source file:org.flowerplatform.web.git.history.internal.WebCommitPlotRenderer.java
License:Open Source License
@Override protected int drawLabel(int x, int y, Ref ref) { specialMessage += "[" + Repository.shortenRefName(ref.getName()) + "]"; return 0;//from ww w . j a va 2 s .c o m }
From source file:org.flowerplatform.web.git.operation.CheckoutOperation.java
License:Open Source License
public boolean execute() { ProgressMonitor monitor = ProgressMonitor .create(GitPlugin.getInstance().getMessage("git.checkout.monitor.title"), channel); try {/*from w w w . j av a 2 s .c om*/ monitor.beginTask( GitPlugin.getInstance().getMessage("git.checkout.monitor.message", new Object[] { name }), 4); monitor.setTaskName("Getting remote branch..."); Git git = new Git(repository); Ref ref; if (node instanceof Ref) { ref = (Ref) node; } else { // get remote branch String dst = Constants.R_REMOTES + remote.getName(); String remoteRefName = dst + "/" + upstreamBranch.getShortName(); ref = repository.getRef(remoteRefName); if (ref == null) { // doesn't exist, fetch it RefSpec refSpec = new RefSpec(); refSpec = refSpec.setForceUpdate(true); refSpec = refSpec.setSourceDestination(upstreamBranch.getName(), remoteRefName); git.fetch().setRemote(new URIish(remote.getUri()).toPrivateString()).setRefSpecs(refSpec) .call(); ref = repository.getRef(remoteRefName); } } monitor.worked(1); monitor.setTaskName("Creating local branch..."); // create local branch git.branchCreate().setName(name).setStartPoint(ref.getName()) .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM).call(); if (!(node instanceof Ref)) { // save upstream configuration StoredConfig config = repository.getConfig(); config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_MERGE, upstreamBranch.getName()); config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REMOTE, remote.getName()); if (rebase) { config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REBASE, true); } else { config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REBASE); } config.save(); } monitor.worked(1); monitor.setTaskName("Creating working directory"); // create working directory for local branch File mainRepoFile = repository.getDirectory().getParentFile(); File wdirFile = new File(mainRepoFile.getParentFile(), GitUtils.WORKING_DIRECTORY_PREFIX + name); if (wdirFile.exists()) { GitPlugin.getInstance().getUtils().delete(wdirFile); } GitPlugin.getInstance().getUtils().run_git_workdir_cmd(mainRepoFile.getAbsolutePath(), wdirFile.getAbsolutePath()); monitor.worked(1); monitor.setTaskName("Checkout branch"); // checkout local branch Repository wdirRepo = GitPlugin.getInstance().getUtils().getRepository(wdirFile); git = new Git(wdirRepo); CheckoutCommand cc = git.checkout().setName(name).setForce(true); cc.call(); // show checkout result if (cc.getResult().getStatus() == CheckoutResult.Status.CONFLICTS) channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand( GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.title"), GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.message"), cc.getResult().getConflictList().toString(), DisplaySimpleMessageClientCommand.ICON_INFORMATION)); else if (cc.getResult().getStatus() == CheckoutResult.Status.NONDELETED) { // double-check if the files are still there boolean show = false; List<String> pathList = cc.getResult().getUndeletedList(); for (String path1 : pathList) { if (new File(wdirRepo.getWorkTree(), path1).exists()) { show = true; break; } } if (show) { channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand( GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.title"), GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.message", Repository.shortenRefName(name)), cc.getResult().getUndeletedList().toString(), DisplaySimpleMessageClientCommand.ICON_ERROR)); } } else if (cc.getResult().getStatus() == CheckoutResult.Status.OK) { if (ObjectId.isId(wdirRepo.getFullBranch())) channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand( GitPlugin.getInstance().getMessage("git.checkout.detachedHead.title"), GitPlugin.getInstance().getMessage("git.checkout.detachedHead.message"), DisplaySimpleMessageClientCommand.ICON_ERROR)); } monitor.worked(1); return true; } catch (Exception e) { channel.appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } finally { monitor.done(); } }
From source file:org.flowerplatform.web.git.operation.internal.PullCommand.java
License:Open Source License
/** * Executes the {@code Pull} command with all the options and parameters * collected by the setter methods (e.g. * {@link #setProgressMonitor(ProgressMonitor)}) of this class. Each * instance of this class should only be used for one invocation of the * command. Don't call this method twice on an instance. * * @return the result of the pull/* w ww . j av a 2s.co m*/ * @throws WrongRepositoryStateException * @throws InvalidConfigurationException * @throws DetachedHeadException * @throws InvalidRemoteException * @throws CanceledException * @throws RefNotFoundException * @throws NoHeadException * @throws org.eclipse.jgit.api.errors.TransportException * @throws GitAPIException */ @SuppressWarnings("restriction") public PullResult call() throws GitAPIException, WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException, InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException, org.eclipse.jgit.api.errors.TransportException { checkCallable(); monitor.beginTask(JGitText.get().pullTaskName, 2); Object[] data = GitPlugin.getInstance().getUtils().getFetchPushUpstreamDataRefSpecAndRemote(repo); String fullBranch = (String) data[0]; String branchName = fullBranch.substring(Constants.R_HEADS.length()); if (!repo.getRepositoryState().equals(RepositoryState.SAFE)) throw new WrongRepositoryStateException(MessageFormat.format(JGitText.get().cannotPullOnARepoWithState, repo.getRepositoryState().name())); // get the configured remote for the currently checked out branch // stored in configuration key branch.<branch name>.remote Config repoConfig = repo.getConfig(); String remote = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE); if (remote == null) // fall back to default remote remote = Constants.DEFAULT_REMOTE_NAME; // get the name of the branch in the remote repository // stored in configuration key branch.<branch name>.merge String remoteBranchName = (String) data[1]; // determines whether rebase should be used after fetching boolean doRebase = (boolean) data[3]; final boolean isRemote = !remote.equals("."); //$NON-NLS-1$ String remoteUri; FetchResult fetchRes; if (isRemote) { remoteUri = (String) data[2]; if (monitor.isCancelled()) throw new CanceledException( MessageFormat.format(JGitText.get().operationCanceled, JGitText.get().pullTaskName)); RefSpec refSpec = new RefSpec(); refSpec = refSpec.setForceUpdate(true); refSpec = refSpec.setSourceDestination(remoteBranchName, fullBranch); FetchCommand fetch = new Git(repo).fetch().setRemote(remote).setRefSpecs(refSpec); fetch.setProgressMonitor(monitor); configure(fetch); fetchRes = fetch.call(); } else { // we can skip the fetch altogether remoteUri = "local repository"; fetchRes = null; } monitor.update(1); if (monitor.isCancelled()) throw new CanceledException( MessageFormat.format(JGitText.get().operationCanceled, JGitText.get().pullTaskName)); // we check the updates to see which of the updated branches // corresponds // to the remote branch name AnyObjectId commitToMerge; if (isRemote) { Ref r = null; if (fetchRes != null) { r = fetchRes.getAdvertisedRef(remoteBranchName); if (r == null) r = fetchRes.getAdvertisedRef(Constants.R_HEADS + remoteBranchName); } if (r == null) throw new JGitInternalException( MessageFormat.format(JGitText.get().couldNotGetAdvertisedRef, remoteBranchName)); else commitToMerge = r.getObjectId(); } else { try { commitToMerge = repo.resolve(remoteBranchName); if (commitToMerge == null) throw new RefNotFoundException( MessageFormat.format(JGitText.get().refNotResolved, remoteBranchName)); } catch (IOException e) { throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfPullCommand, e); } } String upstreamName = "branch \'" + Repository.shortenRefName(remoteBranchName) + "\' of " + remoteUri; PullResult result; if (doRebase) { RebaseCommand rebase = new Git(repo).rebase(); RebaseResult rebaseRes = rebase.setUpstream(commitToMerge).setUpstreamName(upstreamName) .setProgressMonitor(monitor).setOperation(Operation.BEGIN).call(); result = new PullResult(fetchRes, remote, rebaseRes); } else { MergeCommand merge = new Git(repo).merge(); merge.include(upstreamName, commitToMerge); MergeResult mergeRes = merge.call(); monitor.update(1); result = new PullResult(fetchRes, remote, mergeRes); } monitor.endTask(); return result; }