org.eclipse.jgit.api.CreateBranchCommand Java Examples

The following examples show how to use org.eclipse.jgit.api.CreateBranchCommand. 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: GitService.java    From Refactoring-Bot with MIT License 6 votes vote down vote up
/**
 * This method creates a new branch.
 * 
 * @param gitConfig
 * @param branchName
 * @param origin
 * @throws BotRefactoringException
 * @throws GitWorkflowException
 */
public void createBranch(GitConfiguration gitConfig, String branchName, String newBranch, String origin)
		throws BotRefactoringException, GitWorkflowException {
	try (Git git = Git.open(new File(botConfig.getBotRefactoringDirectory() + gitConfig.getConfigurationId()))) {
		// Try to create new branch
		@SuppressWarnings("unused")
		Ref ref = git.checkout().setCreateBranch(true).setName(newBranch)
				.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
				.setStartPoint(origin + "/" + branchName).call();
		// Pull data
		git.pull();
		// If branch already exists
	} catch (RefAlreadyExistsException r) {
		logger.error(r.getMessage(), r);
		throw new BotRefactoringException(
				"Issue was already refactored in the past! The bot database might have been resetted but not the fork itself.");
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
		throw new GitWorkflowException("Branch with the name " + "'" + newBranch + "' could not be created!");
	}
}
 
Example #2
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 #3
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 #4
Source File: JGitOperator.java    From verigreen with Apache License 2.0 6 votes vote down vote up
@Override
public String createBranch(String commitId, String branchName) {
    
    Ref result = null;
    CreateBranchCommand branchCreate = _git.branchCreate();
    branchCreate.setName(branchName);
    branchCreate.setStartPoint(commitId);
    try {
        result = branchCreate.call();
    } catch (Throwable e) {
        throw new RuntimeException(String.format(
                "Failed creating branch: %s for commit [%s]",
                branchName,
                commitId), e);
    }
    
    return result.getName();
}
 
Example #5
Source File: SMAGitTest.java    From salesforce-migration-assistant with MIT License 6 votes vote down vote up
/**
 * Test the ghprb constructor.
 *
 * @throws Exception
 */
@Test
public void testPullRequest() throws Exception
{
    Map<String, byte[]> expectedContents = new HashMap<String, byte[]>();
    expectedContents.put("src/pages/modifyThis.page", contents.getBytes());
    expectedContents.put("src/pages/modifyThis.page-meta.xml", contents.getBytes());
    expectedContents.put("src/triggers/addThis.trigger", contents.getBytes());
    expectedContents.put("src/triggers/addThis.trigger-meta.xml", contents.getBytes());

    String oldBranch = "refs/remotes/origin/oldBranch";
    CreateBranchCommand cbc = new Git(repository).branchCreate();
    cbc.setName(oldBranch);
    cbc.setStartPoint(oldSha);
    cbc.call();

    git = new SMAGit(gitDir, newSha, "oldBranch", SMAGit.Mode.PRB);

    Map<String, byte[]> allMetadata = git.getAllMetadata();

    assertEquals(expectedContents.size(), allMetadata.size());
}
 
Example #6
Source File: GitProctorCore.java    From proctor with Apache License 2.0 6 votes vote down vote up
public void checkoutBranch(final String branchName) {
    Preconditions.checkArgument(
            StringUtils.isEmpty(this.branchName) || this.branchName.equals(branchName),
            "Unable to checkout branch %s because this repository cloned only the branch %s",
            branchName,
            this.branchName
    );

    workspaceProvider.synchronizedOperation(new Callable<Void>() {
        @Override
        public Void call() {
            try {
                git.branchCreate()
                        .setName(branchName)
                        .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM)
                        .setStartPoint("origin/" + branchName)
                        .setForce(true)
                        .call();
                git.checkout().setName(branchName).call();
            } catch (final GitAPIException e) {
                LOGGER.error("Unable to create/checkout branch " + branchName, e);
            }
            return null;
        }
    });
}
 
Example #7
Source File: GitUtil.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 拉取对应分支最新代码
 *
 * @param url                 远程url
 * @param file                仓库路径
 * @param branchName          分支名
 * @param credentialsProvider 凭证
 * @throws IOException     IO
 * @throws GitAPIException api
 */
public static void checkoutPull(String url, File file, String branchName, CredentialsProvider credentialsProvider) throws IOException, GitAPIException {
    try (Git git = initGit(url, file, credentialsProvider)) {
        // 判断本地是否存在对应分支
        List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
        boolean createBranch = true;
        for (Ref ref : list) {
            String name = ref.getName();
            if (name.startsWith(Constants.R_HEADS + branchName)) {
                createBranch = false;
                break;
            }
        }
        // 切换分支
        if (!StrUtil.equals(git.getRepository().getBranch(), branchName)) {
            git.checkout().
                    setCreateBranch(createBranch).
                    setName(branchName).
                    setForceRefUpdate(true).
                    setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM).
                    call();
        }
        git.pull().setCredentialsProvider(credentialsProvider).call();
    } catch (TransportException t) {
        checkTransportException(t);
        throw t;
    }
}
 
Example #8
Source File: Project.java    From onedev with MIT License 5 votes vote down vote up
public void createBranch(String branchName, String branchRevision) {
try {
	CreateBranchCommand command = git().branchCreate();
	command.setName(branchName);
	RevCommit commit = getRevCommit(branchRevision, true);
	command.setStartPoint(getRevCommit(branchRevision, true));
	command.call();
	String refName = GitUtils.branch2ref(branchName); 
	cacheObjectId(refName, commit);
	
   	ObjectId commitId = commit.copy();
   	OneDev.getInstance(TransactionManager.class).runAfterCommit(new Runnable() {

		@Override
		public void run() {
	    	OneDev.getInstance(SessionManager.class).runAsync(new Runnable() {

				@Override
				public void run() {
					Project project = OneDev.getInstance(ProjectManager.class).load(getId());
					OneDev.getInstance(ListenerRegistry.class).post(
							new RefUpdated(project, refName, ObjectId.zeroId(), commitId));
				}
	    		
	    	});
		}
   		
   	});			
} catch (GitAPIException e) {
	throw new RuntimeException(e);
}
  }
 
Example #9
Source File: GitConfigStore.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
private Git initializeGit() throws IOException, GitAPIException {
  if (path.isDirectory()) {
    Git git = Git.open(path);
    String current = git.getRepository().getBranch();
    if (branch.equalsIgnoreCase(current)) {
      PullResult pull = git.pull().setRemote(remote).setCredentialsProvider(credentialProvider)
        .setTransportConfigCallback(transportConfigCallback).call();
      if (!pull.isSuccessful()) {
        LOGGER.warn("Unable to pull the branch + '" + branch +
          "' from the remote repository '" + remote + "'");
      }
      return git;
    } else {
      git.checkout()
        .setName(branch)
        .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
        .setStartPoint(remote + "/" + branch)
        .call();
      return git;
    }
  } else {
    return Git.cloneRepository()
      .setURI(url)
      .setBranch(branch)
      .setRemote(remote)
      .setDirectory(path)
      .setCredentialsProvider(credentialProvider)
      .setTransportConfigCallback(transportConfigCallback)
      .call();
  }
}
 
Example #10
Source File: GitWorkflowRepository.java    From copper-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the used local repository, either with gut-pull or with git-checkout force with git pull.
 *
 * @throws IOException     in case of git open exception
 * @throws GitAPIException in case of exception in git calls
 */
protected synchronized void updateLocalGitRepositories() throws IOException, GitAPIException {
    logger.debug("Update git repositories.");
    if (!getGitRepositoryDir().exists()) {
        logger.info("No local repository found. Clone a new one. Branch is {}.", branch);
        try (Git git = Git.cloneRepository()
                .setURI(originUri)
                .setDirectory(getGitRepositoryDir())
                .setRemote(ORIGIN)
                .setCredentialsProvider(credentialsProvider)
                .call();) {
            git.checkout().setName("remotes/" + ORIGIN + "/" + branch).call();
        }
    } else {
        try (Git git = Git.open(getGitRepositoryDir())) {
            Repository repository = git.getRepository();
            logger.debug("Local repository {} found. Checkout branch {} force.", repository, branch);
            logger.trace("Repository {}: bare={}.", repository, repository.isBare());
            git.checkout()
                    .setName(ORIGIN + "/" + branch)
                    .setForced(true)
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                    .call();
            logger.debug("Pull repository {}", repository);
            git.pull().setRemote(ORIGIN).setCredentialsProvider(credentialsProvider).setRemoteBranchName(branch).call();
            logger.debug("Local repository {} found. Again checkout branch {} force.", repository, branch);
            git.checkout()
                    .setName(ORIGIN + "/" + branch)
                    .setForced(true)
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                    .call();
        }
    }
}
 
Example #11
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 #12
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 #13
Source File: BranchTask.java    From ant-git-tasks with Apache License 2.0 2 votes vote down vote up
/**
 * Corresponds to the --track/--no-track/--set-upstream options; may be null
 *
 * @see <a href="http://download.eclipse.org/jgit/docs/latest/apidocs/org/eclipse/jgit/api/CreateBranchCommand.SetupUpstreamMode.html">CreateBranchCommand.SetupUpstreamMode string values</a>
 *
 * @antdoc.notrequired
 * @param upstreamMode the upstreamMode to set (Default is --track).
 */
public void setUpstreamMode(String upstreamMode) {
        this.upstreamMode = CreateBranchCommand.SetupUpstreamMode.valueOf(upstreamMode);
}