org.eclipse.jgit.api.CheckoutCommand Java Examples

The following examples show how to use org.eclipse.jgit.api.CheckoutCommand. 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: GitMergeUtil.java    From MergeProcessor with Apache License 2.0 6 votes vote down vote up
/**
 * {@code git checkout}
 */
private void checkout() {
	final String localBranch = getLocalTargetBranch();
	if (localBranch == null) {
		return;
	}
	try {
		final List<Ref> branchListResult = repo.branchList().call();
		final boolean localBranchExists = branchListResult.stream()
				.anyMatch(ref -> ref.getName().endsWith(localBranch));
		CheckoutCommand branchCmd = repo.checkout().setName(localBranch);
		if (!localBranchExists) {
			branchCmd = branchCmd.setCreateBranch(true).setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
					.setStartPoint(mergeUnit.getBranchTarget());
		}
		branchCmd.call();
	} catch (GitAPIException e) {
		exception = new MergeUnitException(String.format("Could not checkout branch '%s'", localBranch), e); //$NON-NLS-1$
	}
}
 
Example #2
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
private Ref checkoutBranch(File projectDir, String branch) throws GitAPIException {
	Git git = this.gitFactory.open(projectDir);
	CheckoutCommand command = git.checkout().setName(branch);
	try {
		if (shouldTrack(git, branch)) {
			trackBranch(command, branch);
		}
		return command.call();
	}
	catch (GitAPIException e) {
		deleteBaseDirIfExists();
		throw e;
	}
	finally {
		git.close();
	}
}
 
Example #3
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
protected void checkoutBranch(Git git, GitContext context) throws GitAPIException {
    String current = currentBranch(git);
    if (Objects.equals(current, branch)) {
        return;
    }
    System.out.println("Checking out branch: " + branch);
    // lets check if the branch exists
    CheckoutCommand command = git.checkout().setName(branch);
    boolean exists = localBranchExists(git, branch);
    if (!exists) {
        command = command.setCreateBranch(true).setForce(true).
                setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).
                setStartPoint(getRemote() + "/" + branch);
    }
    Ref ref = command.call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Checked out branch " + branch + " with results " + ref.getName());
    }
    configureBranch(git, branch);
}
 
Example #4
Source File: GitRepo.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private Ref checkoutBranch(File projectDir, String branch) throws GitAPIException {
	Git git = this.gitFactory.open(projectDir);
	CheckoutCommand command = git.checkout().setName(branch);
	try {
		if (shouldTrack(git, branch)) {
			trackBranch(command, branch);
		}
		return command.call();
	}
	catch (GitAPIException e) {
		deleteBaseDirIfExists();
		throw e;
	}
	finally {
		git.close();
	}
}
 
Example #5
Source File: GitConfigurationSource.java    From cfg4j with Apache License 2.0 6 votes vote down vote up
private void checkoutToBranch(String branch) throws GitAPIException {
  CheckoutCommand checkoutCommand = clonedRepo.checkout()
      .setCreateBranch(false)
      .setName(branch);

  List<Ref> refList = clonedRepo.branchList().call();
  if (!anyRefMatches(refList, branch)) {
    checkoutCommand = checkoutCommand
        .setCreateBranch(true)
        .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
        .setStartPoint("origin/" + branch);
  }

  checkoutCommand
      .call();
}
 
Example #6
Source File: JGitOperator.java    From verigreen with Apache License 2.0 6 votes vote down vote up
@Override
public String checkout(
        String branchName,
        boolean useBranchNameAsStartPoint,
        boolean createBranch,
        boolean useForce) {
    
    CheckoutCommand command = _git.checkout();
    command.setCreateBranch(createBranch);
    command.setForce(useForce);
    command.setName(branchName);
    if (useBranchNameAsStartPoint) {
        command.setStartPoint(REFS_REMOTES + branchName);
    }
    Ref ref = null;
    try {
        ref = command.call();
    } catch (Throwable e) {
        throw new RuntimeException(
                String.format("Failed to checkout branch [%s]", branchName),
                e);
    }
    
    return ref.getName();
}
 
Example #7
Source File: ResourcePackRepository.java    From I18nUpdateMod with MIT License 5 votes vote down vote up
public void sparseCheckout(Collection<String> subPathSet, ProgressMonitor monitor) {
    try {
        // sparse checkout
        CheckoutCommand checkoutCommand = gitRepo.checkout();

        checkoutCommand.setProgressMonitor(monitor)
                .setName(branch)
                .setStartPoint(branch);

        subPathSet.forEach(checkoutCommand::addPath);
        checkoutCommand.call();
    } catch (Exception e) {
        logger.error("Exception caught while checking out: ", e);
    }
}
 
Example #8
Source File: GitMergeUtil.java    From MergeProcessor with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate the commit message for the merge unit.
 */
private void evaluteCommitMessage() {
	final String localBranch = getLocalSourceBranch();
	if (localBranch == null) {
		return;
	}
	try {
		final List<Ref> branchListResult = repo.branchList().call();
		final boolean localBranchExists = branchListResult.stream()
				.anyMatch(ref -> ref.getName().endsWith(localBranch));
		CheckoutCommand branchCmd = repo.checkout().setName(localBranch);
		if (!localBranchExists) {
			branchCmd = branchCmd.setCreateBranch(true).setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
					.setStartPoint(mergeUnit.getBranchSource());
		}
		branchCmd.call();

		final ObjectId id = ObjectId.fromString(mergeUnit.getRevisionInfo());
		commitMessage = repo.log().add(id).call().iterator().next().getFullMessage();
		/*
		 * Remove merge processor commit information, if the commmit is done by merge
		 * processor e.g. MP [29c64cf540d8f3ea116c3683eade862c3d996dfb] V1.1 -> master:
		 * (2018-03-06 12:17:22)
		 */
		commitMessage = commitMessage.replaceAll("MP \\[[A-Za-z0-9]*\\] .* -> .*: \\(.*\\) ", ""); //$NON-NLS-1$ //$NON-NLS-2$
	} catch (GitAPIException | MissingObjectException | IncorrectObjectTypeException e) {
		exception = new MergeUnitException(String.format("Could not checkout branch '%s'", localBranch), e); //$NON-NLS-1$
	}
}
 
Example #9
Source File: GitRepository.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void checkoutToSelectedBranch(final Git git) throws IOException, GitAPIException {
    boolean createBranch = !ObjectId.isId(branch);
    if (createBranch) {
        Ref ref = git.getRepository().exactRef(R_HEADS + branch);
        if (ref != null) {
            createBranch = false;
        }
    }
    CheckoutCommand checkout = git.checkout().setCreateBranch(createBranch).setName(branch);
    checkout.call();
    if (checkout.getResult().getStatus() == CheckoutResult.Status.ERROR) {
        throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, defaultRemoteRepository);
    }
}
 
Example #10
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 #11
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 #12
Source File: JGitEnvironmentRepositoryIntegrationTests.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
private String getCommitID(Git git, String label) throws GitAPIException {
	CheckoutCommand checkout = git.checkout();
	checkout.setName(label);
	Ref localRef = checkout.call();
	return localRef.getObjectId().getName();
}
 
Example #13
Source File: JGitEnvironmentRepositoryConcurrencyTests.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
@Override
public CheckoutCommand checkout() {
	return new DelayedCheckoutCommand(getRepository());
}
 
Example #14
Source File: JGitEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
private void trackBranch(Git git, CheckoutCommand checkout, String label) {
	checkout.setCreateBranch(true).setName(label)
			.setUpstreamMode(SetupUpstreamMode.TRACK)
			.setStartPoint("origin/" + label);
}
 
Example #15
Source File: GitOperations.java    From spring-data-dev-tools with Apache License 2.0 4 votes vote down vote up
/**
 * Checks out all projects of the given {@link Train}.
 *
 * @param train
 */
public void checkout(Train train) {

	Assert.notNull(train, "Train must not be null!");

	update(train);

	AtomicBoolean masterSwitch = new AtomicBoolean();
	ExecutionUtils.run(executor, train, module -> {

		Project project = module.getProject();

		doWithGit(project, git -> {

			ModuleIteration gaIteration = train.getModuleIteration(project, Iteration.GA);
			Optional<Tag> gaTag = findTagFor(project, ArtifactVersion.of(gaIteration));

			if (!gaTag.isPresent()) {
				logger.log(project, "Checking out master branch as no GA release tag could be found!");
			}

			Branch branch = gaTag.isPresent() ? Branch.from(module) : Branch.MASTER;

			CheckoutCommand command = git.checkout().setName(branch.toString());

			if (!branchExists(project, branch)) {

				logger.log(project, "git checkout -b %s --track origin/%s", branch, branch);
				command.setCreateBranch(true)//
						.setStartPoint("origin/".concat(branch.toString()))//
						.call();
			} else {

				logger.log(project, "git checkout %s", branch);
				command.call();
			}

			reset(project, branch);
		});
	});

	if (masterSwitch.get()) {
		logger.warn(train,
				"Successfully checked out projects. There were switches to master for certain projects. This happens if the train has no branches yet.");
	} else {
		logger.log(train, "Successfully checked out projects.");
	}

}
 
Example #16
Source File: GitRepo.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
private void trackBranch(CheckoutCommand checkout, String label) {
	checkout.setCreateBranch(true).setName(label)
			.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
			.setStartPoint("origin/" + label);
}
 
Example #17
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 4 votes vote down vote up
private void trackBranch(CheckoutCommand checkout, String label) {
	checkout.setCreateBranch(true).setName(label)
			.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
			.setStartPoint("origin/" + label);
}
 
Example #18
Source File: GitRepository.java    From Getaviz with Apache License 2.0 4 votes vote down vote up
public void reset() throws Exception {
	CheckoutCommand checkout = git.checkout();
	checkout.setName(getDefaultBranch().getName());
	checkout.setCreateBranch(false);
	checkout.call();
}