List of usage examples for org.eclipse.jgit.api Git checkout
public CheckoutCommand checkout()
From source file:org.enterprisedomain.classmaker.impl.ProjectImpl.java
License:Apache License
/** * <!-- begin-user-doc --> <!-- end-user-doc --> * //from w ww .j a va2 s. com * @generated NOT */ public void checkout(Version version, long time) { Revision revision = null; if (getRevisions().containsKey(version)) { setProjectVersion(version); if (getProjectName().isEmpty()) return; Git git = null; @SuppressWarnings("unchecked") SCMOperator<Git> operator = (SCMOperator<Git>) getWorkspace().getSCMRegistry().get(getProjectName()); Ref ref = null; try { git = operator.getRepositorySCM(); ref = git.getRepository().findRef(version.toString()); if (ref != null) git.checkout().setName(ref.getName()).call(); } catch (CheckoutConflictException e) { if (git != null) { try { ResetCommand reset = git.reset().setMode(ResetType.HARD); if (ref != null) reset.setRef(ref.getName()); reset.call(); } catch (CheckoutConflictException ex) { ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(ex)); } catch (GitAPIException ex) { ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(ex)); } } } catch (Exception e) { ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e)); } finally { try { operator.ungetRepositorySCM(); } catch (Exception e) { ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e)); } } revision = getRevisions().get(version); if (revision.getStateHistory().containsKey(time)) { State state = revision.getStateHistory().get((Object) time); EList<String> commits = state.getCommitIds(); if (!commits.isEmpty()) { revision.checkout(time, state.getCommitId()); } else revision.checkout(time); } } else throw new IllegalStateException(NLS.bind(Messages.VersionNotExists, version)); }
From source file:org.exist.git.xquery.Checkout.java
License:Open Source License
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try {//w w w . j av a2s. co m String localPath = args[0].getStringValue(); if (!(localPath.endsWith("/"))) localPath += File.separator; Git git = Git.open(new Resource(localPath), FS); git.checkout().setName(args[1].getStringValue()).setCreateBranch(false).setForce(true).call(); return BooleanValue.TRUE; } catch (Throwable e) { throw new XPathException(this, Module.EXGIT001, e); } }
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 {// w ww . j a va2 s . co m 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.fusesource.fabric.git.internal.GitDataStore.java
License:Apache License
public <T> T gitOperation(PersonIdent personIdent, GitOperation<T> operation, boolean pullFirst, GitContext context) {/*w w w. jav a2s . c o m*/ synchronized (gitOperationMonitor) { assertValid(); try { Git git = getGit(); Repository repository = git.getRepository(); CredentialsProvider credentialsProvider = getCredentialsProvider(); // lets default the identity if none specified if (personIdent == null) { personIdent = new PersonIdent(repository); } if (GitHelpers.hasGitHead(git)) { // lets stash any local changes just in case.. git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write") .call(); } String originalBranch = repository.getBranch(); RevCommit statusBefore = CommitUtils.getHead(repository); if (pullFirst) { doPull(git, credentialsProvider); } T answer = operation.call(git, context); boolean requirePush = context.isRequirePush(); if (context.isRequireCommit()) { requirePush = true; String message = context.getCommitMessage().toString(); if (message.length() == 0) { LOG.warn("No commit message from " + operation + ". Please add one! :)"); } git.commit().setMessage(message).call(); } git.checkout().setName(originalBranch).call(); if (requirePush || hasChanged(statusBefore, CommitUtils.getHead(repository))) { clearCaches(); doPush(git, context, credentialsProvider); fireChangeNotifications(); } return answer; } catch (Exception e) { throw FabricException.launderThrowable(e); } } }
From source file:org.fusesource.fabric.git.internal.GitDataStore.java
License:Apache License
/** * Performs a pull so the git repo is pretty much up to date before we start performing operations on it *//* ww w . jav a2 s . co m*/ protected void doPull(Git git, CredentialsProvider credentialsProvider) { assertValid(); try { Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remote, "url"); if (Strings.isNullOrBlank(url)) { if (LOG.isDebugEnabled()) { LOG.debug("No remote repository defined for the git repository at " + GitHelpers.getRootGitDirectory(git) + " so not doing a pull"); } return; } /* String branch = repository.getBranch(); String mergeUrl = config.getString("branch", branch, "merge"); if (Strings.isNullOrBlank(mergeUrl)) { if (LOG.isDebugEnabled()) { LOG.debug("No merge spec for branch." + branch + ".merge in the git repository at " + GitHelpers.getRootGitDirectory(git) + " so not doing a pull"); } return; } */ if (LOG.isDebugEnabled()) { LOG.debug("Performing a fetch in git repository " + GitHelpers.getRootGitDirectory(git) + " on remote URL: " + url); } boolean hasChanged = false; try { git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remote).call(); } catch (Exception e) { LOG.debug("Fetch failed. Ignoring"); return; } // Get local and remote branches Map<String, Ref> localBranches = new HashMap<String, Ref>(); Map<String, Ref> remoteBranches = new HashMap<String, Ref>(); Set<String> gitVersions = new HashSet<String>(); for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) { if (ref.getName().startsWith("refs/remotes/" + remote + "/")) { String name = ref.getName().substring(("refs/remotes/" + remote + "/").length()); if (!name.endsWith("-tmp")) { remoteBranches.put(name, ref); gitVersions.add(name); } } else if (ref.getName().startsWith("refs/heads/")) { String name = ref.getName().substring(("refs/heads/").length()); if (!name.endsWith("-tmp")) { localBranches.put(name, ref); gitVersions.add(name); } } } // Check git commmits for (String version : gitVersions) { // Delete unneeded local branches. //Check if any remote branches was found as a guard for unwanted deletions. if (!remoteBranches.containsKey(version) && !remoteBranches.isEmpty()) { //We never want to delete the master branch. if (!version.equals(MASTER_BRANCH)) { try { git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true) .call(); } catch (CannotDeleteCurrentBranchException ex) { git.checkout().setName(MASTER_BRANCH).setForce(true).call(); git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true) .call(); } hasChanged = true; } } // Create new local branches else if (!localBranches.containsKey(version)) { git.checkout().setCreateBranch(true).setName(version).setStartPoint(remote + "/" + version) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setForce(true).call(); hasChanged = true; } else { String localCommit = localBranches.get(version).getObjectId().getName(); String remoteCommit = remoteBranches.get(version).getObjectId().getName(); if (!localCommit.equals(remoteCommit)) { git.clean().setCleanDirectories(true).call(); git.checkout().setName("HEAD").setForce(true).call(); git.checkout().setName(version).setForce(true).call(); MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS) .include(remoteBranches.get(version).getObjectId()).call(); if (result.getMergeStatus() != MergeResult.MergeStatus.ALREADY_UP_TO_DATE) { hasChanged = true; } // TODO: handle conflicts } } } if (hasChanged) { LOG.debug("Changed after pull!"); if (credentialsProvider != null) { // TODO lets test if the profiles directory is present after checking out version 1.0? File profilesDirectory = getProfilesDirectory(git); } fireChangeNotifications(); } } catch (Throwable e) { LOG.error("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git) + ". Reason: " + e, e); } }
From source file:org.fusesource.fabric.git.internal.GitHelpers.java
License:Apache License
public static void checkoutBranch(Git git, String branch, String remote) throws GitAPIException { String current = currentBranch(git); if (equals(current, branch)) { return;/*w ww .ja va 2s.c om*/ } // lets check if the branch exists CheckoutCommand command = git.checkout().setName(branch); boolean exists = GitHelpers.localBranchExists(git, branch); if (!exists) { command = command.setCreateBranch(true).setForce(true); /* command = command.setCreateBranch(true).setForce(true). setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK). setStartPoint(remote + "/" + branch); */ } Ref ref = command.call(); if (LOG.isDebugEnabled()) { LOG.debug("Checked out branch " + branch + " with results " + ref.getName()); } configureBranch(git, branch, remote); }
From source file:org.gitective.tests.GitTestCase.java
License:Open Source License
/** * Checkout branch/*from w ww . jav a 2s.com*/ * * @param repo * @param name * @return branch ref * @throws Exception */ protected Ref checkout(File repo, String name) throws Exception { Git git = Git.open(repo); Ref ref = git.checkout().setName(name).call(); assertNotNull(ref); return ref; }
From source file:org.jboss.as.server.controller.git.GitRepository.java
License:Apache License
private void checkoutToSelectedBranch(final Git git) throws IOException, GitAPIException { boolean createBranch = !ObjectId.isId(branch); if (createBranch) { Ref ref = git.getRepository().exactRef(R_HEADS + branch); if (ref != null) { createBranch = false;// www . j a v a 2s . c o m } } CheckoutCommand checkout = git.checkout().setCreateBranch(createBranch).setName(branch); checkout.call(); if (checkout.getResult().getStatus() == CheckoutResult.Status.ERROR) { throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, defaultRemoteRepository); } }
From source file:org.jboss.forge.addon.git.GitUtilsImpl.java
License:Open Source License
@Override public Ref checkout(final Git git, final String remote, final boolean createBranch, final SetupUpstreamMode mode, final boolean force) throws GitAPIException { CheckoutCommand checkout = git.checkout(); checkout.setCreateBranch(createBranch); checkout.setName(remote);//ww w. ja v a 2s . c o m checkout.setForce(force); checkout.setUpstreamMode(mode); return checkout.call(); }
From source file:org.jboss.forge.addon.git.GitUtilsImpl.java
License:Open Source License
@Override public Ref checkout(final Git git, final Ref localRef, final SetupUpstreamMode mode, final boolean force) throws GitAPIException { CheckoutCommand checkout = git.checkout(); checkout.setName(Repository.shortenRefName(localRef.getName())); checkout.setForce(force);//from w w w . j a v a 2 s . c o m checkout.setUpstreamMode(mode); return checkout.call(); }