List of usage examples for org.eclipse.jgit.api Git checkout
public CheckoutCommand checkout()
From source file:com.barchart.jenkins.cascade.PluginScmGit.java
License:BSD License
/** * See {@link Git#checkout()}//from www. j a va2s .c om */ public static CheckoutResult doCheckout(final File workspace, final String localBranch, final String remoteName, final String remoteBranch) { try { final Git git = Git.open(workspace); final CheckoutCommand command = git.checkout().setName(localBranch).setForce(true); if (findRef(workspace, localBranch) == null) { command.setCreateBranch(true).setUpstreamMode(SetupUpstreamMode.TRACK) .setStartPoint(remote(remoteName, remoteBranch)).call(); } else { command.call(); } return command.getResult(); } catch (final Throwable e) { throw new RuntimeException(e); } }
From source file:com.denimgroup.threadfix.service.repository.GitServiceImpl.java
License:Mozilla Public License
@Override public File cloneRepoToDirectory(Application application, File dirLocation) { if (dirLocation.exists()) { File gitDirectoryFile = new File(dirLocation.getAbsolutePath() + File.separator + ".git"); try {//from www.j ava 2s. c o m if (!gitDirectoryFile.exists()) { Git newRepo = clone(application, dirLocation); if (newRepo != null) return newRepo.getRepository().getWorkTree(); } else { Repository localRepo = new FileRepository(gitDirectoryFile); Git git = new Git(localRepo); if (application.getRepositoryRevision() != null && !application.getRepositoryRevision().isEmpty()) { //remote checkout git.checkout().setCreateBranch(true).setStartPoint(application.getRepositoryRevision()) .setName(application.getRepositoryRevision()).call(); } else { List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call(); String repoBranch = (application.getRepositoryBranch() != null && !application.getRepositoryBranch().isEmpty()) ? application.getRepositoryBranch() : "master"; boolean localCheckout = false; for (Ref ref : refs) { String refName = ref.getName(); if (refName.contains(repoBranch) && !refName.contains(Constants.R_REMOTES)) { localCheckout = true; } } String HEAD = localRepo.getFullBranch(); if (HEAD.contains(repoBranch)) { git.pull().setRemote("origin").setRemoteBranchName(repoBranch) .setCredentialsProvider(getApplicationCredentials(application)).call(); } else { if (localCheckout) { //local checkout git.checkout().setName(application.getRepositoryBranch()).call(); git.pull().setRemote("origin").setRemoteBranchName(repoBranch) .setCredentialsProvider(getApplicationCredentials(application)).call(); } else { //remote checkout git.checkout().setCreateBranch(true).setName(repoBranch) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM) .setStartPoint("origin/" + repoBranch).call(); } } } return git.getRepository().getWorkTree(); } } catch (JGitInternalException e) { log.error(EXCEPTION_MESSAGE, e); } catch (IOException e) { log.error(EXCEPTION_MESSAGE, e); } catch (WrongRepositoryStateException e) { log.error(EXCEPTION_MESSAGE, e); } catch (InvalidConfigurationException e) { log.error(EXCEPTION_MESSAGE, e); } catch (DetachedHeadException e) { log.error(EXCEPTION_MESSAGE, e); } catch (InvalidRemoteException e) { log.error(EXCEPTION_MESSAGE, e); } catch (CanceledException e) { log.error(EXCEPTION_MESSAGE, e); } catch (RefNotFoundException e) { log.error(EXCEPTION_MESSAGE, e); } catch (NoHeadException e) { log.error(EXCEPTION_MESSAGE, e); } catch (RefAlreadyExistsException e) { log.error(EXCEPTION_MESSAGE, e); } catch (CheckoutConflictException e) { log.error(EXCEPTION_MESSAGE, e); } catch (InvalidRefNameException e) { log.error(EXCEPTION_MESSAGE, e); } catch (TransportException e) { log.error(EXCEPTION_MESSAGE, e); } catch (GitAPIException e) { log.error(EXCEPTION_MESSAGE, e); } } else { try { log.info("Attempting to clone application from repository."); Git result = clone(application, dirLocation); if (result != null) { log.info("Application was successfully cloned from repository."); return result.getRepository().getWorkTree(); } log.error(EXCEPTION_MESSAGE); } catch (JGitInternalException e) { log.error(EXCEPTION_MESSAGE, e); } } return null; }
From source file:com.denimgroup.threadfix.service.repository.GitServiceImpl.java
License:Mozilla Public License
private Git clone(Application application, File dirLocation) { Git git = null; try {/*from w w w . j a va 2 s . com*/ CloneCommand clone = Git.cloneRepository(); clone.setURI(application.getRepositoryUrl()).setDirectory(dirLocation) .setCredentialsProvider(getApplicationCredentials(application)); if (application.getRepositoryBranch() != null && !application.getRepositoryBranch().isEmpty()) { clone.setBranch(application.getRepositoryBranch()); } // clone git repo git = clone.call(); // checkout specific revision if (application.getRepositoryRevision() != null && !application.getRepositoryRevision().isEmpty()) { git.checkout().setCreateBranch(true).setStartPoint(application.getRepositoryRevision()) .setName(application.getRepositoryRevision()).call(); } } catch (WrongRepositoryStateException e) { log.error(EXCEPTION_MESSAGE, e); } catch (InvalidConfigurationException e) { log.error(EXCEPTION_MESSAGE, e); } catch (DetachedHeadException e) { log.error(EXCEPTION_MESSAGE, e); } catch (InvalidRemoteException e) { log.error(EXCEPTION_MESSAGE, e); } catch (CanceledException e) { log.error(EXCEPTION_MESSAGE, e); } catch (RefNotFoundException e) { log.error(EXCEPTION_MESSAGE, e); } catch (NoHeadException e) { log.error(EXCEPTION_MESSAGE, e); } catch (RefAlreadyExistsException e) { log.error(EXCEPTION_MESSAGE, e); } catch (CheckoutConflictException e) { log.error(EXCEPTION_MESSAGE, e); } catch (InvalidRefNameException e) { log.error(EXCEPTION_MESSAGE, e); } catch (TransportException e) { log.error(EXCEPTION_MESSAGE, e); } catch (GitAPIException e) { log.error(EXCEPTION_MESSAGE, e); } return git; }
From source file:com.door43.translationstudio.tasks.PullTargetTranslationTask.java
private String pull(Repo repo, String remote) { Git git; try {//w w w . j a v a2 s . c o m repo.deleteRemote("origin"); repo.setRemote("origin", remote); git = repo.getGit(); } catch (IOException e) { return null; } Manifest localManifest = Manifest.generate(this.targetTranslation.getPath()); // TODO: we might want to get some progress feedback for the user PullCommand pullCommand = git.pull().setTransportConfigCallback(new TransportCallback()).setRemote("origin") .setStrategy(mergeStrategy).setRemoteBranchName("master").setProgressMonitor(new ProgressMonitor() { @Override public void start(int totalTasks) { } @Override public void beginTask(String title, int totalWork) { } @Override public void update(int completed) { } @Override public void endTask() { } @Override public boolean isCancelled() { return false; } }); try { PullResult result = pullCommand.call(); MergeResult mergeResult = result.getMergeResult(); if (mergeResult != null && mergeResult.getConflicts() != null && mergeResult.getConflicts().size() > 0) { this.status = Status.MERGE_CONFLICTS; this.conflicts = mergeResult.getConflicts(); // revert manifest merge conflict to avoid corruption if (this.conflicts.containsKey("manifest.json")) { Logger.i("PullTargetTranslationTask", "Reverting to server manifest"); try { git.checkout().setStage(CheckoutCommand.Stage.THEIRS).addPath("manifest.json").call(); Manifest remoteManifest = Manifest.generate(this.targetTranslation.getPath()); localManifest = TargetTranslation.mergeManifests(localManifest, remoteManifest); } catch (CheckoutConflictException e) { // failed to reset manifest.json Logger.e(this.getClass().getName(), "Failed to reset manifest: " + e.getMessage(), e); } finally { localManifest.save(); } } // keep our license if (this.conflicts.containsKey("LICENSE.md")) { Logger.i("PullTargetTranslationTask", "Reverting to local license"); try { git.checkout().setStage(CheckoutCommand.Stage.OURS).addPath("LICENSE.md").call(); } catch (CheckoutConflictException e) { Logger.e(this.getClass().getName(), "Failed to reset license: " + e.getMessage(), e); } } } else { this.status = Status.UP_TO_DATE; } return "message"; } catch (TransportException e) { Logger.e(this.getClass().getName(), e.getMessage(), e); Throwable cause = e.getCause(); if (cause != null) { Throwable subException = cause.getCause(); if (subException != null) { String detail = subException.getMessage(); if ("Auth fail".equals(detail)) { this.status = Status.AUTH_FAILURE; // we do special handling for auth failure } } else if (cause instanceof NoRemoteRepositoryException) { this.status = Status.NO_REMOTE_REPO; } } return null; } catch (Exception e) { Throwable cause = e.getCause(); if (cause instanceof NoRemoteRepositoryException) { this.status = Status.NO_REMOTE_REPO; } Logger.e(this.getClass().getName(), e.getMessage(), e); return null; } catch (OutOfMemoryError e) { Logger.e(this.getClass().getName(), e.getMessage(), e); this.status = Status.OUT_OF_MEMORY; return null; } catch (Throwable e) { Logger.e(this.getClass().getName(), e.getMessage(), e); return null; } }
From source file:com.ejwa.gitdepmavenplugin.DownloaderMojo.java
License:Open Source License
private void checkout(Git git, Pom pom, GitDependency dependency) throws MojoExecutionException { final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency); final String version = dependencyHandler.getDependencyVersion(pom); try {// ww w . j a v a 2 s .c o m final Repository repository = git.getRepository(); final ObjectId rev = repository.resolve(version); final RevCommit rc = new RevWalk(repository).parseCommit(rev); final CheckoutCommand checkout = git.checkout(); checkout.setName("maven-gitdep-branch-" + rc.getCommitTime()); checkout.setStartPoint(rc); checkout.setCreateBranch(true); checkout.call(); final Status status = checkout.getResult().getStatus(); if (status != Status.OK) { throw new MojoExecutionException( String.format("Invalid checkout state (%s) of dependency.", status)); } } catch (IOException | InvalidRefNameException | RefAlreadyExistsException | RefNotFoundException ex) { throw new MojoExecutionException(String.format("Failed to check out dependency for %s.%s", dependency.getGroupId(), dependency.getArtifactId()), ex); } }
From source file:com.ejwa.mavengitdepplugin.DownloaderMojo.java
License:Open Source License
private void checkout(Git git, POM pom, GitDependency dependency) { final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency); final String version = dependencyHandler.getDependencyVersion(pom); try {// w w w . jav a2 s . c o m final ObjectId rev = git.getRepository().resolve(version); final RevCommit rc = new RevWalk(git.getRepository()).parseCommit(rev); final CheckoutCommand checkout = git.checkout(); checkout.setName("maven-gitdep-branch-" + rc.getCommitTime()); checkout.setStartPoint(rc); checkout.setCreateBranch(true); checkout.call(); final Status status = checkout.getResult().getStatus(); if (!status.equals(Status.OK)) { getLog().error("Status of checkout: " + status); throw new IllegalStateException("Invalid checkout state of dependency."); } } catch (Exception ex) { getLog().error(ex); throw new IllegalStateException("Failed to check out dependency."); } }
From source file:com.ericsson.eiffel.remrem.semantics.clone.PrepareLocalEiffelSchemas.java
License:Apache License
/** * This method is used to clone repository from github using the URL and branch to local destination folder. * // w w w .j av a 2 s .com * @param repoURL * repository url to clone. * @param branch * specific branch name of the repository to clone * @param localEiffelRepoPath * destination path to clone the repo. */ private void cloneEiffelRepo(final String repoURL, final String branch, final File localEiffelRepoPath) { Git localGitRepo = null; // checking for repository exists or not in the localEiffelRepoPath try { if (!localEiffelRepoPath.exists()) { // cloning github repository by using URL and branch name into local localGitRepo = Git.cloneRepository().setURI(repoURL).setBranch("master") .setDirectory(localEiffelRepoPath).call(); } else { // If required repository already exists localGitRepo = Git.open(localEiffelRepoPath); // Reset to normal if uncommitted changes are present localGitRepo.reset().call(); //Checkout to master before pull the changes localGitRepo.checkout().setName(EiffelConstants.MASTER).call(); // To get the latest changes from remote repository. localGitRepo.pull().call(); } //checkout to input branch after changes pulled into local localGitRepo.checkout().setName(branch).call(); } catch (Exception e) { LOGGER.info( "please check proxy settings if proxy enabled update proxy.properties file to clone behind proxy"); e.printStackTrace(); } }
From source file:com.gitblit.servlet.GitServletTest.java
License:Apache License
private void testMergeCommitterVerification(boolean expectedSuccess) throws Exception { UserModel user = getUser();/* w w w .jav a2 s . c o m*/ delete(user); CredentialsProvider cp = new UsernamePasswordCredentialsProvider(user.username, user.password); // fork from original to a temporary bare repo File verification = new File(GitBlitSuite.REPOSITORIES, "refchecks/verify-committer.git"); if (verification.exists()) { FileUtils.delete(verification, FileUtils.RECURSIVE); } CloneCommand clone = Git.cloneRepository(); clone.setURI(MessageFormat.format("{0}/ticgit.git", url)); clone.setDirectory(verification); clone.setBare(true); clone.setCloneAllBranches(true); clone.setCredentialsProvider(cp); GitBlitSuite.close(clone.call()); // require push permissions and committer verification RepositoryModel model = repositories().getRepositoryModel("refchecks/verify-committer.git"); model.authorizationControl = AuthorizationControl.NAMED; model.accessRestriction = AccessRestrictionType.PUSH; model.verifyCommitter = true; // grant user push permission user.setRepositoryPermission(model.name, AccessPermission.PUSH); gitblit().addUser(user); repositories().updateRepositoryModel(model.name, model, false); // clone temp bare repo to working copy File local = new File(GitBlitSuite.REPOSITORIES, "refchecks/verify-wc"); if (local.exists()) { FileUtils.delete(local, FileUtils.RECURSIVE); } clone = Git.cloneRepository(); clone.setURI(MessageFormat.format("{0}/{1}", url, model.name)); clone.setDirectory(local); clone.setBare(false); clone.setCloneAllBranches(true); clone.setCredentialsProvider(cp); GitBlitSuite.close(clone.call()); Git git = Git.open(local); // checkout a mergetest branch git.checkout().setCreateBranch(true).setName("mergetest").call(); // change identity git.getRepository().getConfig().setString("user", null, "name", "mergetest"); git.getRepository().getConfig().setString("user", null, "email", "mergetest@merge.com"); git.getRepository().getConfig().save(); // commit a file File file = new File(local, "MERGECHK2"); OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET); BufferedWriter w = new BufferedWriter(os); w.write("// " + new Date().toString() + "\n"); w.close(); git.add().addFilepattern(file.getName()).call(); RevCommit mergeTip = git.commit().setMessage(file.getName() + " test").call(); // return to master git.checkout().setName("master").call(); // restore identity if (expectedSuccess) { git.getRepository().getConfig().setString("user", null, "name", user.username); git.getRepository().getConfig().setString("user", null, "email", user.emailAddress); git.getRepository().getConfig().save(); } // commit a file file = new File(local, "MERGECHK1"); os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET); w = new BufferedWriter(os); w.write("// " + new Date().toString() + "\n"); w.close(); git.add().addFilepattern(file.getName()).call(); git.commit().setMessage(file.getName() + " test").call(); // merge the tip of the mergetest branch into master with --no-ff MergeResult mergeResult = git.merge().setFastForward(FastForwardMode.NO_FF).include(mergeTip.getId()) .call(); assertEquals(MergeResult.MergeStatus.MERGED, mergeResult.getMergeStatus()); // push the merged master to the origin Iterable<PushResult> results = git.push().setCredentialsProvider(cp).setRemote("origin").call(); for (PushResult result : results) { RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/master"); Status status = ref.getStatus(); if (expectedSuccess) { assertTrue("Verification failed! User was NOT able to push commit! " + status.name(), Status.OK.equals(status)); } else { assertTrue("Verification failed! User was able to push commit! " + status.name(), Status.REJECTED_OTHER_REASON.equals(status)); } } GitBlitSuite.close(git); // close serving repository GitBlitSuite.close(verification); }
From source file:com.github.checkstyle.regression.extract.CheckstyleInjector.java
License:Open Source License
/** * Checkouts to the PR branch in the given repository. * @throws GitAPIException JGit library exception */// w ww . jav a 2 s.c om private void checkoutToPrBranch() throws GitAPIException { final Git git = new Git(repository); try { git.checkout().setName(branch).call(); } finally { git.close(); } }
From source file:com.github.rwhogg.git_vcr.App.java
License:Open Source License
/** * main is the entry point for Git-VCR/*from w w w.ja v a2 s .c o m*/ * @param args Command-line arguments */ public static void main(String[] args) { Options options = parseCommandLine(args); HierarchicalINIConfiguration configuration = null; try { configuration = getConfiguration(); } catch (ConfigurationException e) { Util.error("could not parse configuration file!"); } // verify we are in a git folder and then construct the repo final File currentFolder = new File("."); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository localRepo = null; try { localRepo = builder.findGitDir().build(); } catch (IOException e) { Util.error("not in a Git folder!"); } // deal with submodules assert localRepo != null; if (localRepo.isBare()) { FileRepositoryBuilder parentBuilder = new FileRepositoryBuilder(); Repository parentRepo; try { parentRepo = parentBuilder.setGitDir(new File("..")).findGitDir().build(); localRepo = SubmoduleWalk.getSubmoduleRepository(parentRepo, currentFolder.getName()); } catch (IOException e) { Util.error("could not find parent of submodule!"); } } // if we need to retrieve the patch file, get it now URL patchUrl = options.getPatchUrl(); String patchPath = patchUrl.getFile(); File patchFile = null; HttpUrl httpUrl = HttpUrl.get(patchUrl); if (httpUrl != null) { try { patchFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".diff"); Request request = new Request.Builder().url(httpUrl).build(); OkHttpClient client = new OkHttpClient(); Call call = client.newCall(request); Response response = call.execute(); ResponseBody body = response.body(); if (!response.isSuccessful()) { Util.error("could not retrieve diff file from URL " + patchUrl); } String content = body.string(); org.apache.commons.io.FileUtils.write(patchFile, content, (Charset) null); } catch (IOException ie) { Util.error("could not retrieve diff file from URL " + patchUrl); } } else { patchFile = new File(patchPath); } // find the patch //noinspection ConstantConditions if (!patchFile.canRead()) { Util.error("patch file " + patchFile.getAbsolutePath() + " is not readable!"); } final Git git = new Git(localRepo); // handle the branch String branchName = options.getBranchName(); String theOldCommit = null; try { theOldCommit = localRepo.getBranch(); } catch (IOException e2) { Util.error("could not get reference to current branch!"); } final String oldCommit = theOldCommit; // needed to reference from shutdown hook if (branchName != null) { // switch to the branch try { git.checkout().setName(branchName).call(); } catch (RefAlreadyExistsException e) { // FIXME Auto-generated catch block e.printStackTrace(); } catch (RefNotFoundException e) { Util.error("the branch " + branchName + " was not found!"); } catch (InvalidRefNameException e) { Util.error("the branch name " + branchName + " is invalid!"); } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) { Util.error("there was a checkout conflict!"); } catch (GitAPIException e) { Util.error("there was an unspecified Git API failure!"); } } // ensure there are no changes before we apply the patch try { if (!git.status().call().isClean()) { Util.error("cannot run git-vcr while there are uncommitted changes!"); } } catch (NoWorkTreeException e1) { // won't happen assert false; } catch (GitAPIException e1) { Util.error("call to git status failed!"); } // list all the files changed String patchName = patchFile.getName(); Patch patch = new Patch(); try { patch.parse(new FileInputStream(patchFile)); } catch (FileNotFoundException e) { assert false; } catch (IOException e) { Util.error("could not parse the patch file!"); } ReviewResults oldResults = new ReviewResults(patchName, patch, configuration, false); try { oldResults.review(); } catch (InstantiationException e1) { Util.error("could not instantiate a review tool class!"); } catch (IllegalAccessException e1) { Util.error("illegal access to a class"); } catch (ClassNotFoundException e1) { Util.error("could not find a review tool class"); } catch (ReviewFailedException e1) { e1.printStackTrace(); Util.error("Review failed!"); } // we're about to change the repo, so register a shutdown hook to clean it up Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { cleanupGit(git, oldCommit); } }); // apply the patch try { git.apply().setPatch(new FileInputStream(patchFile)).call(); } catch (PatchFormatException e) { Util.error("patch file " + patchFile.getAbsolutePath() + " is malformatted!"); } catch (PatchApplyException e) { Util.error("patch file " + patchFile.getAbsolutePath() + " did not apply correctly!"); } catch (FileNotFoundException e) { assert false; } catch (GitAPIException e) { Util.error(e.getLocalizedMessage()); } ReviewResults newResults = new ReviewResults(patchName, patch, configuration, true); try { newResults.review(); } catch (InstantiationException e1) { Util.error("could not instantiate a review tool class!"); } catch (IllegalAccessException e1) { Util.error("illegal access to a class"); } catch (ClassNotFoundException e1) { Util.error("could not find a review tool class"); } catch (ReviewFailedException e1) { e1.printStackTrace(); Util.error("Review failed!"); } // generate and show the report VelocityReport report = new VelocityReport(patch, oldResults, newResults); File reportFile = null; try { reportFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".html"); org.apache.commons.io.FileUtils.write(reportFile, report.toString(), (String) null); } catch (IOException e) { Util.error("could not generate the results page!"); } try { assert reportFile != null; Desktop.getDesktop().open(reportFile); } catch (IOException e) { Util.error("could not open the results page!"); } }