Example usage for org.eclipse.jgit.api Git checkout

List of usage examples for org.eclipse.jgit.api Git checkout

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git checkout.

Prototype

public CheckoutCommand checkout() 

Source Link

Document

Return a command object to execute a checkout command

Usage

From source file:org.archicontribs.modelrepository.grafico.MergeConflictHandler.java

License:Open Source License

private void checkout(Git git, Stage stage, List<String> paths) throws IOException, GitAPIException {
    CheckoutCommand checkoutCommand = git.checkout();
    checkoutCommand.setStage(stage);/*from  w w w  . ja  v  a 2 s .  c  o  m*/
    checkoutCommand.addPaths(paths);
    checkoutCommand.call();
}

From source file:org.cicomponents.git.impl.LatestRevisionGitBranchMonitor.java

License:Mozilla Public License

@SneakyThrows
protected void emitRevisionIfNecessary(RefsChangedEvent event) {
    synchronized (git) {
        ObjectId newHead = event.getRepository().findRef("refs/heads/" + branch).getObjectId();
        if (!newHead.equals(head)) {
            log.info("Detected refs change for {}, branch {}, old: {}, new: {}", git, branch, head, newHead);
            WorkingDirectory workingDirectory = getWorkingDirectory();
            String directory = workingDirectory.getDirectory() + "/git";
            Git clone = Git.cloneRepository()
                    .setURI("file://" + git.getRepository().getDirectory().getAbsolutePath())
                    .setDirectory(new File(directory)).call();
            Ref checkedOutRef = clone.checkout().setName(newHead.getName()).call();
            assert checkedOutRef == newHead;
            GitRevision resource = new LocalGitRevision(clone, newHead, workingDirectory);
            ResourceHolder<GitRevision> holder = new SimpleResourceHolder<>(resource);
            emit(holder);/*from   ww  w . ja v  a2  s.c  o m*/
            head = newHead;
            persistentMap.put(head.getName(), head.getName());
        }
    }
}

From source file:org.cicomponents.github.impl.PullRequestMonitor.java

License:Mozilla Public License

@SneakyThrows
private void emit(GHPullRequest pr) {
    WorkingDirectory directory = environment.getWorkingDirectoryProvider().getDirectory();
    String path = directory.getDirectory() + "/git";
    String name = pr.getHead().getRepository().getFullName();
    log.info("Cloning fork {}#{}", name, pr.getHead().getSha());
    Git git = Git.cloneRepository().setURI("https://github.com/" + name).setDirectory(new File(path)).call();

    git.checkout().setName(pr.getHead().getSha()).call();
    log.info("Emitting fork {}#{}", name, pr.getHead().getSha());

    GithubPullRequest pullRequest = new GithubPullRequestResource(git, pr, directory);
    persistentMap.put(getIssueStatusKey(pr), new Date());
    emit(new SimpleResourceHolder<>(pullRequest));
}

From source file:org.commonwl.view.git.GitService.java

License:Apache License

/**
 * Gets a repository, cloning into a local directory or
 * @param gitDetails The details of the Git repository
 * @param reuseDir Whether the cached repository can be used
 * @return The git object for the repository
 *///from  w  ww  . ja  v a2  s .c  o  m
public Git getRepository(GitDetails gitDetails, boolean reuseDir) throws GitAPIException, IOException {
    Git repo;
    if (reuseDir) {
        // Base dir from configuration, name from hash of repository URL
        String baseName = DigestUtils.sha1Hex(GitDetails.normaliseUrl(gitDetails.getRepoUrl()));

        // Check if folder already exists
        Path repoDir = gitStorage.resolve(baseName);
        if (Files.isReadable(repoDir) && Files.isDirectory(repoDir)) {
            repo = Git.open(repoDir.toFile());
            repo.fetch().call();
        } else {
            // Create a folder and clone repository into it
            Files.createDirectory(repoDir);
            repo = cloneRepo(gitDetails.getRepoUrl(), repoDir.toFile());
        }
    } else {
        // Another thread is already using the existing folder
        // Must create another temporary one
        repo = cloneRepo(gitDetails.getRepoUrl(), createTempDir());
    }

    // Checkout the specific branch or commit ID
    if (repo != null) {
        // Create a new local branch if it does not exist and not a commit ID
        String branchOrCommitId = gitDetails.getBranch();
        final boolean isId = ObjectId.isId(branchOrCommitId);
        if (!isId) {
            branchOrCommitId = "refs/remotes/origin/" + branchOrCommitId;
        }
        try {
            repo.checkout().setName(branchOrCommitId).call();
        } catch (Exception ex) {
            // Maybe it was a tag
            if (!isId && ex instanceof RefNotFoundException) {
                final String tag = gitDetails.getBranch();
                try {
                    repo.checkout().setName(tag).call();
                } catch (Exception ex2) {
                    // Throw the first exception, to keep the same behavior as before.
                    throw ex;
                }
            } else {
                throw ex;
            }
        }
    }

    return repo;
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private void checkoutEnvironment(Repository repository, String site) {
    Git git = null;
    try {/*  w ww  .  j a v a 2s. c o  m*/
        Ref branchRef = repository.findRef(environment);
        git = new Git(repository);
        git.checkout().setCreateBranch(true).setName(environment)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setStartPoint("origin/" + environment).call();
        git.fetch().call();
        git.pull().call();
    } catch (RefNotFoundException e) {
        try {
            git.checkout().setOrphan(true).setName(environment).call();
            ProcessBuilder pb = new ProcessBuilder();
            pb.command("git", "rm", "-rf", ".");
            pb.directory(repository.getDirectory().getParentFile());
            Process p = pb.start();
            p.waitFor();

            git.commit().setMessage("initial content").setAllowEmpty(true).call();
        } catch (GitAPIException | InterruptedException | IOException e1) {
            logger.error("Error checking out environment store branch for site " + site + " environment "
                    + environment, e1);
        }
    } catch (IOException | GitAPIException e) {
        logger.error(
                "Error checking out environment store branch for site " + site + " environment " + environment,
                e);
    }
}

From source file:org.eclipse.egit.core.synchronize.dto.GitSynchronizeDataTest.java

License:Open Source License

@Test
public void shouldReturnSourceMergeForSymbolicRef() throws Exception {
    // given/*  w w w .  jav  a 2s  .  com*/
    Git git = new Git(repo);
    git.branchCreate().setName("test").setStartPoint("refs/heads/master")
            .setUpstreamMode(SetupUpstreamMode.TRACK).call();
    git.checkout().setName("test").call();
    GitSynchronizeData gsd = new GitSynchronizeData(repo, HEAD, HEAD, false);

    // when
    String srcMerge = gsd.getSrcMerge();

    // then
    assertThat(srcMerge, is("refs/heads/master"));
}

From source file:org.eclipse.egit.core.synchronize.dto.GitSynchronizeDataTest.java

License:Open Source License

@Test
public void shouldReturnSourceMergeForLocalRef() throws Exception {
    // given/*from   w w  w .jav a  2  s. co  m*/
    Git git = new Git(repo);
    git.branchCreate().setName("test2").setStartPoint("refs/heads/master")
            .setUpstreamMode(SetupUpstreamMode.TRACK).call();
    git.checkout().setName("test2").call();
    GitSynchronizeData gsd = new GitSynchronizeData(repo, R_HEADS + "test2", HEAD, false);

    // when
    String srcMerge = gsd.getSrcMerge();

    // then
    assertThat(srcMerge, is("refs/heads/master"));
}

From source file:org.eclipse.egit.core.synchronize.dto.GitSynchronizeDataTest.java

License:Open Source License

@Test
public void shouldReturnSourceMergeForRemoteBranch() throws Exception {
    // given/*  w w w  .ja  v a  2  s . c  o  m*/
    Git git = new Git(repo);
    git.branchCreate().setName("test3").setStartPoint("refs/heads/master")
            .setUpstreamMode(SetupUpstreamMode.TRACK).call();
    git.checkout().setName("test3").call();
    repo.renameRef(R_HEADS + "test3", Constants.R_REMOTES + "origin/master").rename();
    GitSynchronizeData gsd = new GitSynchronizeData(repo, "refs/remotes/origin/master", HEAD, false);

    // when
    String srcMerge = gsd.getSrcMerge();

    // then
    assertThat(srcMerge, is("refs/heads/master"));
}

From source file:org.eclipse.egit.core.test.GitProjectSetCapabilityTest.java

License:Open Source License

private File createRepository(IPath location, String url, String branch) throws Exception {
    File gitDirectory = new File(location.toFile(), Constants.DOT_GIT);
    Repository repo = new FileRepository(gitDirectory);
    repo.getConfig().setString(ConfigConstants.CONFIG_REMOTE_SECTION, "origin", ConfigConstants.CONFIG_KEY_URL,
            url);//w w  w .  j ava2  s. c o  m
    repo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_REMOTE,
            "origin");
    repo.create();
    repo.close();

    Git git = new Git(repo);
    git.add().addFilepattern(".").call();
    git.commit().setMessage("initial").call();
    if (!branch.equals("master"))
        git.checkout().setName(branch).setCreateBranch(true).call();

    pathsToClean.add(gitDirectory);
    return gitDirectory;
}

From source file:org.eclipse.egit.ui.internal.actions.SwitchToMenuTest.java

License:Open Source License

@Test
public void selectionWithProj1AndReflog() throws Exception {
    File gitDir = createProjectAndCommitToRepository();

    // create additional reflog entries
    Git git = new Git(lookupRepository(gitDir));
    git.checkout().setName("stable").call();
    git.checkout().setName("master").call();

    selectionWithProj1Common();/*from  www.j ava2 s  .  co m*/

    // delete reflog again to not confuse other tests
    new File(gitDir, Constants.LOGS + "/" + Constants.HEAD).delete();
}