Running into TransportException “Nothing to push” when pushing changed file with JGit

吃可爱长大的小学妹 提交于 2020-02-07 05:20:25

问题


I'm using JGit to checkout a branch from my git repository and modify a file. After I committed the changes I try to push it but running into TransportException:

Caused by: org.eclipse.jgit.errors.TransportException: Nothing to push.
at org.eclipse.jgit.transport.Transport.push(Transport.java:1332)
at org.eclipse.jgit.api.PushCommand.call(PushCommand.java:169)
...

My code looks like this:

this.checkoutBranch(branchName);
try (Writer writer = new OutputStreamWriter(new FileOutputStream(getFilePath(filepath).toFile(), true),
                    StandardCharsets.UTF_8))
{
    Yaml yaml = this.initializeYaml();
    Map<String, Object> parameterMap = this.getParameterMap(filepath, yaml);
    parameterMap.put(key, value);

    // write file
    yaml.dump(parameterMap, writer);

    // commit and push
    git.add().addFilepattern(filepath).call();
    git.commit().setMessage("Added parameter with key: '" + key + "'").call();

    git.push().setCredentialsProvider(getCredentialProvider()).call();
}
catch(GitAPIException | IOException e)
{
    throw new GitClientException("Cannot write parameters.", e);
}

Here is the method for checking out the current branch:

public void checkoutBranch(String branchName)
{
    try
    {
        git.checkout().setName("origin/" + branchName).call();
    }
    catch(GitAPIException e)
    {
        throw new GitClientException("Cannot checkout branch.", e);
    }
}

I looked for JGit examples and I found many of them, but no example handles file changes. Has anybody a hint what could be wrong?


回答1:


Calling checkoutBranch will result in a detached HEAD and this may be the reason why the push command fails.

git.getRepository().getFullBranch() now returns the object id (SHA-1) of the commit to which the remote branch points to.

To check out a remote branch without detaching HEAD, Git needs to create a local branch that acts as a proxy and tracks the remote branch. See JGit: Checkout a remote branch for how to achieve this with JGit.



来源:https://stackoverflow.com/questions/51496146/running-into-transportexception-nothing-to-push-when-pushing-changed-file-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!