在Jgit中使用'pull'命令

问题描述 投票:7回答:3

我是git的新用户,我正在使用JGit与远程git存储库进行交互。在JGit中,我使用CloneCommand来初步克隆回购,它没有问题。但是,当我尝试使用PullCommand(相当于SVN更新AFAIK)时,本地存储库内容不会更新。

这是我使用的代码:

private String localPath;
private Repository localRepo;
private Git git;

localPath = "/home/test/git_repo_test";
remotePath = "https://github.com/test/repo_1.git";

try {
    localRepo = new FileRepository(localPath + "/.git");
} catch (IOException e) {
    e.printStackTrace();  
}
git = new Git(localRepo);

PullCommand pullCmd = git.pull();
try {
    pullCmd.call();
} catch (GitAPIException e) {
    e.printStackTrace();  
}

这不会更新我使用命令行推送到远程存储库的新文件的本地存储库。但是,如果我删除本地存储库并再次获取克隆,则会反映所有更改。

请告诉我在JGit中使用PullCommand的正确方法是什么。

编辑:

远程存储库的结构:

root ____ file_1
  |______ directory_1
              |__________ file_2 
              |__________ file_3

在初始克隆之后,从命令行推送了directory_1和两个文件,我尝试了这个代码,这样它就会反映在本地存储库中,而这种情况并没有发生。

用于克隆存储库的代码:

File file = new File(localPath);
CloneCommand cloneCmd = git.cloneRepository();
try {
    cloneCmd.setURI(remotePath)
            .setDirectory(file)
            .call();
} catch (GitAPIException e) {
    e.printStackTrace();  
}

在这里,gitlocalPathremotePath与上面的变量相同。

java git git-pull jgit
3个回答
7
投票

我怀疑问题是当前分支没有上游配置(因此pull不会合并获取的分支)。

要查看拉动期间发生的事情,请检查pullCmd.call()的结果:

PullResult result = pullCmd.call();
FetchResult fetchResult = result.getFetchResult();
MergeResult mergeResult = result.getMergeResult();
mergeResult.getMergeStatus();  // this should be interesting

4
投票

Documentations说关于Git类的构造函数如下:

构造一个可以与指定的git存储库交互的新Git对象。此类的方法返回的所有命令类将始终与此git存储库进行交互。

所以,正如我所建议的那样,你必须将远程仓库的路径传递给构造函数,现在你正试图从你的本地仓库中提取。


0
投票

我遇到了同样的问题。对我来说,解决方案是在克隆后设置git配置文件:

CloneCommand cloneCommand = Git.cloneRepository();
cloneCommand.setURI("<repo-uri>");
cloneCommand.setDirectory("<repo-dir>");
cloneCommand.call();

Git git = Git.open("<repo-dir>");
StoredConfig config = git.getRepository().getConfig();
config.setString("branch", "master", "merge", "refs/heads/master");
config.setString("branch", "master", "remote", "origin");
config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
config.setString("remote", "origin", "url", "<repo-uri>");
config.save();

拉动时,我将远程分支名称设置为“master”,将远程分支设置为“origin”:

PullCommand pull = git.pull();
pull.setRemote("origin");
pull.setRemoteBranchName("master");

拉动后的这些变化我看到本地反映的变化。

© www.soinside.com 2019 - 2024. All rights reserved.