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

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

Introduction

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

Prototype

public Repository getRepository() 

Source Link

Document

Get repository

Usage

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

License:Apache License

private FetchResult fetch(Git git, String label) {
    FetchCommand fetch = git.fetch();/*  w  w  w  . ja  v  a  2  s  . c  o  m*/
    fetch.setRemote("origin");
    fetch.setTagOpt(TagOpt.FETCH_TAGS);

    setTimeout(fetch);
    try {
        setCredentialsProvider(fetch);
        FetchResult result = fetch.call();
        if (result.getTrackingRefUpdates() != null && result.getTrackingRefUpdates().size() > 0) {
            logger.info("Fetched for remote " + label + " and found " + result.getTrackingRefUpdates().size()
                    + " updates");
        }
        return result;
    } catch (Exception ex) {
        String message = "Could not fetch remote for " + label + " remote: "
                + git.getRepository().getConfig().getString("remote", "origin", "url");
        warn(message, ex);
        return null;
    }
}

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

License:Apache License

private MergeResult merge(Git git, String label) {
    try {//from  w  w w.jav a2 s  .  co  m
        MergeCommand merge = git.merge();
        merge.include(git.getRepository().getRef("origin/" + label));
        MergeResult result = merge.call();
        if (!result.getMergeStatus().isSuccessful()) {
            this.logger.warn("Merged from remote " + label + " with result " + result.getMergeStatus());
        }
        return result;
    } catch (Exception ex) {
        String message = "Could not merge remote for " + label + " remote: "
                + git.getRepository().getConfig().getString("remote", "origin", "url");
        warn(message, ex);
        return null;
    }
}

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

License:Apache License

private Ref resetHard(Git git, String label, String ref) {
    ResetCommand reset = git.reset();/*from  ww  w .  java  2s. c o  m*/
    reset.setRef(ref);
    reset.setMode(ResetType.HARD);
    try {
        Ref resetRef = reset.call();
        if (resetRef != null) {
            this.logger.info("Reset label " + label + " to version " + resetRef.getObjectId());
        }
        return resetRef;
    } catch (Exception ex) {
        String message = "Could not reset to remote for " + label + " (current ref=" + ref + "), remote: "
                + git.getRepository().getConfig().getString("remote", "origin", "url");
        warn(message, ex);
        return null;
    }
}

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  www .  j a v  a 2s  .co m*/
 */
@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.JGitEnvironmentRepositoryTests.java

License:Apache License

@Test
public void shouldPullForcepullNotClean() throws Exception {
    Git git = mock(Git.class);
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    Repository repository = mock(Repository.class);
    StoredConfig storedConfig = mock(StoredConfig.class);

    when(git.status()).thenReturn(statusCommand);
    when(git.getRepository()).thenReturn(repository);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(false);

    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);
    repo.setForcePull(true);//  w  w  w. j  a va 2s. c om

    boolean shouldPull = repo.shouldPull(git);

    assertThat("shouldPull was false", shouldPull, is(true));
}

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

License:Apache License

@Test
public void shouldPullNotClean() throws Exception {
    Git git = mock(Git.class);
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    Repository repository = mock(Repository.class);
    StoredConfig storedConfig = mock(StoredConfig.class);

    when(git.status()).thenReturn(statusCommand);
    when(git.getRepository()).thenReturn(repository);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(false);

    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);

    boolean shouldPull = repo.shouldPull(git);

    assertThat("shouldPull was true", shouldPull, is(false));
}

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

License:Apache License

@Test
public void shouldPullClean() throws Exception {
    Git git = mock(Git.class);
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    Repository repository = mock(Repository.class);
    StoredConfig storedConfig = mock(StoredConfig.class);

    when(git.status()).thenReturn(statusCommand);
    when(git.getRepository()).thenReturn(repository);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true);

    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);

    boolean shouldPull = repo.shouldPull(git);

    assertThat("shouldPull was false", shouldPull, is(true));
}

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

License:Apache License

@Test
public void testFetchException() throws Exception {

    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);
    this.repository.setGitFactory(factory);

    //refresh()->shouldPull
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    when(git.status()).thenReturn(statusCommand);
    Repository repository = mock(Repository.class);
    when(git.getRepository()).thenReturn(repository);
    StoredConfig storedConfig = mock(StoredConfig.class);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true);

    //refresh()->fetch
    FetchCommand fetchCommand = mock(FetchCommand.class);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenThrow(new InvalidRemoteException("invalid mock remote")); //here is our exception we are testing

    //refresh()->checkout
    CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
    //refresh()->checkout->containsBranch
    ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
    when(git.checkout()).thenReturn(checkoutCommand);
    when(git.branchList()).thenReturn(listBranchCommand);
    List<Ref> refs = new ArrayList<>();
    Ref ref = mock(Ref.class);
    refs.add(ref);/*from   ww w.  j  a  v  a 2  s . c  o  m*/
    when(ref.getName()).thenReturn("/master");
    when(listBranchCommand.call()).thenReturn(refs);

    //refresh()->merge
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    when(mergeCommand.call()).thenThrow(new NotMergedException()); //here is our exception we are testing

    //refresh()->return git.getRepository().getRef("HEAD").getObjectId().getName();
    Ref headRef = mock(Ref.class);
    when(repository.getRef(anyString())).thenReturn(headRef);

    ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 });
    when(headRef.getObjectId()).thenReturn(newObjectId);

    SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", null);
    assertEquals(locations.getVersion(), newObjectId.getName());
}

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

License:Apache License

@Test
public void testMergeException() throws Exception {

    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);
    this.repository.setGitFactory(factory);

    //refresh()->shouldPull
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    when(git.status()).thenReturn(statusCommand);
    Repository repository = mock(Repository.class);
    when(git.getRepository()).thenReturn(repository);
    StoredConfig storedConfig = mock(StoredConfig.class);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true);

    //refresh()->fetch
    FetchCommand fetchCommand = mock(FetchCommand.class);
    FetchResult fetchResult = mock(FetchResult.class);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenReturn(fetchResult);
    when(fetchResult.getTrackingRefUpdates()).thenReturn(Collections.EMPTY_LIST);

    //refresh()->checkout
    CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
    //refresh()->checkout->containsBranch
    ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
    when(git.checkout()).thenReturn(checkoutCommand);
    when(git.branchList()).thenReturn(listBranchCommand);
    List<Ref> refs = new ArrayList<>();
    Ref ref = mock(Ref.class);
    refs.add(ref);//  w w w .j av  a2  s  .  c  om
    when(ref.getName()).thenReturn("/master");
    when(listBranchCommand.call()).thenReturn(refs);

    //refresh()->merge
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    when(mergeCommand.call()).thenThrow(new NotMergedException()); //here is our exception we are testing

    //refresh()->return git.getRepository().getRef("HEAD").getObjectId().getName();
    Ref headRef = mock(Ref.class);
    when(repository.getRef(anyString())).thenReturn(headRef);

    ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 });
    when(headRef.getObjectId()).thenReturn(newObjectId);

    SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master");
    assertEquals(locations.getVersion(), newObjectId.getName());
}

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

License:Apache License

@Test
public void testResetHardException() throws Exception {

    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);
    this.repository.setGitFactory(factory);

    //refresh()->shouldPull
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    when(git.status()).thenReturn(statusCommand);
    Repository repository = mock(Repository.class);
    when(git.getRepository()).thenReturn(repository);
    StoredConfig storedConfig = mock(StoredConfig.class);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true).thenReturn(false);

    //refresh()->fetch
    FetchCommand fetchCommand = mock(FetchCommand.class);
    FetchResult fetchResult = mock(FetchResult.class);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenReturn(fetchResult);
    when(fetchResult.getTrackingRefUpdates()).thenReturn(Collections.EMPTY_LIST);

    //refresh()->checkout
    CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
    //refresh()->checkout->containsBranch
    ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
    when(git.checkout()).thenReturn(checkoutCommand);
    when(git.branchList()).thenReturn(listBranchCommand);
    List<Ref> refs = new ArrayList<>();
    Ref ref = mock(Ref.class);
    refs.add(ref);/*from   w ww  .  j a  v a 2s .co m*/
    when(ref.getName()).thenReturn("/master");
    when(listBranchCommand.call()).thenReturn(refs);

    //refresh()->merge
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    when(mergeCommand.call()).thenThrow(new NotMergedException()); //here is our exception we are testing

    //refresh()->hardReset
    ResetCommand resetCommand = mock(ResetCommand.class);
    when(git.reset()).thenReturn(resetCommand);
    when(resetCommand.call()).thenReturn(ref);

    //refresh()->return git.getRepository().getRef("HEAD").getObjectId().getName();
    Ref headRef = mock(Ref.class);
    when(repository.getRef(anyString())).thenReturn(headRef);

    ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 });
    when(headRef.getObjectId()).thenReturn(newObjectId);

    SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master");
    assertEquals(locations.getVersion(), newObjectId.getName());
}