List of usage examples for org.eclipse.jgit.api PushCommand call
@Override public Iterable<PushResult> call() throws GitAPIException, InvalidRemoteException, org.eclipse.jgit.api.errors.TransportException
Execute the push command with all the options and parameters collected by the setter methods of this class.
From source file:org.jboss.arquillian.container.openshift.util.GitUtil.java
License:Apache License
/** * Pushes local repository upstream/*from w w w . j a v a2 s .c o m*/ * * @param credentialsProvider the credentials provider to get SSH pass phrase */ public void push(CredentialsProvider credentialsProvider) { PushCommand push = git.push(); push.setCredentialsProvider(credentialsProvider); try { push.call(); } catch (JGitInternalException e) { throw new IllegalStateException("Unable to push into remote Git repository", e); } catch (InvalidRemoteException e) { throw new IllegalStateException("Unable to push into remote Git repository", e); } catch (TransportException e) { throw new IllegalStateException("Unable to push into remote Git repository", e); } catch (GitAPIException e) { throw new IllegalStateException("Unable to push into remote Git repository", e); } }
From source file:org.kuali.student.git.importer.ApplyManualBranchCleanup.java
License:Educational Community License
/** * @param args/*from w ww. j a va2s. c o m*/ */ public static void main(String[] args) { if (args.length < 4 || args.length > 7) { usage(); } File inputFile = new File(args[0]); if (!inputFile.exists()) usage(); boolean bare = false; if (args[2].trim().equals("1")) { bare = true; } String remoteName = args[3].trim(); String refPrefix = Constants.R_HEADS; if (args.length == 5) refPrefix = args[4].trim(); String userName = null; String password = null; if (args.length == 6) userName = args[5].trim(); if (args.length == 7) password = args[6].trim(); try { Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[1]).getAbsoluteFile(), false, bare); Git git = new Git(repo); RevWalk rw = new RevWalk(repo); ObjectInserter objectInserter = repo.newObjectInserter(); BufferedReader fileReader = new BufferedReader(new FileReader(inputFile)); String line = fileReader.readLine(); int lineNumber = 1; BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate(); List<RefSpec> branchesToDelete = new ArrayList<>(); while (line != null) { if (line.startsWith("#") || line.length() == 0) { // skip over comments and blank lines line = fileReader.readLine(); lineNumber++; continue; } String parts[] = line.trim().split(":"); String branchName = parts[0]; Ref branchRef = repo.getRef(refPrefix + "/" + branchName); if (branchRef == null) { log.warn("line: {}, No branch matching {} exists, skipping.", lineNumber, branchName); line = fileReader.readLine(); lineNumber++; continue; } String tagName = null; if (parts.length > 1) tagName = parts[1]; if (tagName != null) { if (tagName.equals("keep")) { log.info("keeping existing branch for {}", branchName); line = fileReader.readLine(); lineNumber++; continue; } if (tagName.equals("tag")) { /* * Shortcut to say make the tag start with the same name as the branch. */ tagName = branchName; } // create a tag RevCommit commit = rw.parseCommit(branchRef.getObjectId()); ObjectId tag = GitRefUtils.insertTag(tagName, commit, objectInserter); batch.addCommand(new ReceiveCommand(null, tag, Constants.R_TAGS + tagName, Type.CREATE)); log.info("converting branch {} into a tag {}", branchName, tagName); } if (remoteName.equals("local")) { batch.addCommand( new ReceiveCommand(branchRef.getObjectId(), null, branchRef.getName(), Type.DELETE)); } else { // if the branch is remote then remember its name so we can batch delete after we have the full list. branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + branchName)); } line = fileReader.readLine(); lineNumber++; } fileReader.close(); // run the batch update batch.execute(rw, new TextProgressMonitor()); if (!remoteName.equals("local")) { // push the tag to the remote right now log.info("pushing tags to {}", remoteName); PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags() .setProgressMonitor(new TextProgressMonitor()); if (userName != null) pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password)); Iterable<PushResult> results = pushCommand.call(); for (PushResult pushResult : results) { if (!pushResult.equals(Result.NEW)) { log.warn("failed to push tag " + pushResult.getMessages()); } } // delete the branches from the remote log.info("pushing branch deletes to remote: {}", remoteName); results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete) .setProgressMonitor(new TextProgressMonitor()).call(); } objectInserter.release(); rw.release(); } catch (Exception e) { log.error("unexpected Exception ", e); } }
From source file:org.kuali.student.git.importer.ConvertBuildTagBranchesToGitTags.java
License:Educational Community License
/** * @param args/*w ww. j a v a 2 s.c o m*/ */ public static void main(String[] args) { if (args.length < 3 || args.length > 6) { System.err.println("USAGE: <git repository> <bare> <ref mode> [<ref prefix> <username> <password>]"); System.err.println("\t<bare> : 0 (false) or 1 (true)"); System.err.println("\t<ref mode> : local or name of remote"); System.err.println("\t<ref prefix> : refs/heads (default) or say refs/remotes/origin (test clone)"); System.exit(-1); } boolean bare = false; if (args[1].trim().equals("1")) { bare = true; } String remoteName = args[2].trim(); String refPrefix = Constants.R_HEADS; if (args.length == 4) refPrefix = args[3].trim(); String userName = null; String password = null; if (args.length == 5) userName = args[4].trim(); if (args.length == 6) password = args[5].trim(); try { Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[0]).getAbsoluteFile(), false, bare); Git git = new Git(repo); ObjectInserter objectInserter = repo.newObjectInserter(); Collection<Ref> repositoryHeads = repo.getRefDatabase().getRefs(refPrefix).values(); RevWalk rw = new RevWalk(repo); Map<String, ObjectId> tagNameToTagId = new HashMap<>(); Map<String, Ref> tagNameToRef = new HashMap<>(); for (Ref ref : repositoryHeads) { String branchName = ref.getName().substring(refPrefix.length() + 1); if (branchName.contains("tag") && branchName.contains("builds")) { String branchParts[] = branchName.split("_"); int buildsIndex = ArrayUtils.indexOf(branchParts, "builds"); String moduleName = StringUtils.join(branchParts, "_", buildsIndex + 1, branchParts.length); RevCommit commit = rw.parseCommit(ref.getObjectId()); ObjectId tag = GitRefUtils.insertTag(moduleName, commit, objectInserter); tagNameToTagId.put(moduleName, tag); tagNameToRef.put(moduleName, ref); } } BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate(); List<RefSpec> branchesToDelete = new ArrayList<>(); for (Entry<String, ObjectId> entry : tagNameToTagId.entrySet()) { String tagName = entry.getKey(); // create the reference to the tag object batch.addCommand( new ReceiveCommand(null, entry.getValue(), Constants.R_TAGS + tagName, Type.CREATE)); // delete the original branch object Ref branch = tagNameToRef.get(entry.getKey()); if (remoteName.equals("local")) { batch.addCommand(new ReceiveCommand(branch.getObjectId(), null, branch.getName(), Type.DELETE)); } else { String adjustedBranchName = branch.getName().substring(refPrefix.length() + 1); branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + adjustedBranchName)); } } // create the tags batch.execute(rw, new TextProgressMonitor()); if (!remoteName.equals("local")) { // push the tag to the remote right now PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags() .setProgressMonitor(new TextProgressMonitor()); if (userName != null) pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password)); Iterable<PushResult> results = pushCommand.call(); for (PushResult pushResult : results) { if (!pushResult.equals(Result.NEW)) { log.warn("failed to push tag " + pushResult.getMessages()); } } // delete the branches from the remote results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete) .setProgressMonitor(new TextProgressMonitor()).call(); log.info(""); } // Result result = GitRefUtils.createTagReference(repo, moduleName, tag); // // if (!result.equals(Result.NEW)) { // log.warn("failed to create tag {} for branch {}", moduleName, branchName); // continue; // } // // if (deleteMode) { // result = GitRefUtils.deleteRef(repo, ref); // // if (!result.equals(Result.NEW)) { // log.warn("failed to delete branch {}", branchName); // continue; // } objectInserter.release(); rw.release(); } catch (Exception e) { log.error("unexpected Exception ", e); } }
From source file:org.ms123.common.git.GitServiceImpl.java
License:Open Source License
public void push(@PName("name") String name) throws RpcException { try {//from ww w . j ava 2 s.c o m String gitSpace = System.getProperty("git.repos"); File dir = new File(gitSpace, name); if (!dir.exists()) { throw new RpcException(ERROR_FROM_METHOD, 100, "GitService.push:Repo(" + name + ") not exists"); } Git git = Git.open(dir); PushCommand push = git.push(); push.setRefSpecs(new RefSpec(REF_PREFIX + "master")).setRemote("origin"); //ic.setPushAll(true); Iterable<PushResult> result = null; try { result = push.call(); } catch (org.eclipse.jgit.api.errors.TransportException e) { if (e.getCause() instanceof org.eclipse.jgit.errors.NoRemoteRepositoryException) { info("Push:" + e.getCause().getMessage()); return; } else { throw e; } } for (PushResult pushResult : result) { if (StringUtils.isNotBlank(pushResult.getMessages())) { debug(pushResult.getMessages()); } } return; } catch (Exception e) { throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.push:", e); } finally { } }
From source file:org.mule.module.git.GitConnector.java
License:Open Source License
/** * Update remote refs along with associated objects * * {@sample.xml ../../../doc/mule-module-git.xml.sample git:push} * * @param remote The remote (uri or name) used for the push operation. * @param force Sets the force preference for push operation * @param overrideDirectory Name of the directory to use for git repository *///from ww w .ja v a 2 s. com @Processor public void push(@Optional @Default("origin") String remote, @Optional @Default("false") boolean force, @Optional String overrideDirectory) { try { Git git = new Git(getGitRepo(overrideDirectory)); PushCommand push = git.push(); push.setRemote(remote); push.setForce(force); push.call(); } catch (Exception e) { throw new RuntimeException("Unable to push to " + remote, e); } }
From source file:org.wandora.application.tools.git.CommitPush.java
License:Open Source License
@Override public void execute(Wandora wandora, Context context) { try {/*from w w w. jav a2 s . co m*/ Git git = getGit(); if (git != null) { if (isNotEmpty(getGitRemoteUrl())) { if (commitPushUI == null) { commitPushUI = new CommitPushUI(); } commitPushUI.setPassword(getPassword()); commitPushUI.setUsername(getUsername()); commitPushUI.openInDialog(); if (commitPushUI.wasAccepted()) { setDefaultLogger(); setLogTitle("Git commit and push"); saveWandoraProject(); log("Removing deleted files from local repository."); org.eclipse.jgit.api.Status status = git.status().call(); Set<String> missing = status.getMissing(); if (missing != null && !missing.isEmpty()) { for (String missingFile : missing) { git.rm().addFilepattern(missingFile).call(); } } log("Adding new files to the local repository."); git.add().addFilepattern(".").call(); log("Committing changes to the local repository."); String commitMessage = commitPushUI.getMessage(); if (commitMessage == null || commitMessage.length() == 0) { commitMessage = getDefaultCommitMessage(); log("No commit message provided. Using default message."); } git.commit().setMessage(commitMessage).call(); String username = commitPushUI.getUsername(); String password = commitPushUI.getPassword(); setUsername(username); setPassword(password); PushCommand push = git.push(); if (isNotEmpty(username)) { log("Setting push credentials."); CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( username, password); push.setCredentialsProvider(credentialsProvider); } log("Pushing upstream."); push.call(); log("Ready."); } } else { log("Repository has no remote origin and can't be pushed. " + "Commit changes to the local repository using Commit to local... " + "To push changes to a remote repository initialize repository by cloning."); } } else { logAboutMissingGitRepository(); } } catch (GitAPIException gae) { log(gae.toString()); } catch (NoWorkTreeException nwte) { log(nwte.toString()); } catch (IOException ioe) { log(ioe.toString()); } catch (TopicMapException tme) { log(tme.toString()); } catch (Exception e) { log(e); } setState(WAIT); }
From source file:org.wandora.application.tools.git.Push.java
License:Open Source License
@Override public void execute(Wandora wandora, Context context) { try {//from ww w. j a v a 2s .c o m Git git = getGit(); if (git != null) { if (isNotEmpty(getGitRemoteUrl())) { if (pushUI == null) { pushUI = new PushUI(); } pushUI.setPassword(getPassword()); pushUI.setUsername(getUsername()); pushUI.setRemoteUrl(getGitRemoteUrl()); pushUI.openInDialog(); if (pushUI.wasAccepted()) { setDefaultLogger(); setLogTitle("Git push"); String username = pushUI.getUsername(); String password = pushUI.getPassword(); String remoteUrl = pushUI.getRemoteUrl(); setUsername(username); setPassword(password); // setGitRemoteUrl(remoteUrl); PushCommand push = git.push(); log("Pushing local changes to upstream."); if (username != null && username.length() > 0) { CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( username, password); push.setCredentialsProvider(credentialsProvider); } Iterable<PushResult> pushResults = push.call(); for (PushResult pushResult : pushResults) { String pushResultMessage = pushResult.getMessages(); if (isNotEmpty(pushResultMessage)) { log(pushResultMessage); } } log("Ready."); } } else { log("Repository has no remote origin and can't be pushed. " + "Initialize repository by cloning remote repository to set the remote origin."); } } else { logAboutMissingGitRepository(); } } catch (TransportException tre) { if (tre.toString().contains("origin: not found.")) { log("Git remote origin is not found. Check the remote url and remote git repository."); } } catch (GitAPIException gae) { log(gae.toString()); } catch (NoWorkTreeException nwte) { log(nwte.toString()); } catch (Exception e) { log(e); } setState(WAIT); }
From source file:org.webcat.core.git.GitUtilities.java
License:Open Source License
/** * Sets up a new base Git repository for the specified object. * * @param object the object whose file store is desired * @param location the file system location for the repository * @return the newly created repository//from ww w.j av a2 s . c om */ private static Repository setUpNewRepository(EOEnterpriseObject object, File location) throws IOException { // This method performs the following actions to set up a new // repository: // // 1) Creates a new bare repository in the location requested by the // method argument. // 2) Creates a temporary non-bare repository in the system temp // directory, which is then configured to use the bare repository // as a remote repository. // 3) Creates a README.txt file in the temporary repository's working // directory, which contains a welcome message determined by the // type of object that created the repo. // 4) Adds the README.txt to the repository, commits the change, and // then pushes the changes to the bare repository. // 5) Finally, the temporary repository is deleted. // // This results in a usable bare repository being created, which a user // can now clone locally in order to manage their Web-CAT file store. // Create the bare repository. InitCommand init = new InitCommand(); init.setDirectory(location); init.setBare(true); Repository bareRepository = init.call().getRepository(); // Create the temporary repository. File tempRepoDir = File.createTempFile("newgitrepo", null); tempRepoDir.delete(); tempRepoDir.mkdirs(); init = new InitCommand(); init.setDirectory(tempRepoDir); Repository tempRepository = init.call().getRepository(); // Create the welcome files in the temporary repo. if (object instanceof RepositoryProvider) { RepositoryProvider provider = (RepositoryProvider) object; try { provider.initializeRepositoryContents(tempRepoDir); } catch (Exception e) { log.error( "The following exception occurred when trying to " + "initialize the repository contents at " + location.getAbsolutePath() + ", but I'm continuing " + "anyway to ensure that the repository isn't corrupt.", e); } } // Make sure we created at least one file, since we can't do much with // an empty repository. If the object didn't put anything in the // staging area, we'll just create a dummy README file. File[] files = tempRepoDir.listFiles(); boolean foundFile = false; for (File file : files) { String name = file.getName(); if (!".".equals(name) && !"..".equals(name) && !".git".equalsIgnoreCase(name)) { foundFile = true; break; } } if (!foundFile) { PrintWriter writer = new PrintWriter(new File(tempRepoDir, "README.txt")); writer.println("This readme file is provided so that the initial repository\n" + "has some content. You may delete it when you push other files\n" + "into the repository, if you wish."); writer.close(); } // Create an appropriate default .gitignore file. PrintWriter writer = new PrintWriter(new File(tempRepoDir, ".gitignore")); writer.println("~*"); writer.println("._*"); writer.println(".TemporaryItems"); writer.println(".DS_Store"); writer.println("Thumbs.db"); writer.close(); // Add the files to the temporary repository. AddCommand add = new AddCommand(tempRepository); add.addFilepattern("."); add.setUpdate(false); try { add.call(); } catch (NoFilepatternException e) { log.error("An exception occurred when adding the welcome files " + "to the repository: ", e); return bareRepository; } // Commit the changes. String email = Application.configurationProperties().getProperty("coreAdminEmail"); CommitCommand commit = new Git(tempRepository).commit(); commit.setAuthor("Web-CAT", email); commit.setCommitter("Web-CAT", email); commit.setMessage("Initial repository setup."); try { commit.call(); } catch (Exception e) { log.error("An exception occurred when committing the welcome files " + "to the repository: ", e); return bareRepository; } // Push the changes to the bare repository. PushCommand push = new Git(tempRepository).push(); @SuppressWarnings("deprecation") String url = location.toURL().toString(); push.setRemote(url); push.setRefSpecs(new RefSpec("master"), new RefSpec("master")); try { push.call(); } catch (Exception e) { log.error("An exception occurred when pushing the welcome files " + "to the repository: ", e); return bareRepository; } // Cleanup after ourselves. FileUtilities.deleteDirectory(tempRepoDir); return bareRepository; }
From source file:org.wso2.carbon.deployment.synchronizer.git.GitBasedArtifactRepository.java
License:Open Source License
/** * Pushes the artifacts of the tenant to relevant remote repository * * @param gitRepoCtx TenantGitRepositoryContext instance for the tenant *//*from w w w . j a v a 2 s.co m*/ private void pushToRemoteRepo(TenantGitRepositoryContext gitRepoCtx) { PushCommand pushCmd = gitRepoCtx.getGit().push(); UsernamePasswordCredentialsProvider credentialsProvider = GitUtilities .createCredentialsProvider(repositoryManager, gitRepoCtx.getTenantId()); if (credentialsProvider == null) { log.warn("Remote repository credentials not available for tenant " + gitRepoCtx.getTenantId() + ", aborting push"); return; } pushCmd.setCredentialsProvider(credentialsProvider); try { pushCmd.call(); } catch (GitAPIException e) { log.error("Pushing artifacts to remote repository failed for tenant " + gitRepoCtx.getTenantId(), e); } }
From source file:org.zanata.sync.jobs.plugin.git.service.impl.GitSyncService.java
License:Open Source License
@Override public void syncTranslationToRepo(SyncJobDetail jobDetail, Path workingDir) { UsernamePasswordCredential user = new UsernamePasswordCredential(jobDetail.getSrcRepoUsername(), jobDetail.getSrcRepoSecret()); try (Git git = Git.open(workingDir.toFile())) { if (log.isDebugEnabled()) { log.debug("before syncing translation, current branch: {}", git.getRepository().getBranch()); }//from www . j a v a 2 s . c o m StatusCommand statusCommand = git.status(); Status status = statusCommand.call(); Set<String> uncommittedChanges = status.getUncommittedChanges(); uncommittedChanges.addAll(status.getUntracked()); if (!uncommittedChanges.isEmpty()) { log.info("uncommitted files in git repo: {}", uncommittedChanges); AddCommand addCommand = git.add(); // ignore zanata cache folder uncommittedChanges.stream().filter(file -> !file.startsWith(".zanata-cache/")) .forEach(addCommand::addFilepattern); addCommand.call(); log.info("commit changed files"); CommitCommand commitCommand = git.commit(); commitCommand.setAuthor(commitAuthorName(), commitAuthorEmail()); commitCommand.setMessage(commitMessage(jobDetail.getZanataUsername())); RevCommit revCommit = commitCommand.call(); log.info("push to remote the commit: {}", revCommit); PushCommand pushCommand = git.push(); setUserIfProvided(pushCommand, user); pushCommand.call(); } else { log.info("nothing changed so nothing to do"); } } catch (IOException e) { log.error("what the heck", e); throw new RepoSyncException("failed opening " + workingDir + " as git repo", e); } catch (GitAPIException e) { log.error("what the heck", e); throw new RepoSyncException("Failed committing translations into the repo", e); } }