List of usage examples for org.eclipse.jgit.api Git fetch
public FetchCommand fetch()
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 . ja v a 2s . c o 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
/** * Performs a pull so the git repo is pretty much up to date before we start performing operations on it *//*from www . j a v 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.itests.basic.git.ExternalGitTest.java
License:Apache License
@Test public void testCreateProfilesMixedWithVersion() throws Exception { String testZkProfilebase = "zkprofile"; String testGitProfilebase = "gitprofile"; System.err.println(executeCommand("fabric:create -n")); //Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult().build(); String gitRepoUrl = GitUtils.getMasterUrl(getCurator()); assertNotNull(gitRepoUrl);/*w w w . j ava 2s. c om*/ GitUtils.waitForBranchUpdate(getCurator(), "1.0"); Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo) .setCredentialsProvider(getCredentialsProvider()).call(); Git git = Git.open(testrepo); GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0"); git.fetch().setCredentialsProvider(getCredentialsProvider()); GitUtils.checkoutBranch(git, "origin", "1.0"); //Check that the default profile exists assertTrue(new File(testrepo, "fabric/profiles/default.profile").exists()); FabricService fabricService = getFabricService(); for (int v = 0; v < 2; v++) { //Create test profile for (int i = 1; i < 2; i++) { String gitProfile = testGitProfilebase + v + "p" + i; String zkProfile = testZkProfilebase + v + "p" + i; createAndTestProfileInGit(git, "1." + v, gitProfile); createAndTestProfileInDataStore(git, "1." + v, zkProfile); } } }
From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java
License:Apache License
@Ignore @Test//from ww w .j a v a 2 s . c om public void testCreateProfileInGit() throws Exception { String testProfileNameBase = "mytestprofile-"; System.err.println(executeCommand("fabric:create -n")); System.err.println(executeCommand("features:install fabric-git")); //Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult().build(); String gitRepoUrl = GitUtils.getMasterUrl(getCurator()); assertNotNull(gitRepoUrl); GitUtils.waitForBranchUpdate(getCurator(), "1.0"); Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo) .setCredentialsProvider(getCredentialsProvider()).call(); Git git = Git.open(testrepo); GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0"); git.fetch().setCredentialsProvider(getCredentialsProvider()); GitUtils.checkoutBranch(git, "origin", "1.0"); //Check that the default profile exists assertTrue(new File(testrepo, "default").exists()); //Create test profile for (int i = 1; i <= 5; i++) { String testProfileName = testProfileNameBase + i; createAndTestProfileInGit(git, "1.0", testProfileName); } }
From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java
License:Apache License
@Ignore @Test/*ww w. j av a 2 s . co m*/ public void testCreateProfileInZk() throws Exception { String testProfileNameBase = "mytestprofile-"; System.err.println(executeCommand("fabric:create -n")); System.err.println(executeCommand("features:install fabric-git")); //Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult().build(); String gitRepoUrl = GitUtils.getMasterUrl(getCurator()); assertNotNull(gitRepoUrl); GitUtils.waitForBranchUpdate(getCurator(), "1.0"); Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo) .setCredentialsProvider(getCredentialsProvider()).call(); Git git = Git.open(testrepo); GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0"); git.fetch().setCredentialsProvider(getCredentialsProvider()); GitUtils.checkoutBranch(git, "origin", "1.0"); //Check that the default profile exists assertTrue(new File(testrepo, "default").exists()); FabricService fabricService = getFabricService(); //Create test profile for (int i = 1; i <= 5; i++) { String testProfileName = testProfileNameBase + i; createAndTestProfileInZooKeeper(git, "1.0", testProfileName); } }
From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java
License:Apache License
@Ignore @Test/* w w w . j a v a2s .co m*/ public void testCreateProfilesMixed() throws Exception { String testZkProfilebase = "zkprofile-"; String testGitProfilebase = "gitprofile-"; System.err.println(executeCommand("fabric:create -n")); System.err.println(executeCommand("features:install fabric-git")); //Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult().build(); String gitRepoUrl = GitUtils.getMasterUrl(getCurator()); assertNotNull(gitRepoUrl); GitUtils.waitForBranchUpdate(getCurator(), "1.0"); Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo) .setCredentialsProvider(getCredentialsProvider()).call(); Git git = Git.open(testrepo); GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0"); git.fetch().setCredentialsProvider(getCredentialsProvider()); GitUtils.checkoutBranch(git, "origin", "1.0"); //Check that the default profile exists assertTrue(new File(testrepo, "default").exists()); FabricService fabricService = getFabricService(); //Create test profile for (int i = 1; i <= 5; i++) { String gitProfile = testGitProfilebase + i; String zkProfile = testZkProfilebase + i; createAndTestProfileInGit(git, "1.0", gitProfile); createAndTestProfileInZooKeeper(git, "1.0", zkProfile); } }
From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java
License:Apache License
@Test public void testCreateProfilesMixedWithVersion() throws Exception { String testZkProfilebase = "zkprofile-"; String testGitProfilebase = "gitprofile-"; System.err.println(executeCommand("fabric:create -n")); System.err.println(executeCommand("features:install fabric-git")); //Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult().build(); String gitRepoUrl = GitUtils.getMasterUrl(getCurator()); assertNotNull(gitRepoUrl);//from w w w . j av a 2 s .c o m GitUtils.waitForBranchUpdate(getCurator(), "1.0"); Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo) .setCredentialsProvider(getCredentialsProvider()).call(); Git git = Git.open(testrepo); GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0"); git.fetch().setCredentialsProvider(getCredentialsProvider()); GitUtils.checkoutBranch(git, "origin", "1.0"); //Check that the default profile exists assertTrue(new File(testrepo, "default").exists()); FabricService fabricService = getFabricService(); for (int v = 0; v < 3; v++) { //Create test profile for (int i = 1; i <= 3; i++) { String gitProfile = testGitProfilebase + v + "-" + i; String zkProfile = testZkProfilebase + v + "-" + i; createAndTestProfileInGit(git, "1." + v, gitProfile); createAndTestProfileInZooKeeper(git, "1." + v, zkProfile); } } }
From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java
License:Apache License
public void testWithProfiles() throws Exception { String testProfileNameBase = "mytestprofile-"; System.err.println(executeCommand("fabric:create -n")); Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult() .build();//from w ww. j a va 2 s . com String gitRepoUrl = GitUtils.getMasterUrl(getCurator()); GitUtils.waitForBranchUpdate(getCurator(), "1.0"); Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo) .setCredentialsProvider(getCredentialsProvider()).call(); Git git = Git.open(testrepo); GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0"); git.fetch().setCredentialsProvider(getCredentialsProvider()); GitUtils.checkoutBranch(git, "origin", "1.0"); //Check that the default profile exists assertTrue(new File(testrepo, "default").exists()); //Create test profile for (int i = 1; i <= 3; i++) { String testProfileName = testProfileNameBase + i; System.err.println("Create test profile:" + testProfileName + " in zookeeper"); getFabricService().getVersion("1.0").createProfile(testProfileName); GitUtils.waitForBranchUpdate(getCurator(), "1.0"); git.pull().setRebase(true).setCredentialsProvider(getCredentialsProvider()).call(); //Check that a newly created profile exists assertTrue(new File(testrepo, testProfileName).exists()); //Delete test profile System.err.println("Delete test profile:" + testProfileName + " in git."); git.rm().addFilepattern(testProfileName).call(); git.commit().setMessage("Delete " + testProfileName).call(); git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call(); GitUtils.waitForBranchUpdate(getCurator(), "1.0"); Thread.sleep(5000); assertFalse(new File(testrepo, testProfileName).exists()); assertNull(getCurator().checkExists() .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName))); //Create the test profile in git System.err.println("Create test profile:" + testProfileName + " in git."); File testProfileDir = new File(testrepo, testProfileName); testProfileDir.mkdirs(); File testProfileConfig = new File(testProfileDir, "org.fusesource.fabric.agent.properties"); testProfileConfig.createNewFile(); Files.writeToFile(testProfileConfig, "", Charset.defaultCharset()); git.add().addFilepattern(testProfileName).call(); RevCommit commit = git.commit().setMessage("Create " + testProfileName).call(); FileTreeIterator fileTreeItr = new FileTreeIterator(git.getRepository()); IndexDiff indexDiff = new IndexDiff(git.getRepository(), commit.getId(), fileTreeItr); System.out.println(indexDiff.getChanged()); System.out.println(indexDiff.getAdded()); git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call(); GitUtils.waitForBranchUpdate(getCurator(), "1.0"); //Check that it has been bridged in zookeeper Thread.sleep(15000); assertNotNull(getCurator().checkExists() .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName))); } }
From source file:org.gradle.vcs.git.internal.GitVersionControlSystem.java
License:Apache License
private static void updateSubModules(Git git) throws IOException, GitAPIException { SubmoduleWalk walker = SubmoduleWalk.forIndex(git.getRepository()); try {/*from w ww.j a v a 2 s . c o m*/ while (walker.next()) { Repository submodule = walker.getRepository(); try { Git submoduleGit = Git.wrap(submodule); submoduleGit.fetch().call(); git.submoduleUpdate().addPath(walker.getPath()).call(); submoduleGit.reset().setMode(ResetCommand.ResetType.HARD).call(); updateSubModules(submoduleGit); } finally { submodule.close(); } } } finally { walker.close(); } }
From source file:org.jabylon.team.git.GitTeamProvider.java
License:Open Source License
@Override public Collection<PropertyFileDiff> update(ProjectVersion project, IProgressMonitor monitor) throws TeamProviderException { SubMonitor subMon = SubMonitor.convert(monitor, 100); List<PropertyFileDiff> updatedFiles = new ArrayList<PropertyFileDiff>(); try {//from ww w . j a va 2 s .co m Repository repository = createRepository(project); Git git = Git.wrap(repository); FetchCommand fetchCommand = git.fetch(); URI uri = project.getParent().getRepositoryURI(); if (uri != null) fetchCommand.setRemote(stripUserInfo(uri).toString()); String refspecString = "refs/heads/{0}:refs/remotes/origin/{0}"; refspecString = MessageFormat.format(refspecString, project.getName()); RefSpec spec = new RefSpec(refspecString); fetchCommand.setRefSpecs(spec); subMon.subTask("Fetching from remote"); if (!"https".equals(uri.scheme()) && !"http".equals(uri.scheme())) fetchCommand.setTransportConfigCallback(createTransportConfigCallback(project.getParent())); fetchCommand.setCredentialsProvider(createCredentialsProvider(project.getParent())); fetchCommand.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(80))); fetchCommand.call(); ObjectId remoteHead = repository.resolve("refs/remotes/origin/" + project.getName() + "^{tree}"); DiffCommand diff = git.diff(); subMon.subTask("Caculating Diff"); diff.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(20))); diff.setOldTree(new FileTreeIterator(repository)); CanonicalTreeParser p = new CanonicalTreeParser(); ObjectReader reader = repository.newObjectReader(); try { p.reset(reader, remoteHead); } finally { reader.release(); } diff.setNewTree(p); checkCanceled(subMon); List<DiffEntry> diffs = diff.call(); for (DiffEntry diffEntry : diffs) { checkCanceled(subMon); updatedFiles.add(convertDiffEntry(diffEntry)); LOGGER.trace(diffEntry.toString()); } if (!updatedFiles.isEmpty()) { checkCanceled(subMon); //no more cancel after this point ObjectId lastCommitID = repository .resolve("refs/remotes/origin/" + project.getName() + "^{commit}"); LOGGER.info("Merging remote commit {} to {}/{}", new Object[] { lastCommitID, project.getName(), project.getParent().getName() }); //TODO: use rebase here? if (isRebase(project)) { RebaseCommand rebase = git.rebase(); rebase.setUpstream("refs/remotes/origin/" + project.getName()); RebaseResult result = rebase.call(); if (result.getStatus().isSuccessful()) { LOGGER.info("Rebase finished: {}", result.getStatus()); } else { LOGGER.error("Rebase of {} failed. Attempting abort", project.relativePath()); rebase = git.rebase(); rebase.setOperation(Operation.ABORT); result = rebase.call(); LOGGER.error("Abort finished with {}", result.getStatus()); } } else { MergeCommand merge = git.merge(); merge.include(lastCommitID); MergeResult mergeResult = merge.call(); LOGGER.info("Merge finished: {}", mergeResult.getMergeStatus()); } } else LOGGER.info("Update finished successfully. Nothing to merge, already up to date"); } catch (JGitInternalException e) { throw new TeamProviderException(e); } catch (InvalidRemoteException e) { throw new TeamProviderException(e); } catch (GitAPIException e) { throw new TeamProviderException(e); } catch (AmbiguousObjectException e) { throw new TeamProviderException(e); } catch (IOException e) { throw new TeamProviderException(e); } finally { monitor.done(); } return updatedFiles; }