Java Code Examples for org.eclipse.jgit.api.FetchCommand#call()

The following examples show how to use org.eclipse.jgit.api.FetchCommand#call() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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);
}