JGit:推送到特定分支

han*_*nsi 3 git branch push jgit

我在github上有两个分支:master和development.我想将新创建的文件推送到开发分支.

    String user = "user";
    String password = "password";
    String localPath = "local";
    String remotePath = "https://github.com/some/git.git";
    Git.cloneRepository().setBranch("refs/heads/development").setURI(remotePath).setDirectory(new File(localPath)).call();
    Git localGit = Git.open(new File(localPath));         
    localGit.checkout().setName("origin/development").setUpstreamMode(SetupUpstreamMode.TRACK).call();

    new File("local/test").createNewFile();

    localGit.add().addFilepattern(".").call();
    localGit.commit().setMessage("message").call();
    localGit.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, password)).call();
Run Code Online (Sandbox Code Playgroud)

我得到的是一个

  TransportException: Nothing to push.
Run Code Online (Sandbox Code Playgroud)

有什么问题?

更新: 我可以通过删除checkout命令使其工作.由于克隆已经检出指定的分支,这在我之前并不清楚.

Von*_*onC 6

By doing a checkout of the origin/development (that is a remote tracking branch of the upstream repo 'origin'), you have created a detached head, that is a head associated with 0 local branch (ie, not with refs/head/development, but here with refs/remotes/origin/development)

That is why a git push returns "nothing to push", since no local branch has received any new commit to push.

You need to be sure of:

  • having the local 'development' branch checked out (which you did with .setBranch("development"), although I prefer, as in the jgit clone test, to use .setBranch("refs/head/development") to be sure to reference a local branch)
  • making 'origin/development' the upstream branch of 'development'.
    Or at least, as in this jgit push test, use the right refspec development:development.