运行 使用 JGit 推送更改的文件时进入 TransportException "Nothing to push"

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

我正在使用 JGit 从我的 git 存储库中检出一个分支并修改一个文件。提交更改后,我尝试将其推送,但 运行 进入 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)
...

我的代码如下所示:

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);
}

查看当前分支的方法如下:

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

我查找了 JGit 示例并找到了很多,但是没有示例处理文件更改。 有没有人提示可能出了什么问题?

调用checkoutBranch将导致分离的HEAD,这可能是推送命令失败的原因。

git.getRepository().getFullBranch() 现在 returns 远程分支指向的提交的对象 ID (SHA-1)。

要在不分离 HEAD 的情况下检出远程分支,Git 需要创建一个本地分支作为代理并跟踪远程分支。请参阅 JGit: Checkout a remote branch 以了解如何使用 JGit 实现此目的。