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

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

Introduction

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

Prototype

public static Git open(File dir) throws IOException 

Source Link

Document

Open repository

Usage

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

/**
 * Tests a special use case where the remote repository has been updated with a forced
 * push conflicting with the local repo of the Config Server. The Config Server has to
 * reset hard on the new reference because a simple pull operation could result in a
 * conflicting local repository.//from   w w  w .j a v a2s . com
 */
@Test
public void pullDirtyRepo() throws Exception {
    ConfigServerTestUtils.prepareLocalRepo();
    String uri = ConfigServerTestUtils.copyLocalRepo("config-copy");

    // Create a remote bare repository.
    Repository remote = ConfigServerTestUtils.prepareBareRemote();

    Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile());
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", remote.getDirectory().getAbsolutePath());
    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.save();

    // Pushes the raw branch to remote repository.
    git.push().call();

    String commitToRevertBeforePull = git.log().setMaxCount(1).call().iterator().next().getName();

    this.context = new SpringApplicationBuilder(TestConfiguration.class).web(false)
            .run("--spring.cloud.config.server.git.uri=" + uri);

    JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class);

    // Fetches the repository for the first time.
    SearchPathLocator.Locations locations = repository.getLocations("bar", "test", "raw");
    assertEquals(locations.getVersion(), commitToRevertBeforePull);

    // Resets to the original commit.
    git.reset().setMode(ResetType.HARD).setRef("master").call();

    // Generate a conflicting commit who will be forced on the origin.
    Path applicationFilePath = Paths.get(ResourceUtils.getFile(uri).getAbsoluteFile() + "/application.yml");

    Files.write(applicationFilePath, Arrays.asList("info:", "  foo: bar", "raw: false"), StandardCharsets.UTF_8,
            StandardOpenOption.TRUNCATE_EXISTING);
    git.add().addFilepattern(".").call();
    git.commit().setMessage("Conflicting commit.").call();
    git.push().setForce(true).call();
    String conflictingCommit = git.log().setMaxCount(1).call().iterator().next().getName();

    // Reset to the raw branch.
    git.reset().setMode(ResetType.HARD).setRef(commitToRevertBeforePull).call();

    // Triggers the repository refresh.
    locations = repository.getLocations("bar", "test", "raw");
    assertEquals(locations.getVersion(), conflictingCommit);

    assertTrue("Local repository is not cleaned after retrieving resources.", git.status().call().isClean());
}

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.srcdeps.core.impl.scm.JGitScm.java

License:Apache License

void fetchAndReset(BuildRequest request) throws ScmException {
    final Path dir = request.getProjectRootDirectory();
    /* Forget local changes */
    try (Git git = Git.open(dir.toFile())) {
        Set<String> removedFiles = git.clean().setCleanDirectories(true).call();
        for (String removedFile : removedFiles) {
            log.debug("Srcdeps removed an unstaged file {}", removedFile);
        }/*w  w  w .ja  v  a  2  s . c om*/
        git.reset().setMode(ResetType.HARD).call();

        /* make sure the srcdeps-working-branch exists */
        git.branchCreate().setName(SRCDEPS_WORKING_BRANCH).setForce(true).call();
        git.checkout().setName(SRCDEPS_WORKING_BRANCH).call();

    } catch (Exception e) {
        log.warn(String.format("Srcdeps could not forget local changes in [%s]", dir), e);
    }

    final SrcVersion srcVersion = request.getSrcVersion();
    ScmException lastException = null;
    int i = 0;
    for (String url : request.getScmUrls()) {
        String useUrl = stripUriPrefix(url);
        log.info("Srcdeps attempting to fetch version {} from SCM URL {}", request.getSrcVersion(), useUrl);
        String remoteAlias = i == 0 ? "origin" : "origin" + i;
        try (Git git = Git.open(dir.toFile())) {

            StoredConfig config = git.getRepository().getConfig();
            config.setString("remote", remoteAlias, "url", useUrl);
            config.save();

            final String startPoint;
            final String refToFetch;
            FetchCommand fetch = git.fetch().setRemote(remoteAlias);
            switch (srcVersion.getWellKnownType()) {
            case branch:
                refToFetch = "refs/heads/" + srcVersion.getScmVersion();
                fetch.setRefSpecs(new RefSpec(refToFetch));
                startPoint = remoteAlias + "/" + srcVersion.getScmVersion();
                break;
            case tag:
                refToFetch = "refs/tags/" + srcVersion.getScmVersion();
                fetch.setRefSpecs(new RefSpec(refToFetch));
                startPoint = srcVersion.getScmVersion();
                break;
            case revision:
                refToFetch = null;
                startPoint = srcVersion.getScmVersion();
                break;
            default:
                throw new IllegalStateException("Unexpected " + WellKnownType.class.getName() + " value '"
                        + srcVersion.getWellKnownType() + "'.");
            }
            FetchResult fetchResult = fetch.call();

            /*
             * Let's check that the desired startPoint was really fetched from the current URL. Otherwise, the
             * startPoint may come from an older fetch of the same repo URL (but was removed in between) or it may
             * come from an older fetch of another URL. These cases may introduce situations when one developer can
             * see a successful srcdep build (because he still has the outdated ref in his local git repo) but
             * another dev with exectly the same setup cannot checkout because the ref is not there in any of the
             * remote repos anymore.
             */
            Collection<Ref> advertisedRefs = fetchResult.getAdvertisedRefs();
            switch (srcVersion.getWellKnownType()) {
            case branch:
            case tag:
                assertRefFetched(advertisedRefs, refToFetch, url);
                break;
            case revision:
                assertRevisionFetched(git.getRepository(), advertisedRefs, srcVersion.getScmVersion(), url);
                break;
            default:
                throw new IllegalStateException("Unexpected " + WellKnownType.class.getName() + " value '"
                        + srcVersion.getWellKnownType() + "'.");
            }

            git.reset().setMode(ResetType.HARD).setRef(startPoint).call();
            return;
        } catch (ScmException e) {
            log.warn("Srcdeps could not checkout version {} from SCM URL {}: {}: {}", request.getSrcVersion(),
                    useUrl, e.getClass().getName(), e.getMessage());
            lastException = e;
        } catch (Exception e) {
            log.warn("Srcdeps could not checkout version {} from SCM URL {}: {}: {}", request.getSrcVersion(),
                    useUrl, e.getClass().getName(), e.getMessage());
            lastException = new ScmException(String.format("Could not checkout from URL [%s]", useUrl), e);
        }
        i++;
    }
    throw lastException;
}

From source file:org.srcdeps.core.impl.scm.JGitScmTest.java

License:Apache License

private void assertCommit(Path dir, String expectedSha1) throws IOException, NoHeadException, GitAPIException {
    try (Git git = Git.open(dir.toFile())) {
        Iterable<RevCommit> history = git.log().call();
        String foundSha1 = history.iterator().next().getName();
        Assert.assertEquals(String.format("Git repository in [%s] not at the expected revision", dir),
                expectedSha1, foundSha1);
    }//www .  j a v  a 2  s .c  o m

}

From source file:org.uberfire.java.nio.fs.jgit.JGitMirrorTest.java

License:Apache License

@Test
public void testToHTTPMirrorSuccess() throws IOException, GitAPIException {
    final File parentFolder = createTempDirectory();
    final File directory = new File(parentFolder, TARGET_GIT);
    new Clone(directory, ORIGIN, false, CredentialsProvider.getDefault(), null).execute();

    final Git cloned = Git.open(directory);

    assertThat(cloned).isNotNull();//from  www. j av  a 2 s  .c om

    assertThat(new ListRefs(cloned.getRepository()).execute()).is(new Condition<List<Ref>>() {
        @Override
        public boolean matches(final List<Ref> refs) {
            return refs.size() > 0;
        }
    });

    assertThat(new ListRefs(cloned.getRepository()).execute().get(0).getName()).isEqualTo("refs/heads/master");

    URIish remoteUri = cloned.remoteList().call().get(0).getURIs().get(0);
    String remoteUrl = remoteUri.getScheme() + "://" + remoteUri.getHost() + remoteUri.getPath();
    assertThat(remoteUrl).isEqualTo(ORIGIN);
}

From source file:org.uberfire.java.nio.fs.jgit.JGitMirrorTest.java

License:Apache License

@Test
public void testEmptyCredentials() throws IOException, GitAPIException {
    final File parentFolder = createTempDirectory();
    final File directory = new File(parentFolder, TARGET_GIT);
    new Clone(directory, ORIGIN, false, null, null).execute();

    final Git cloned = Git.open(directory);

    assertThat(cloned).isNotNull();/*  w w  w  .j a  va  2  s .  c om*/

    assertThat(new ListRefs(cloned.getRepository()).execute()).is(new Condition<List<Ref>>() {
        @Override
        public boolean matches(final List<Ref> refs) {
            return refs.size() > 0;
        }
    });

    assertThat(new ListRefs(cloned.getRepository()).execute().get(0).getName()).isEqualTo("refs/heads/master");

    URIish remoteUri = cloned.remoteList().call().get(0).getURIs().get(0);
    String remoteUrl = remoteUri.getScheme() + "://" + remoteUri.getHost() + remoteUri.getPath();
    assertThat(remoteUrl).isEqualTo(ORIGIN);
}

From source file:org.uberfire.provisioning.source.git.CloneTestJUnitTest.java

License:Apache License

@Test
public void hello() throws Exception {
    final String repoName = "drools-workshop-build";
    final Optional<Source> source = new GitConfigExecutor(new InMemorySourceRegistry())
            .apply(new GitConfigImpl(tempPath.getAbsolutePath(), "master", gitUrl, repoName, "true"));
    assertTrue(source.isPresent());/*www  . j  ava 2 s.  c  o  m*/

    final String targetRepoDir = tempPath.getAbsolutePath() + "/" + repoName + ".git";
    Git git = Git.open(new File(targetRepoDir));

    assertNotNull(git.getRepository().exactRef(Constants.HEAD));
}

From source file:org.walkmod.git.constraints.JavaConstraintProvider.java

License:Open Source License

public JavaConstraintProvider() throws IOException {
    File file = new File(".git").getCanonicalFile();
    if (file.exists()) {
        Git git = Git.open(file.getAbsoluteFile().getParentFile().getCanonicalFile());

        formatter = new WalkmodDiffFormatter(git.getRepository());

        AbstractTreeIterator commitTreeIterator = prepareTreeParser(git.getRepository(), Constants.HEAD);
        FileTreeIterator workTreeIterator = new FileTreeIterator(git.getRepository());
        List<DiffEntry> diffEntries = formatter.scan(commitTreeIterator, workTreeIterator);

        for (DiffEntry entry : diffEntries) {
            File aux = new File(entry.getNewPath()).getCanonicalFile();
            this.diffEntries.put(aux.getPath(), entry);
        }/*w w  w .  j  a  v a  2 s .  c o m*/
        formatter.close();
    }
}

From source file:org.walkmod.git.readers.GitFileReader.java

License:Open Source License

@Override
public Resource<File> read() throws Exception {
    File file = new File(".git");
    Resource<File> result = null;
    if (file.exists()) {

        Git git = Git.open(file.getAbsoluteFile().getParentFile().getCanonicalFile());

        try {/*from  www  . jav a2s. com*/
            StatusCommand cmd = git.status();
            List<String> cfgIncludesList = null;
            String[] cfgIncludes = getIncludes();
            if (cfgIncludes != null && cfgIncludes.length > 0) {
                cfgIncludesList = Arrays.asList(cfgIncludes);
            }
            String path = getPath();
            Status status = cmd.call();
            Set<String> uncommitted = status.getUncommittedChanges();
            uncommitted.addAll(status.getUntracked());
            Set<String> includes = new HashSet<String>();
            if (!uncommitted.isEmpty()) {

                for (String uncommittedFile : uncommitted) {
                    if (uncommittedFile.startsWith(path)) {
                        String fileName = uncommittedFile.substring(path.length() + 1);
                        if (cfgIncludesList == null || cfgIncludesList.contains(fileName)) {
                            includes.add(fileName);
                        }
                    }
                }

            } else {

                Set<String> filesInCommit = getFilesInHEAD(git.getRepository());
                for (String committedFile : filesInCommit) {
                    if (committedFile.startsWith(path)) {
                        String fileName = committedFile.substring(path.length() + 1);
                        if (cfgIncludesList == null || cfgIncludesList.contains(fileName)) {
                            includes.add(fileName);
                        }
                    }
                }

            }
            if (!includes.isEmpty()) {
                String[] includesArray = new String[includes.size()];
                includesArray = includes.toArray(includesArray);

                setIncludes(includesArray);
            }
        } finally {
            git.close();
        }
    }
    result = super.read();
    return result;
}