org.eclipse.jgit.api.FetchCommand Java Examples

The following examples show how to use org.eclipse.jgit.api.FetchCommand. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StudioNodeSyncGlobalRepoTask.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private void updateBranch(Git git, ClusterMember remoteNode) throws CryptoException, GitAPIException,
        IOException, ServiceLayerException {
    final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
    FetchCommand fetchCommand = git.fetch().setRemote(remoteNode.getGitRemoteName());
    fetchCommand = configureAuthenticationForCommand(remoteNode, fetchCommand, tempKey);
    FetchResult fetchResult = fetchCommand.call();

    ObjectId commitToMerge;
    Ref r;
    if (fetchResult != null) {
        r = fetchResult.getAdvertisedRef(Constants.MASTER);
        if (r == null) {
            r = fetchResult.getAdvertisedRef(Constants.R_HEADS + Constants.MASTER);
        }
        if (r != null) {
            commitToMerge = r.getObjectId();

            MergeCommand mergeCommand = git.merge();
            mergeCommand.setMessage(studioConfiguration.getProperty(REPO_SYNC_DB_COMMIT_MESSAGE_NO_PROCESSING));
            mergeCommand.setCommit(true);
            mergeCommand.include(remoteNode.getGitRemoteName(), commitToMerge);
            mergeCommand.setStrategy(MergeStrategy.THEIRS);
            mergeCommand.call();
        }
    }

    Files.delete(tempKey);
}
 
Example #2
Source File: GitUtils.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public static void fetch(final Repository repo, final StandardCredentials credential) {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        FetchCommand fetchCommand = git.fetch();

        addCredential(repo, fetchCommand, credential);

        fetchCommand.setRemote("origin")
            .setRemoveDeletedRefs(true)
            .setRefSpecs(new RefSpec("+refs/heads/*:refs/remotes/origin/*"))
            .call();
    } catch (GitAPIException ex) {
        if (ex.getMessage().contains("Auth fail")) {
            throw new ServiceException.UnauthorizedException("Not authorized", ex);
        }
        throw new RuntimeException(ex);
    }
}
 
Example #3
Source File: DifferentFiles.java    From gitflow-incremental-builder with MIT License 6 votes vote down vote up
private void fetch(String branchName) throws GitAPIException {
    logger.info("Fetching branch " + branchName);
    if (!branchName.startsWith(REFS_REMOTES)) {
        throw new IllegalArgumentException("Branch name '" + branchName + "' is not tracking branch name since it does not start " + REFS_REMOTES);
    }
    String remoteName = extractRemoteName(branchName);
    String shortName = extractShortName(remoteName, branchName);
    FetchCommand fetchCommand = git.fetch()
            .setCredentialsProvider(credentialsProvider)
            .setRemote(remoteName)
            .setRefSpecs(new RefSpec(REFS_HEADS + shortName + ":" + branchName));
    if (configuration.useJschAgentProxy) {
        fetchCommand.setTransportConfigCallback(transport -> {
            if (transport instanceof SshTransport) {
                ((SshTransport) transport).setSshSessionFactory(new AgentProxyAwareJschConfigSessionFactory());
            }
        });
    }
    fetchCommand.call();
}
 
Example #4
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSetRemoveBranchesFlagToFetchCommand() throws Exception {
	Git mockGit = mock(Git.class);
	FetchCommand fetchCommand = mock(FetchCommand.class);

	when(mockGit.fetch()).thenReturn(fetchCommand);
	when(fetchCommand.call()).thenReturn(mock(FetchResult.class));

	JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
			this.environment, new JGitEnvironmentProperties());
	envRepository
			.setGitFactory(new MockGitFactory(mockGit, mock(CloneCommand.class)));
	envRepository.setUri("http://somegitserver/somegitrepo");
	envRepository.setDeleteUntrackedBranches(true);

	envRepository.fetch(mockGit, "master");

	verify(fetchCommand, times(1)).setRemoveDeletedRefs(true);
	verify(fetchCommand, times(1)).call();
}
 
Example #5
Source File: JGitOperator.java    From verigreen with Apache License 2.0 6 votes vote down vote up
@Override
public String fetch(String localBranchName, String remoteBranchName) {
    
    RefSpec spec = new RefSpec().setSourceDestination(localBranchName, remoteBranchName);
    FetchCommand command = _git.fetch();
    command.setRefSpecs(spec);
    FetchResult result = null;
    try {
        if(_cp != null)
            command.setCredentialsProvider(_cp);
        result = command.call();
    } catch (Throwable e) {
        throw new RuntimeException(String.format(
                "Failed to fetch from [%s] to [%s]",
                remoteBranchName,
                localBranchName), e);
    }
    
    return result.getMessages();
}
 
Example #6
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSetTransportConfigCallbackOnCloneAndFetch() throws Exception {
	Git mockGit = mock(Git.class);
	FetchCommand fetchCommand = mock(FetchCommand.class);
	when(mockGit.fetch()).thenReturn(fetchCommand);
	when(fetchCommand.call()).thenReturn(mock(FetchResult.class));

	CloneCommand mockCloneCommand = mock(CloneCommand.class);
	when(mockCloneCommand.setURI(anyString())).thenReturn(mockCloneCommand);
	when(mockCloneCommand.setDirectory(any(File.class))).thenReturn(mockCloneCommand);

	TransportConfigCallback configCallback = mock(TransportConfigCallback.class);
	JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
			this.environment, new JGitEnvironmentProperties());
	envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand));
	envRepository.setUri("http://somegitserver/somegitrepo");
	envRepository.setTransportConfigCallback(configCallback);
	envRepository.setCloneOnStart(true);

	envRepository.afterPropertiesSet();
	verify(mockCloneCommand, times(1)).setTransportConfigCallback(configCallback);

	envRepository.fetch(mockGit, "master");
	verify(fetchCommand, times(1)).setTransportConfigCallback(configCallback);
}
 
Example #7
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
private FetchResult fetch(File projectDir) throws GitAPIException {
	Git git = this.gitFactory.open(projectDir);
	FetchCommand command = git.fetch();
	try {
		return command.call();
	}
	catch (GitAPIException e) {
		deleteBaseDirIfExists();
		throw e;
	}
	finally {
		git.close();
	}
}
 
Example #8
Source File: StudioNodeSyncSandboxTask.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
private void updateBranch(Git git, ClusterMember remoteNode) throws CryptoException, GitAPIException,
        IOException, ServiceLayerException {
    final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
    FetchCommand fetchCommand = git.fetch().setRemote(remoteNode.getGitRemoteName());
    fetchCommand = configureAuthenticationForCommand(remoteNode, fetchCommand, tempKey);
    FetchResult fetchResult = fetchCommand.call();

    ObjectId commitToMerge;
    Ref r;
    if (fetchResult != null) {
        r = fetchResult.getAdvertisedRef(REPO_SANDBOX_BRANCH);
        if (r == null) {
            r = fetchResult.getAdvertisedRef(Constants.R_HEADS +
                    studioConfiguration.getProperty(REPO_SANDBOX_BRANCH));
        }
        if (r != null) {
            commitToMerge = r.getObjectId();

            MergeCommand mergeCommand = git.merge();
            mergeCommand.setMessage(studioConfiguration.getProperty(REPO_SYNC_DB_COMMIT_MESSAGE_NO_PROCESSING));
            mergeCommand.setCommit(true);
            mergeCommand.include(remoteNode.getGitRemoteName(), commitToMerge);
            mergeCommand.setStrategy(MergeStrategy.THEIRS);
            MergeResult result = mergeCommand.call();
            if (result.getMergeStatus().isSuccessful()) {
                deploymentService.syncAllContentToPreview(siteId, true);
            }
        }
    }

    Files.delete(tempKey);
}
 
Example #9
Source File: RepositoryManagementServiceInternalImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
private void fetchRemote(String siteId, Git git, RemoteConfig conf)
        throws CryptoException, IOException, ServiceLayerException, GitAPIException {
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration);
    RemoteRepository remoteRepository = getRemoteRepository(siteId, conf.getName());
    if (remoteRepository != null) {
        Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
        FetchCommand fetchCommand = git.fetch().setRemote(conf.getName());
        fetchCommand = helper.setAuthenticationForCommand(fetchCommand,
                remoteRepository.getAuthenticationType(), remoteRepository.getRemoteUsername(),
                remoteRepository.getRemotePassword(), remoteRepository.getRemoteToken(),
                remoteRepository.getRemotePrivateKey(), tempKey, true);
        fetchCommand.call();
    }
}
 
Example #10
Source File: JGitWrapper.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
public void updateChanges(ProgressMonitor monitor) throws Exception {
    Git git = getGit(monitor);

    FetchCommand fetch = git.fetch();
    fetch.setCredentialsProvider(credentialsProvider);
    if (monitor != null)
        fetch.setProgressMonitor(monitor);
    fetch.call();

    SyncState state = getSyncState(git);
    Ref fetchHead = git.getRepository().getRef("FETCH_HEAD");
    switch (state) {
        case Equal:
            // Do nothing
            Log.d("Git", "Local branch is up-to-date");
            break;

        case Ahead:
            Log.d("Git", "Local branch ahead, pushing changes to remote");
            git.push().setCredentialsProvider(credentialsProvider).setRemote(remotePath).call();
            break;

        case Behind:
            Log.d("Git", "Local branch behind, fast forwarding changes");
            MergeResult result = git.merge().include(fetchHead).setFastForward(MergeCommand.FastForwardMode.FF_ONLY).call();
            if (result.getMergeStatus().isSuccessful() == false)
                throw new IllegalStateException("Fast forward failed on behind merge");
            break;

        case Diverged:
            Log.d("Git", "Branches are diverged, merging with strategy " + mergeStrategy.getName());
            MergeResult mergeResult = git.merge().include(fetchHead).setStrategy(mergeStrategy).call();
            if (mergeResult.getMergeStatus().isSuccessful()) {
                git.push().setCredentialsProvider(credentialsProvider).setRemote(remotePath).call();
            } else
                throw new IllegalStateException("Merge failed for diverged branches using strategy " + mergeStrategy.getName());
            break;
    }
}
 
Example #11
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUpdateLastRefresh() 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);
	FetchCommand fetchCommand = mock(FetchCommand.class);
	FetchResult fetchResult = mock(FetchResult.class);

	when(git.status()).thenReturn(statusCommand);
	when(git.getRepository()).thenReturn(repository);
	when(fetchCommand.call()).thenReturn(fetchResult);
	when(git.fetch()).thenReturn(fetchCommand);
	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);

	JGitEnvironmentProperties properties = new JGitEnvironmentProperties();
	properties.setRefreshRate(1000);
	JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment,
			properties);

	repo.setLastRefresh(0);
	repo.fetch(git, "master");

	long timeDiff = System.currentTimeMillis() - repo.getLastRefresh();

	assertThat(timeDiff < 1000L)
			.as("time difference (" + timeDiff + ") was longer than 1 second")
			.isTrue();
}
 
Example #12
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
@Test
public void testRefreshWithoutFetch() throws Exception {
	Git git = mock(Git.class);

	CloneCommand cloneCommand = mock(CloneCommand.class);
	when(cloneCommand.setURI(anyString())).thenReturn(cloneCommand);
	when(cloneCommand.setDirectory(any(File.class))).thenReturn(cloneCommand);
	when(cloneCommand.call()).thenReturn(git);

	MockGitFactory factory = new MockGitFactory(git, cloneCommand);

	StatusCommand statusCommand = mock(StatusCommand.class);
	CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
	Status status = mock(Status.class);
	Repository repository = mock(Repository.class, Mockito.RETURNS_DEEP_STUBS);
	StoredConfig storedConfig = mock(StoredConfig.class);
	Ref ref = mock(Ref.class);
	ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
	FetchCommand fetchCommand = mock(FetchCommand.class);
	FetchResult fetchResult = mock(FetchResult.class);
	Ref branch1Ref = mock(Ref.class);

	when(git.branchList()).thenReturn(listBranchCommand);
	when(git.status()).thenReturn(statusCommand);
	when(git.getRepository()).thenReturn(repository);
	when(git.checkout()).thenReturn(checkoutCommand);
	when(git.fetch()).thenReturn(fetchCommand);
	when(git.merge())
			.thenReturn(mock(MergeCommand.class, Mockito.RETURNS_DEEP_STUBS));
	when(repository.getConfig()).thenReturn(storedConfig);
	when(storedConfig.getString("remote", "origin", "url"))
			.thenReturn("http://example/git");
	when(statusCommand.call()).thenReturn(status);
	when(checkoutCommand.call()).thenReturn(ref);
	when(listBranchCommand.call()).thenReturn(Arrays.asList(branch1Ref));
	when(fetchCommand.call()).thenReturn(fetchResult);
	when(branch1Ref.getName()).thenReturn("origin/master");
	when(status.isClean()).thenReturn(true);

	JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment,
			new JGitEnvironmentProperties());
	repo.setGitFactory(factory);
	repo.setUri("http://somegitserver/somegitrepo");
	repo.setBasedir(this.basedir);

	// Set the refresh rate to 2 seconds and last update before 100ms. There should be
	// no remote repo fetch.
	repo.setLastRefresh(System.currentTimeMillis() - 100);
	repo.setRefreshRate(2);

	repo.refresh("master");

	// Verify no fetch but merge only.
	verify(git, times(0)).fetch();
	verify(git).merge();
}
 
Example #13
Source File: JGitEnvironmentRepositoryConcurrencyTests.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
@Override
public FetchCommand fetch() {
	return new DelayedFetchCommand(getRepository());
}
 
Example #14
Source File: UpdateLocalRepositoryAdapter.java    From coderadar with MIT License 4 votes vote down vote up
private List<Branch> updateInternal(UpdateRepositoryCommand command)
    throws GitAPIException, IOException, UnableToCloneRepositoryException {
  FileRepositoryBuilder builder = new FileRepositoryBuilder();
  Repository repository =
      builder
          .setWorkTree(new File(command.getLocalDir()))
          .setBare()
          .setGitDir(new File(command.getLocalDir()))
          .build();
  Git git = new Git(repository);
  ObjectId oldHead = git.getRepository().resolve(Constants.HEAD);
  if (oldHead == null) {
    git.close();
    deleteAndCloneRepository(command);
    return getAvailableBranchesAdapter.getAvailableBranches(command.getLocalDir());
  }
  StoredConfig config = git.getRepository().getConfig();
  config.setString("remote", "origin", "url", command.getRemoteUrl());
  config.save();
  FetchCommand fetchCommand = git.fetch().setRemoveDeletedRefs(true);
  if (command.getUsername() != null && command.getPassword() != null) {
    fetchCommand.setCredentialsProvider(
        new UsernamePasswordCredentialsProvider(command.getUsername(), command.getPassword()));
  }
  List<Branch> updatedBranches = new ArrayList<>();
  fetchCommand
      .call()
      .getTrackingRefUpdates()
      .forEach(
          trackingRefUpdate -> {
            if (!trackingRefUpdate.getNewObjectId().equals(trackingRefUpdate.getOldObjectId())) {
              String[] branchName = trackingRefUpdate.getLocalName().split("/");
              int length = branchName.length;
              String truncatedName = branchName[length - 1];
              updatedBranches.add(
                  new Branch()
                      .setName(truncatedName)
                      .setCommitHash(trackingRefUpdate.getNewObjectId().getName()));
            }
          });
  git.getRepository().close();
  git.close();
  return updatedBranches;
}
 
Example #15
Source File: Config.java    From github-bucket with ISC License 4 votes vote down vote up
default FetchCommand configure(FetchCommand cmd) {
    return cmd;
}
 
Example #16
Source File: Config.java    From github-bucket with ISC License 4 votes vote down vote up
default FetchCommand configure(FetchCommand cmd) {
    return cmd;
}
 
Example #17
Source File: StudioNodeSyncPublishedTask.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
private void updatePublishedBranch(Git git, ClusterMember remoteNode, String branch) throws CryptoException,
        GitAPIException, IOException, ServiceLayerException {
    logger.debug("Update published environment " + branch + " from " + remoteNode.getLocalAddress() +
            " for site " + siteId);
    final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");

    Repository repo = git.getRepository();
    Ref ref = repo.exactRef(Constants.R_HEADS + branch);
    boolean createBranch = (ref == null);

    logger.debug("Checkout " + branch);
    CheckoutCommand checkoutCommand = git.checkout()
            .setName(branch)
            .setCreateBranch(createBranch);
    if (createBranch) {
        checkoutCommand.setStartPoint(remoteNode.getGitRemoteName() + "/" + branch);
    }
    checkoutCommand.call();

    FetchCommand fetchCommand = git.fetch().setRemote(remoteNode.getGitRemoteName());
    fetchCommand = configureAuthenticationForCommand(remoteNode, fetchCommand, tempKey);
    FetchResult fetchResult = fetchCommand.call();

    ObjectId commitToMerge;
    Ref r;
    if (fetchResult != null) {
        r = fetchResult.getAdvertisedRef(branch);
        if (r == null) {
            r = fetchResult.getAdvertisedRef(Constants.R_HEADS + branch);
        }
        if (r != null) {
            commitToMerge = r.getObjectId();

            MergeCommand mergeCommand = git.merge();
            mergeCommand.setMessage(studioConfiguration.getProperty(REPO_SYNC_DB_COMMIT_MESSAGE_NO_PROCESSING));
            mergeCommand.setCommit(true);
            mergeCommand.include(remoteNode.getGitRemoteName(), commitToMerge);
            mergeCommand.setStrategy(MergeStrategy.THEIRS);
            mergeCommand.call();
        }
    }

    Files.delete(tempKey);
}
 
Example #18
Source File: FetchJob.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private IStatus doFetch(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	Repository db = null;
	try {
		db = getRepository();
		Git git = Git.wrap(db);
		FetchCommand fc = git.fetch();
		fc.setProgressMonitor(gitMonitor);

		RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
		credentials.setUri(remoteConfig.getURIs().get(0));
		if (this.cookie != null) {
			fc.setTransportConfigCallback(new TransportConfigCallback() {
				@Override
				public void configure(Transport t) {
					if (t instanceof TransportHttp && cookie != null) {
						HashMap<String, String> map = new HashMap<String, String>();
						map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
						((TransportHttp) t).setAdditionalHeaders(map);
					}
				}
			});
		}
		fc.setCredentialsProvider(credentials);
		fc.setRemote(remote);
		if (branch != null) {
			// refs/heads/{branch}:refs/remotes/{remote}/{branch}
			String remoteBranch = branch;
			if (branch.startsWith("for/")) {
				remoteBranch = branch.substring(4);
			}

			RefSpec spec = new RefSpec(Constants.R_HEADS + remoteBranch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
			spec = spec.setForceUpdate(force);
			fc.setRefSpecs(spec);
		}
		FetchResult fetchResult = fc.call();
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		GitJobUtils.packRefs(db, gitMonitor);
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		return handleFetchResult(fetchResult);
	} finally {
		if (db != null) {
			db.close();
		}
	}
}
 
Example #19
Source File: GitWithAuth.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@Override
public FetchCommand fetch() {
    return configure(super.fetch()).setProgressMonitor(progressMonitor("fetch"));
}