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.kaazing.bower.dependency.maven.plugin.UnpackBowerDependencyMojo.java

License:Open Source License

public void execute() throws MojoExecutionException {

    if (outputDir.exists()) {
        deleteFully(outputDir);// w  ww .  j  a  va 2s . c  om
    }
    outputDir.mkdirs();

    for (BowerDependency bowerDependency : bowerDependencies) {

        String name = bowerDependency.getName();
        String location = bowerDependency.getLocation();
        String requiredVersion = bowerDependency.getVersion();

        location = parseGitLocation(location);
        log.debug("Git Repo is at " + location);

        Git repo = checkoutGitRepo(new File(outputDir, name), location);

        List<Ref> tagList;
        try {
            tagList = repo.tagList().call();
        } catch (GitAPIException e) {
            throw new MojoExecutionException("Could not tags on repo", e);
        }

        String tag = findMatchingTag(requiredVersion, tagList);

        try {
            repo.checkout().setName(tag).call();
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to switch to tag: " + tag, e);
        }
    }
}

From source file:org.kuali.student.git.model.TestKSCMContribImport.java

License:Educational Community License

private void setupBase()
        throws FileNotFoundException, IOException, PatchFormatException, PatchApplyException, GitAPIException {

    /*//from w ww  . ja va  2 s  .  co m
     * Create the repository and apply the base patch for the source branch.
     * 
     * Also create the Subversion Revision Meta Data.
     */

    ExternalGitUtils.applyPatch("git", repository,
            new BZip2CompressorInputStream(new FileInputStream("src/test/resources/ks-r53642-base.patch.bz2")),
            System.out);

    Git git = new Git(repository);

    DirCache dircache = git.add().addFilepattern(".").call();

    RevCommit result = git.commit().setMessage("create sandbox_ksenroll-8475@53642 base")
            .setCommitter("name", "email").call();

    GitTreeProcessor processor = new GitTreeProcessor(repository);

    GitTreeData tree = processor.extractExistingTreeDataFromCommit(result);

    Assert.assertNotNull(tree.find(repository, "CM"));
    Assert.assertNotNull(tree.find(repository, "aggregate"));

    Ref sandboxBranchRef = git.checkout().setStartPoint("master").setName("sandbox_ksenroll-8475")
            .setCreateBranch(true).call();

    Assert.assertNotNull(sandboxBranchRef);

}

From source file:org.mule.module.git.GitConnector.java

License:Open Source License

/**
 * Checkout a local branch or create a local branch from a remote branch
 *
 * {@sample.xml ../../../doc/mule-module-git.xml.sample git:checkout}
 *
 * or //from w  ww .j av a 2  s  .c  o  m
 *
 * {@sample.xml ../../../doc/mule-module-git.xml.sample git:checkout}
 *
 * @param startPoint If specified creates a new branch pointing to this startPoint
 * @param branch Name of the branch to checkout
 * @param overrideDirectory Name of the directory to use for git repository
 */
@Processor
public void checkout(String branch, @Optional String startPoint, @Optional String overrideDirectory) {
    try {
        Git git = new Git(getGitRepo(overrideDirectory));
        CheckoutCommand checkout = git.checkout();

        checkout.setName(branch);
        if (startPoint != null) {
            checkout.setCreateBranch(true);
            checkout.setStartPoint(startPoint);
        }

        checkout.call();
    } catch (Exception e) {
        throw new RuntimeException("Unable to fetch", e);
    }

}

From source file:org.ocpsoft.redoculous.model.impl.GitRepository.java

License:Open Source License

@Override
public void initRef(String ref) {
    File repoDir = getRepoDir();//from  w ww. j  a v a2s .  co  m

    File refDir = getRefDir(ref);
    File refCacheDir = getCachedRefDir(ref);

    ref = resolveRef(ref);

    if (!refDir.exists()) {
        log.info("Creating ref copy [" + getUrl() + "] [" + ref + "] [" + getKey() + "]");
        refDir.mkdirs();
        refCacheDir.mkdirs();
        Git git = null;
        try {
            git = Git.open(repoDir);
            git.reset().setMode(ResetType.HARD).call();
            git.clean().setCleanDirectories(true).call();
            git.checkout().setName(ref).call();

            log.info("Deleting cache for [" + getUrl() + "] [" + ref + "] [" + getKey() + "]");
            Files.delete(refDir, true);
            Files.delete(refCacheDir, true);
            refCacheDir.mkdirs();
            Files.copyDirectory(repoDir, refDir, new FileFilter() {
                @Override
                public boolean accept(File file) {
                    return !(file.getName().equals(".git") || file.getName().equals(".gitignore"));
                }
            });
        } catch (Exception e) {
            if (git != null) {
                git.getRepository().close();
                git = null;
            }
            Files.delete(refDir, true);
            Files.delete(refCacheDir, true);
            throw new RewriteException(
                    "Could checkout ref [" + ref + "] from repository [" + getUrl() + "] [" + getKey() + "].",
                    e);
        } finally {
            if (git != null) {
                git.getRepository().close();
            }
        }
    }
}

From source file:org.spdx.tools.LicenseListPublisher.java

License:Apache License

/**
 * Publish a license list to the license data git repository
 * @param release license list release name (must be associatd with a tag in the license-list-xml repo)
 * @param gitUserName github username to be used - must have commit access to the license-xml-data repo
 * @param gitPassword github password/*ww  w  .  j  ava 2 s .  c o m*/
 * @throws LicensePublisherException 
 * @throws LicenseGeneratorException 
 */
private static void publishLicenseList(String release, String gitUserName, String gitPassword,
        boolean ignoreWarnings) throws LicensePublisherException, LicenseGeneratorException {
    CredentialsProvider githubCredentials = new UsernamePasswordCredentialsProvider(gitUserName, gitPassword);
    File licenseXmlDir = null;
    File licenseDataDir = null;
    Git licenseXmlGit = null;
    Git licenseDataGit = null;
    try {
        licenseXmlDir = Files.createTempDirectory("LicenseXML").toFile();
        System.out.println("Cloning the license XML repository - this could take a while...");
        licenseXmlGit = Git.cloneRepository().setCredentialsProvider(githubCredentials)
                .setDirectory(licenseXmlDir).setURI(LICENSE_XML_URI).call();
        Ref releaseTag = licenseXmlGit.getRepository().getTags().get(release);
        if (releaseTag == null) {
            throw new LicensePublisherException(
                    "Release " + release + " not found as a tag in the License List XML repository");
        }
        licenseXmlGit.checkout().setName(releaseTag.getName()).call();
        licenseDataDir = Files.createTempDirectory("LicenseData").toFile();
        System.out.println("Cloning the license data repository - this could take a while...");
        licenseDataGit = Git.cloneRepository().setCredentialsProvider(githubCredentials)
                .setDirectory(licenseDataDir).setURI(LICENSE_DATA_URI).call();
        Ref dataReleaseTag = licenseDataGit.getRepository().getTags().get(release);
        boolean dataReleaseTagExists = false;
        if (dataReleaseTag != null) {
            dataReleaseTagExists = true;
            licenseDataGit.checkout().setName(releaseTag.getName()).call();
        }
        cleanLicenseDataDir(licenseDataDir);
        String todayDate = new SimpleDateFormat("dd-MMM-yyyy").format(Calendar.getInstance().getTime());
        List<String> warnings = LicenseRDFAGenerator.generateLicenseData(
                new File(licenseXmlDir.getPath() + File.separator + "src"), licenseDataDir, release, todayDate);
        if (warnings.size() > 0 && !ignoreWarnings) {
            throw new LicensePublisherException(
                    "There are some skipped or invalid license input data.  Publishing aborted.  To ignore, add the --ignore option as the first parameter");
        }
        licenseDataGit.add().addFilepattern(".").call();
        licenseDataGit.commit().setAll(true)
                .setCommitter("SPDX License List Publisher", "spdx-tech@lists.spdx.org")
                .setMessage("License List Publisher for " + gitUserName + ".  License list version " + release)
                .call();
        if (!dataReleaseTagExists) {
            licenseDataGit.tag().setName(release).setMessage("SPDX License List release " + release).call();
        }
        licenseDataGit.push().setCredentialsProvider(githubCredentials).setPushTags().call();
    } catch (IOException e) {
        throw new LicensePublisherException("I/O Error publishing license list", e);
    } catch (InvalidRemoteException e) {
        throw new LicensePublisherException("Invalid remote error trying to access the git repositories", e);
    } catch (TransportException e) {
        throw new LicensePublisherException("Transport error trying to access the git repositories", e);
    } catch (GitAPIException e) {
        throw new LicensePublisherException("GIT API error trying to access the git repositories", e);
    } finally {
        if (licenseXmlGit != null) {
            licenseXmlGit.close();
        }
        if (licenseDataGit != null) {
            licenseDataGit.close();
        }
        if (licenseXmlDir != null) {
            deleteDir(licenseXmlDir);
        }
        if (licenseDataDir != null) {
            deleteDir(licenseDataDir);
        }
    }
}

From source file:org.springframework.cloud.config.server.environment.JGitConfigServerTestData.java

License:Apache License

public static JGitConfigServerTestData prepareClonedGitRepository(Object... sources) throws Exception {
    //setup remote repository
    String remoteUri = ConfigServerTestUtils.prepareLocalRepo();
    File remoteRepoDir = ResourceUtils.getFile(remoteUri);
    Git remoteGit = Git.open(remoteRepoDir.getAbsoluteFile());
    remoteGit.checkout().setName("master").call();

    //setup local repository
    File clonedRepoDir = new File("target/repos/cloned");
    if (clonedRepoDir.exists()) {
        FileSystemUtils.deleteRecursively(clonedRepoDir);
    } else {//  w w w .j a va 2 s  . c  om
        clonedRepoDir.mkdirs();
    }
    Git clonedGit = Git.cloneRepository().setURI("file://" + remoteRepoDir.getAbsolutePath())
            .setDirectory(clonedRepoDir).setBranch("master").setCloneAllBranches(true).call();

    //setup our test spring application pointing to the local repo
    ConfigurableApplicationContext context = new SpringApplicationBuilder(sources).web(false)
            .properties("spring.cloud.config.server.git.uri:" + "file://" + clonedRepoDir.getAbsolutePath())
            .run();
    JGitEnvironmentRepository repository = context.getBean(JGitEnvironmentRepository.class);

    return new JGitConfigServerTestData(new JGitConfigServerTestData.LocalGit(remoteGit, remoteRepoDir),
            new JGitConfigServerTestData.LocalGit(clonedGit, clonedRepoDir), repository, context);
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.java

License:Apache License

private Ref checkout(Git git, String label) throws GitAPIException {
    CheckoutCommand checkout = git.checkout();
    if (shouldTrack(git, label)) {
        trackBranch(git, checkout, label);
    } else {/*from w w w. j ava 2 s .  c  o m*/
        // works for tags and local branches
        checkout.setName(label);
    }
    return checkout.call();
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryIntegrationTests.java

License:Apache License

@Test
public void pull() throws Exception {
    ConfigServerTestUtils.prepareLocalRepo();
    String uri = ConfigServerTestUtils.copyLocalRepo("config-copy");
    this.context = new SpringApplicationBuilder(TestConfiguration.class).web(false)
            .run("--spring.cloud.config.server.git.uri=" + uri);
    EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class);
    repository.findOne("bar", "staging", "master");
    Environment environment = repository.findOne("bar", "staging", "master");
    assertEquals("bar", environment.getPropertySources().get(0).getSource().get("foo"));
    Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile());
    git.checkout().setName("master").call();
    StreamUtils.copy("foo: foo", Charset.defaultCharset(),
            new FileOutputStream(ResourceUtils.getFile(uri + "/bar.properties")));
    git.add().addFilepattern("bar.properties").call();
    git.commit().setMessage("Updated for pull").call();
    environment = repository.findOne("bar", "staging", "master");
    assertEquals("foo", environment.getPropertySources().get(0).getSource().get("foo"));
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryIntegrationTests.java

License:Apache License

@Test
public void findOne_FileAddedToRepo_FindOneSuccess() throws Exception {
    ConfigServerTestUtils.prepareLocalRepo();
    String uri = ConfigServerTestUtils.copyLocalRepo("config-copy");
    this.context = new SpringApplicationBuilder(TestConfiguration.class).web(false).run(
            "--spring.cloud.config.server.git.uri=" + uri,
            "--spring.cloud.config.server.git.cloneOnStart=true");
    EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class);
    repository.findOne("bar", "staging", "master");
    Environment environment = repository.findOne("bar", "staging", "master");
    assertEquals("bar", environment.getPropertySources().get(0).getSource().get("foo"));
    Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile());
    git.checkout().setName("master").call();
    StreamUtils.copy("foo: foo", Charset.defaultCharset(),
            new FileOutputStream(ResourceUtils.getFile(uri + "/bar.properties")));
    git.add().addFilepattern("bar.properties").call();
    git.commit().setMessage("Updated for pull").call();
    environment = repository.findOne("bar", "staging", "master");
    assertEquals("foo", environment.getPropertySources().get(0).getSource().get("foo"));
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryIntegrationTests.java

License:Apache License

@Test
public void testNewRemoteTag() throws Exception {
    JGitConfigServerTestData testData = JGitConfigServerTestData
            .prepareClonedGitRepository(TestConfiguration.class);

    Git serverGit = testData.getServerGit().getGit();

    Environment environment = testData.getRepository().findOne("bar", "staging", "master");
    Object fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo");
    assertEquals(fooProperty, "bar");

    serverGit.checkout().setName("master").call();

    //create a new tag
    serverGit.tag().setName("testTag").setMessage("Testing a tag").call();

    //update the remote repo
    FileOutputStream out = new FileOutputStream(
            new File(testData.getServerGit().getGitWorkingDirectory(), "/bar.properties"));
    StreamUtils.copy("foo: testAfterTag", Charset.defaultCharset(), out);
    testData.getServerGit().getGit().add().addFilepattern("bar.properties").call();
    testData.getServerGit().getGit().commit().setMessage("Updated for branch test").call();

    environment = testData.getRepository().findOne("bar", "staging", "master");
    fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo");
    assertEquals(fooProperty, "testAfterTag");

    environment = testData.getRepository().findOne("bar", "staging", "testTag");
    fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo");
    assertEquals(fooProperty, "bar");

    //now move the tag and test again
    serverGit.tag().setName("testTag").setForceUpdate(true).setMessage("Testing a moved tag").call();

    environment = testData.getRepository().findOne("bar", "staging", "testTag");
    fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo");
    assertEquals(fooProperty, "testAfterTag");

}