List of usage examples for org.eclipse.jgit.api Git checkout
public CheckoutCommand checkout()
From source file:io.fabric8.git.internal.GitHelpers.java
License:Apache License
public static boolean checkoutTag(Git git, String tagName) throws GitAPIException { git.checkout().setName(tagName).setForce(true).call(); LOGGER.debug("Checked out tag: {}", tagName); return true;/*from w ww . j av a2 s . com*/ }
From source file:io.fabric8.git.zkbridge.Bridge.java
License:Apache License
private void updateLocal(Git git, CuratorFramework zookeeper, CredentialsProvider credentialsProvider) throws Exception { String remoteName = "origin"; try {/*from ww w . j av a 2 s . c o m*/ git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remoteName).call(); } catch (Exception e) { // Ignore fetch exceptions 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/" + 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); } } } // Check git commmits for (String version : gitVersions) { // Delete unneeded local branches if (!remoteBranches.containsKey(version)) { git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true).call(); } // Create new local branches else if (!localBranches.containsKey(version)) { git.branchCreate().setName(version).call(); git.reset().setMode(ResetCommand.ResetType.HARD).setRef(remoteBranches.get(version).getName()) .call(); } 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(); // TODO: handle conflicts } } } }
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 ww w . j a va 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.GitUtils.java
License:Apache License
public static void checkoutBranch(Git git, CredentialsProvider credentialsProvider, String remote, String branch) throws GitAPIException { String current = currentBranch(git); if (Objects.equal(current, branch)) { return;//from w ww . ja v a 2s . c o m } boolean localExists = localBranchExists(git, branch); boolean remoteExists = remoteBranchExists(git, remote, branch); if (localExists) { git.checkout().setName(branch).call(); } else if (remoteExists) { git.checkout().setName(branch).setCreateBranch(true).setForce(true) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) .setStartPoint(remote + "/" + branch).call(); } else { git.branchCreate().setName(branch).setForce(true).call(); git.checkout().setName(branch).call(); git.push().setCredentialsProvider(credentialsProvider).setRemote(remote) .setRefSpecs(new RefSpec(branch)).setForce(true).call(); } configureBranch(git, remote, getRemote(git, remote), branch); }
From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCacheCloneReadSaveRequest.java
License:Open Source License
private @Nonnull Git getActiveRepository(Repository repository) throws IOException { try {//from w w w .j av a 2s.c o m // Clone the bare repository File cloneDir = File.createTempFile("clone", ""); if (cloneDir.exists()) { if (cloneDir.isDirectory()) { FileUtils.deleteDirectory(cloneDir); } else { if (!cloneDir.delete()) { throw new ServiceException.UnexpectedErrorException("Unable to delete repository clone"); } } } if (!cloneDir.mkdirs()) { throw new ServiceException.UnexpectedErrorException("Unable to create repository clone directory"); } String url = repository.getConfig().getString("remote", "origin", "url"); Git gitClient = Git.cloneRepository().setCloneAllBranches(false) .setProgressMonitor(new CloneProgressMonitor(url)) .setURI(repository.getDirectory().getCanonicalPath()).setDirectory(cloneDir).call(); RemoteRemoveCommand remove = gitClient.remoteRemove(); remove.setName("origin"); remove.call(); RemoteAddCommand add = gitClient.remoteAdd(); add.setName("origin"); add.setUri(new URIish(gitSource.getRemote())); add.call(); if (GitUtils.isSshUrl(gitSource.getRemote())) { // Get committer info and credentials User user = User.current(); if (user == null) { throw new ServiceException.UnauthorizedException("Not authenticated"); } BasicSSHUserPrivateKey privateKey = UserSSHKeyManager.getOrCreate(user); // Make sure up-to-date and credentials work GitUtils.fetch(repository, privateKey); } else { FetchCommand fetch = gitClient.fetch(); fetch.call(); } if (!StringUtils.isEmpty(sourceBranch) && !sourceBranch.equals(branch)) { CheckoutCommand checkout = gitClient.checkout(); checkout.setStartPoint("origin/" + sourceBranch); checkout.setName(sourceBranch); checkout.setCreateBranch(true); // to create a new local branch checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK); checkout.call(); checkout = gitClient.checkout(); checkout.setName(branch); checkout.setCreateBranch(true); // this *should* be a new branch checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK); checkout.call(); } else { CheckoutCommand checkout = gitClient.checkout(); checkout.setStartPoint("origin/" + branch); checkout.setName(branch); checkout.setCreateBranch(true); // to create a new local branch checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK); checkout.call(); } return gitClient; } catch (GitAPIException | URISyntaxException ex) { throw new ServiceException.UnexpectedErrorException("Unable to get working repository directory", ex); } }
From source file:io.vertx.config.git.GitConfigStore.java
License:Apache License
private Git initializeGit() throws IOException, GitAPIException { if (path.isDirectory()) { Git git = Git.open(path); String current = git.getRepository().getBranch(); if (branch.equalsIgnoreCase(current)) { PullResult pull = git.pull().setRemote(remote).setCredentialsProvider(credentialProvider) .setTransportConfigCallback(transportConfigCallback).call(); if (!pull.isSuccessful()) { LOGGER.warn("Unable to pull the branch + '" + branch + "' from the remote repository '" + remote + "'"); }//ww w . ja v a 2 s .c om return git; } else { git.checkout().setName(branch).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) .setStartPoint(remote + "/" + branch).call(); return git; } } else { return Git.cloneRepository().setURI(url).setBranch(branch).setRemote(remote).setDirectory(path) .setCredentialsProvider(credentialProvider).setTransportConfigCallback(transportConfigCallback) .call(); } }
From source file:io.vertx.config.git.GitConfigStoreTest.java
License:Apache License
private GitConfigStoreTest add(Git git, File root, File file, String directory) throws IOException, GitAPIException { if (!file.isFile()) { throw new RuntimeException("File not found " + file.getAbsolutePath()); }//from ww w . j a va 2s . c o m if (!"master".equalsIgnoreCase(git.getRepository().getBranch())) { git.checkout().setCreateBranch(true).setName("master").call(); } if (!branch.equalsIgnoreCase(git.getRepository().getBranch())) { boolean create = true; for (Ref ref : git.branchList().call()) { if (ref.getName().equals("refs/heads/" + branch)) { create = false; } } git.checkout().setCreateBranch(create).setName(branch).call(); } String relative; if (directory != null) { relative = directory + File.separator + file.getName(); } else { relative = file.getName(); } File output = new File(root, relative); if (output.exists()) { output.delete(); } if (!output.getParentFile().isDirectory()) { output.getParentFile().mkdirs(); } FileUtils.copyFile(file, output); git.add().addFilepattern(relative).call(); git.commit().setAuthor("clement", "clement@apache.org").setCommitter("clement", "clement@apache.org") .setMessage("Add " + relative).call(); return this; }
From source file:models.PullRequestTest.java
License:Apache License
@Before public void initRepositories() throws Exception { GitRepository.setRepoPrefix(REPO_PREFIX); app = support.Helpers.makeTestApplication(); Helpers.start(app);/* www. ja va2s.c o m*/ Project project = Project.findByOwnerAndProjectName("yobi", "projectYobi"); forkedProject = Project.findByOwnerAndProjectName("yobi", "projectYobi-1"); // 1. projectYobi RepositoryService.createRepository(project); // 2. projectYobi ? { String localRepoPath = LOCAL_REPO_PREFIX + project.name; Git git = Git.cloneRepository().setURI(GitRepository.getGitDirectoryURL(project)) .setDirectory(new File(localRepoPath)).call(); Repository repo = git.getRepository(); baseCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncat\n", "commit 1"); git.push().setRefSpecs(new RefSpec("+refs/heads/master:refs/heads/master")).call(); } // 3. ??? ? ?? GitRepository.cloneLocalRepository(project, forkedProject); // 4. ??? ? ? ? ? { String localRepoPath = LOCAL_REPO_PREFIX + forkedProject.name; Git git = Git.cloneRepository().setURI(GitRepository.getGitDirectoryURL(forkedProject)) .setDirectory(new File(localRepoPath)).call(); git.branchCreate().setName("fix/1").call(); git.checkout().setName("fix/1").call(); Repository repo = git.getRepository(); assertThat(repo.isBare()).describedAs("projectYobi-1 must be non-bare").isFalse(); firstCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncorn\n", "commit 1"); secondCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncake\n", "commit 2"); git.push().setRefSpecs(new RefSpec("+refs/heads/fix/1:refs/heads/fix/1")).call(); } // 5. projectYobi? pullrequest . pullRequest = PullRequest.createNewPullRequest(forkedProject, project, "refs/heads/fix/1", "refs/heads/master"); pullRequest.save(); // 6. attempt merge boolean isConflict = pullRequest.updateMerge().conflicts(); assertThat(isConflict).isFalse(); }
From source file:net.mobid.codetraq.runnables.GitChecker.java
License:Open Source License
private void attachHead(Git g, String branch) { LogService.writeMessage("Trying to attach HEAD to " + g.getRepository().toString()); try {/*from www.ja v a2s . c o m*/ CheckoutCommand temp = g.checkout(); temp.setCreateBranch(true); temp.setName("temp"); Ref tRef = temp.call(); CheckoutCommand b = g.checkout(); b.setName(branch); b.setCreateBranch(true); b.call(); MergeCommand merge = g.merge(); merge.include(tRef); merge.call(); } catch (Exception ex) { LogService.getLogger(GitChecker.class.getName()).log(Level.SEVERE, null, ex); LogService.writeLog(Level.SEVERE, ex); } }
From source file:org.apache.maven.scm.provider.git.jgit.command.checkout.JGitCheckOutCommand.java
License:Apache License
/** * For git, the given repository is a remote one. We have to clone it first if the working directory does not * contain a git repo yet, otherwise we have to git-pull it. * <p/>//from w ww. j ava2 s.c o m * {@inheritDoc} */ protected CheckOutScmResult executeCheckOutCommand(ScmProviderRepository repo, ScmFileSet fileSet, ScmVersion version, boolean recursive) throws ScmException { GitScmProviderRepository repository = (GitScmProviderRepository) repo; if (GitScmProviderRepository.PROTOCOL_FILE.equals(repository.getFetchInfo().getProtocol()) && repository.getFetchInfo().getPath().indexOf(fileSet.getBasedir().getPath()) >= 0) { throw new ScmException("remote repository must not be the working directory"); } Git git = null; try { ProgressMonitor monitor = JGitUtils.getMonitor(getLogger()); String branch = version != null ? version.getName() : null; if (StringUtils.isBlank(branch)) { branch = Constants.MASTER; } getLogger().debug("try checkout of branch: " + branch); if (!fileSet.getBasedir().exists() || !(new File(fileSet.getBasedir(), ".git").exists())) { if (fileSet.getBasedir().exists()) { // git refuses to clone otherwise fileSet.getBasedir().delete(); } // FIXME only if windauze WindowCacheConfig cfg = new WindowCacheConfig(); cfg.setPackedGitMMAP(false); cfg.install(); // no git repo seems to exist, let's clone the original repo CredentialsProvider credentials = JGitUtils.getCredentials((GitScmProviderRepository) repo); getLogger().info("cloning [" + branch + "] to " + fileSet.getBasedir()); CloneCommand command = Git.cloneRepository().setURI(repository.getFetchUrl()); command.setCredentialsProvider(credentials).setBranch(branch).setDirectory(fileSet.getBasedir()); command.setProgressMonitor(monitor); git = command.call(); } JGitRemoteInfoCommand remoteInfoCommand = new JGitRemoteInfoCommand(); remoteInfoCommand.setLogger(getLogger()); RemoteInfoScmResult result = remoteInfoCommand.executeRemoteInfoCommand(repository, fileSet, null); if (git == null) { git = Git.open(fileSet.getBasedir()); } if (fileSet.getBasedir().exists() && new File(fileSet.getBasedir(), ".git").exists() && result.getBranches().size() > 0) { // git repo exists, so we must git-pull the changes CredentialsProvider credentials = JGitUtils.prepareSession(getLogger(), git, repository); if (version != null && StringUtils.isNotEmpty(version.getName()) && (version instanceof ScmTag)) { // A tag will not be pulled but we only fetch all the commits from the upstream repo // This is done because checking out a tag might not happen on the current branch // but create a 'detached HEAD'. // In fact, a tag in git may be in multiple branches. This occurs if // you create a branch after the tag has been created getLogger().debug("fetch..."); git.fetch().setCredentialsProvider(credentials).setProgressMonitor(monitor).call(); } else { getLogger().debug("pull..."); git.pull().setCredentialsProvider(credentials).setProgressMonitor(monitor).call(); } } Set<String> localBranchNames = JGitBranchCommand.getShortLocalBranchNames(git); if (version instanceof ScmTag) { getLogger().info("checkout tag [" + branch + "] at " + fileSet.getBasedir()); git.checkout().setName(branch).call(); } else if (localBranchNames.contains(branch)) { getLogger().info("checkout [" + branch + "] at " + fileSet.getBasedir()); git.checkout().setName(branch).call(); } else { getLogger().info("checkout remote branch [" + branch + "] at " + fileSet.getBasedir()); git.checkout().setName(branch).setCreateBranch(true) .setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + branch).call(); } RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit commit = revWalk.parseCommit(git.getRepository().resolve(Constants.HEAD)); revWalk.release(); final TreeWalk walk = new TreeWalk(git.getRepository()); walk.reset(); // drop the first empty tree, which we do not need here walk.setRecursive(true); walk.addTree(commit.getTree()); List<ScmFile> listedFiles = new ArrayList<ScmFile>(); while (walk.next()) { listedFiles.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT)); } walk.release(); getLogger().debug("current branch: " + git.getRepository().getBranch()); return new CheckOutScmResult("checkout via JGit", listedFiles); } catch (Exception e) { throw new ScmException("JGit checkout failure!", e); } finally { JGitUtils.closeRepo(git); } }