List of usage examples for org.eclipse.jgit.api Git push
public PushCommand push()
From source file:gov.va.isaac.sync.git.SyncServiceGIT.java
License:Apache License
/** * @throws MergeFailure /* w w w. j a va 2 s . co m*/ * @throws AuthenticationException * @see gov.va.isaac.interfaces.sync.ProfileSyncI#updateCommitAndPush(java.io.File, java.lang.String, java.lang.String, java.lang.String, * java.lang.String[]) */ @Override public Set<String> updateCommitAndPush(String commitMessage, String username, String password, MergeFailOption mergeFailOption, String... files) throws IllegalArgumentException, IOException, MergeFailure, AuthenticationException { try { log.info("Commit Files called {}", (files == null ? "-null-" : Arrays.toString(files))); Git git = getGit(); if (git.status().call().getConflicting().size() > 0) { log.info("Previous merge failure not yet resolved"); throw new MergeFailure(git.status().call().getConflicting(), new HashSet<>()); } if (files == null) { files = git.status().call().getUncommittedChanges().toArray(new String[0]); log.info("Will commit the uncommitted files {}", Arrays.toString(files)); } if (StringUtils.isEmptyOrNull(commitMessage) && files.length > 0) { throw new IllegalArgumentException("The commit message is required when files are specified"); } if (files.length > 0) { CommitCommand commit = git.commit(); for (String file : files) { commit.setOnly(file); } commit.setAuthor(username, "42"); commit.setMessage(commitMessage); RevCommit rv = commit.call(); log.debug("Local commit completed: " + rv.getFullMessage()); } //need to merge origin/master into master now, prior to push Set<String> result = updateFromRemote(username, password, mergeFailOption); log.debug("Pushing"); CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username, (password == null ? new char[] {} : password.toCharArray())); Iterable<PushResult> pr = git.push().setCredentialsProvider(cp).call(); pr.forEach(new Consumer<PushResult>() { @Override public void accept(PushResult t) { log.debug("Push Result Messages: " + t.getMessages()); } }); log.info("commit and push complete. Current status: " + statusToString(git.status().call())); return result; } catch (TransportException te) { if (te.getMessage().contains("Auth fail")) { log.info("Auth fail", te); throw new AuthenticationException("Auth fail"); } else { log.error("Unexpected", te); throw new IOException("Internal error", te); } } catch (GitAPIException e) { log.error("Unexpected", e); throw new IOException("Internal error", e); } }
From source file:io.dpwspoon.github.utils.TravisCIUtils.java
public static void addTravisFileToRepo(final String uri, final String branchName, final String orgName, final String repoName, File workingDir) throws IOException, InvalidRemoteException, TransportException, GitAPIException { File directory = new File(workingDir, repoName); Git localRepo = null; for (int trys = 0; true; trys++) { try {//from w ww.ja v a2 s. com localRepo = Git.cloneRepository().setCredentialsProvider(credentialsProvider) .setDirectory(directory).setURI(uri).call(); break; } catch (TransportException e) { // sporadic failure FileUtils.deleteFolder(directory); if (trys > 3) { throw e; } } } localRepo.checkout().setCreateBranch(true).setName(branchName).call(); addTravisFileTo(localRepo, directory, orgName, repoName); localRepo.commit().setAll(true).setMessage("Added .travis.yml and badge to README.md").call(); localRepo.push().setCredentialsProvider(credentialsProvider).call(); }
From source file:io.fabric8.collector.git.GitHelpers.java
License:Apache License
public static RevCommit doCommitAndPush(Git git, String message, UserDetails userDetails, PersonIdent author, String branch, String origin, boolean pushOnCommit) throws GitAPIException { CommitCommand commit = git.commit().setAll(true).setMessage(message); if (author != null) { commit = commit.setAuthor(author); }//from w w w .j av a2s. c o m RevCommit answer = commit.call(); if (LOG.isDebugEnabled()) { LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage()); } if (pushOnCommit) { PushCommand push = git.push(); configureCommand(push, userDetails); Iterable<PushResult> results = push.setRemote(origin).call(); for (PushResult result : results) { if (LOG.isDebugEnabled()) { LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch + " updates: " + toString(result.getRemoteUpdates())); } } } return answer; }
From source file:io.fabric8.forge.rest.client.ForgeTestSupport.java
License:Apache License
protected Build assertCodeChangeTriggersWorkingBuild(JenkinsServer jenkins, String jenkinsUrl, final String projectName, Build firstBuild, String folderName) throws Exception { File cloneDir = new File(getBasedir(), "target/projects/" + projectName); String gitUrl = asserGetAppGitCloneURL(forgeClient, projectName); Git git = ForgeClientAsserts.assertGitCloneRepo(gitUrl, cloneDir); // lets make a dummy commit... File readme = new File(cloneDir, "ReadMe.md"); boolean mustAdd = false; String text = ""; if (readme.exists()) { text = IOHelpers.readFully(readme); } else {/*from w w w.j a va 2s . c o m*/ mustAdd = true; } text += "\nupdated at: " + new Date(); Files.writeToFile(readme, text, Charset.defaultCharset()); if (mustAdd) { AddCommand add = git.add().addFilepattern("*").addFilepattern("."); add.call(); } LOG.info("Committing change to " + readme); CommitCommand commit = git.commit().setAll(true).setAuthor(forgeClient.getPersonIdent()) .setMessage("dummy commit to trigger a rebuild"); commit.call(); PushCommand command = git.push(); command.setCredentialsProvider(forgeClient.createCredentialsProvider()); command.setRemote("origin").call(); LOG.info("Git pushed change to " + readme); // now lets wait for the next build to start int nextBuildNumber = firstBuild.getNumber() + 1; Asserts.assertWaitFor(10 * 60 * 1000, new Block() { @Override public void invoke() throws Exception { JenkinsServer jenkins = createJenkinsServer(forgeClient.getKubernetesClient(), jenkinsNamespace); JobWithDetails job = assertJob(jenkins, folderName, projectName); Build lastBuild = job.getLastBuild(); assertThat(lastBuild.getNumber()) .describedAs("Waiting for latest build for job " + projectName + " to start") .isGreaterThanOrEqualTo(nextBuildNumber); } }); return ForgeClientAsserts.assertBuildCompletes(jenkins, jenkinsUrl, folderName, projectName); }
From source file:io.fabric8.forge.rest.git.RepositoryResource.java
License:Apache License
protected Iterable<PushResult> doPush(Git git) throws Exception { PushCommand command = git.push(); configureCommand(command, userDetails); return command.setRemote(getRemote()).call(); }
From source file:io.fabric8.forge.rest.main.GitCommandCompletePostProcessor.java
License:Apache License
protected RevCommit doCommitAndPush(Git git, String message, CredentialsProvider credentials, PersonIdent author, String remote, String branch, String origin) throws IOException, GitAPIException { CommitCommand commit = git.commit().setAll(true).setMessage(message); if (author != null) { commit = commit.setAuthor(author); }/*from w ww. ja va2 s. co m*/ RevCommit answer = commit.call(); if (LOG.isDebugEnabled()) { LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage()); } if (isPushOnCommit()) { Iterable<PushResult> results = git.push().setCredentialsProvider(credentials).setRemote(origin).call(); for (PushResult result : results) { if (LOG.isDebugEnabled()) { LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch + " updates: " + GitHelpers.toString(result.getRemoteUpdates())); } } } return answer; }
From source file:io.fabric8.git.internal.GitDataStore.java
License:Apache License
@Override public void deleteVersion(final String version) { assertValid();//from w w w. j ava 2s. c o m // remove a branch gitOperation(new GitOperation<Void>() { public Void call(Git git, GitContext context) throws Exception { removeVersion(version); GitHelpers.removeBranch(git, version); git.push().setTimeout(gitTimeout).setCredentialsProvider(getCredentialsProvider()) .add(":refs/heads/" + version).call(); return null; } }); }
From source file:io.fabric8.git.internal.GitDataStore.java
License:Apache License
/** * Pushes any committed changes to the remote repo *//*from w w w.j av a 2 s. c o m*/ protected Iterable<PushResult> doPush(Git git, GitContext gitContext, CredentialsProvider credentialsProvider) throws Exception { assertValid(); try { Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remoteRef.get(), "url"); if (Strings.isNullOrBlank(url)) { LOG.info("No remote repository defined yet for the git repository at " + GitHelpers.getRootGitDirectory(git) + " so not doing a push"); return Collections.emptyList(); } return git.push().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setPushAll() .call(); } catch (Throwable ex) { // log stacktrace at debug level LOG.warn("Failed to push from the remote git repo " + GitHelpers.getRootGitDirectory(git) + " due " + ex.getMessage() + ". This exception is ignored."); LOG.debug("Failed to push from the remote git repo " + GitHelpers.getRootGitDirectory(git) + ". This exception is ignored.", ex); return Collections.emptyList(); } }
From source file:io.fabric8.git.zkbridge.Bridge.java
License:Apache License
private static void update(Git git, CuratorFramework zookeeper, CredentialsProvider credentialsProvider) throws Exception { String remoteName = "origin"; boolean remoteAvailable = false; try {/*from w ww. j a v a 2 s. c o m*/ git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remoteName).call(); remoteAvailable = true; } catch (Exception e) { // Ignore fetch exceptions if (LOGGER.isTraceEnabled()) { LOGGER.trace("Unable to fetch master", e); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("Unable to fetch master: " + e.getClass().getName() + ": " + e.getMessage()); } } // Handle versions in git and not in zookeeper 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/" + remoteName + "/")) { String name = ref.getName().substring(("refs/remotes/" + remoteName + "/").length()); if (!"master".equals(name) && !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.equals("master") && !name.endsWith("-tmp")) { localBranches.put(name, ref); gitVersions.add(name); } } } List<String> zkVersions = getChildren(zookeeper, ZkPath.CONFIG_VERSIONS.getPath()); createDefault(zookeeper, "/fabric/configs/git", null); Properties versionsMetadata = loadProps(zookeeper, "/fabric/configs/git"); boolean allDone = true; // Check no modifs in zookeeper String lastModified = Long.toString(lastModified(zookeeper, ZkPath.CONFIG_VERSIONS.getPath())); if (!lastModified.equals(versionsMetadata.get("zk-lastmodified"))) { allDone = false; } // Check the versions in zk and git are the same if (zkVersions.size() != gitVersions.size() || !zkVersions.containsAll(gitVersions)) { allDone = false; } // Check all local and remote branches exists if (gitVersions.size() != localBranches.size() || !localBranches.keySet().containsAll(gitVersions)) { allDone = false; } // If remote is available, check that all remote branches exist if (remoteAvailable && !remoteBranches.keySet().containsAll(gitVersions)) { allDone = false; } // Check git commmits if (allDone) { for (String version : zkVersions) { String zkCommit = versionsMetadata.get(version); String localCommit = localBranches.get(version).getObjectId().getName(); String remoteCommit = remoteAvailable ? remoteBranches.get(version).getObjectId().getName() : null; if (!localCommit.equals(zkCommit) || remoteCommit != null && !localCommit.equals(remoteCommit)) { allDone = false; break; } } } if (allDone) { return; } // ZooKeeper -> Git changes for (String version : zkVersions) { String zkNode = ZkPath.CONFIG_VERSION.getPath(version); // Checkout updated version List<Ref> allBranches = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call(); Ref local = null; Ref remote = null; Ref tmp = null; for (Ref ref : allBranches) { if (ref.getName().equals("refs/remotes/" + remoteName + "/" + version)) { remote = ref; } else if (ref.getName().equals("refs/heads/" + version)) { local = ref; } else if (ref.getName().equals("refs/heads/" + version + "-tmp")) { tmp = ref; } } if (local == null) { git.branchCreate().setName(version).call(); } if (tmp == null) { git.branchCreate().setName(version + "-tmp").call(); } git.clean().setCleanDirectories(true).call(); git.checkout().setName("HEAD").setForce(true).call(); git.checkout().setName(version).setForce(true).call(); if (remoteAvailable && remote != null) { MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS).include(remote.getObjectId()) .call(); // TODO: check merge conflicts } git.checkout().setName(version + "-tmp").setForce(true).call(); String gitCommit = versionsMetadata.get(version); if (gitCommit != null) { try { git.reset().setMode(ResetCommand.ResetType.HARD).setRef(gitCommit).call(); } catch (Exception e) { // Ignore, we did our best if (LOGGER.isTraceEnabled()) { LOGGER.trace("Unable to reset branch to commit", e); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("Unable to reset branch to commit " + gitCommit + ": " + e.getClass().getName() + ": " + e.getMessage()); } } } // Apply changes to git syncVersionFromZkToGit(git, zookeeper, zkNode); if (git.status().call().isClean()) { git.checkout().setName(version).setForce(true).call(); } else { ObjectId rev = git.commit().setMessage("Merge zookeeper updates in version " + version).call() .getId(); git.checkout().setName(version).setForce(true).call(); MergeResult result = git.merge().setStrategy(MergeStrategy.OURS).include(rev).call(); // TODO: check merge conflicts } if (remoteAvailable) { git.push().setCredentialsProvider(credentialsProvider).setRefSpecs(new RefSpec(version)).call(); } // Apply changes to zookeeper syncVersionFromGitToZk(git, zookeeper, zkNode); versionsMetadata.put(version, git.getRepository().getRef("HEAD").getObjectId().getName()); } // Iterate through known git versions for (String version : gitVersions) { String state = versionsMetadata.get(version); if (zkVersions.contains(version)) { continue; } // The version is not known to zookeeper, so create it if (state == null) { if (localBranches.containsKey(version)) { if (remoteAvailable) { git.push().setRefSpecs(new RefSpec(version)).call(); } } else { git.branchCreate().setName(version).call(); git.reset().setMode(ResetCommand.ResetType.HARD).setRef(remoteBranches.get(version).getName()) .call(); } git.checkout().setName(version).setForce(true).call(); // Sync zookeeper String zkNode = ZkPath.CONFIG_VERSION.getPath(version); create(zookeeper, zkNode); create(zookeeper, ZkPath.CONFIG_VERSIONS_PROFILES.getPath(version)); create(zookeeper, ZkPath.CONFIG_VERSIONS_CONTAINERS.getPath(version)); syncVersionFromGitToZk(git, zookeeper, zkNode); // Flag version as active versionsMetadata.put(version, git.getRepository().getRef("HEAD").getObjectId().getName()); } // The version has been deleted from zookeeper so delete it in git else { git.checkout().setName("master").setForce(true).call(); git.branchDelete().setBranchNames(version, version + "-tmp").setForce(true).call(); git.push().setRefSpecs(new RefSpec(version + ":")).call(); versionsMetadata.remove(version); } } versionsMetadata.put("zk-lastmodified", Long.toString(lastModified(zookeeper, ZkPath.CONFIG_VERSIONS.getPath()))); setPropertiesAsMap(zookeeper, "/fabric/configs/git", versionsMetadata); }
From source file:io.fabric8.itests.basic.git.FabricGitTestSupport.java
License:Apache License
/** * Create a profile in git and check that its bridged to the registry. *///from w w w.j av a 2s . c o m protected void createAndTestProfileInGit(FabricService fabricService, CuratorFramework curator, Git git, String version, String profile) throws Exception { //Create the test profile in git System.out.println("Create test profile:" + profile + " in git."); GitUtils.checkoutBranch(git, "origin", version); String relativeProfileDir = "fabric/profiles/" + profile + ".profile"; File testProfileDir = new File(git.getRepository().getWorkTree(), relativeProfileDir); testProfileDir.mkdirs(); File testProfileConfig = new File(testProfileDir, "io.fabric8.agent.properties"); testProfileConfig.createNewFile(); Files.writeToFile(testProfileConfig, "", Charset.defaultCharset()); git.add().addFilepattern(relativeProfileDir).call(); git.commit().setAll(true).setMessage("Create " + profile).call(); PullResult pullResult = git.pull().setCredentialsProvider(getCredentialsProvider()).setRebase(true).call(); git.push().setCredentialsProvider(getCredentialsProvider()).setPushAll().setRemote("origin").call(); GitUtils.waitForBranchUpdate(curator, version); for (int i = 0; i < 5; i++) { if (fabricService.getDataStore().hasProfile(version, profile)) { return; } else { Thread.sleep(1000); } } fail("Expected to find profile " + profile + " in version " + version); }