我正在尝试构建一个允许用户使用基于Git的存储库的Java应用程序.我可以使用以下命令从命令行执行此操作:
git init
<create some files>
git add .
git commit
git remote add <remote repository name> <remote repository URI>
git push -u <remote repository name> master
Run Code Online (Sandbox Code Playgroud)
这允许我创建,添加和提交内容到我的本地存储库并将内容推送到远程存储库.我现在正试图在我的Java代码中使用JGit做同样的事情.我能够轻松地使用JGit API执行git init,添加和提交.
Repository localRepo = new FileRepository(localPath);
this.git = new Git(localRepo);
localRepo.create();
git.add().addFilePattern(".").call();
git.commit().setMessage("test message").call();
Run Code Online (Sandbox Code Playgroud)
同样,所有这一切都很好.我找不到任何例子或者等效代码git remote add
和git push
.我确实看过这个问题.
testPush()
失败并显示错误消息TransportException: origin not found
.在其他例子我见过https://gist.github.com/2487157做git clone
之前 git push
,我不明白为什么这是必要的.
任何有关如何做到这一点的指示将不胜感激.
Olg*_*zek 22
最简单的方法是使用JGit Porcelain API:
Repository localRepo = new FileRepository(localPath);
Git git = new Git(localRepo);
// add remote repo:
RemoteAddCommand remoteAddCommand = git.remoteAdd();
remoteAddCommand.setName("origin");
remoteAddCommand.setUri(new URIish(httpUrl));
// you can add more settings here if needed
remoteAddCommand.call();
// push to remote:
PushCommand pushCommand = git.push();
pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider("username", "password"));
// you can add more settings here if needed
pushCommand.call();
Run Code Online (Sandbox Code Playgroud)
Von*_*onC 14
您将在org.eclipse.jgit.test
所有需要的示例中找到:
RemoteconfigTest.java
用途Config
:
config.setString("remote", "origin", "pushurl", "short:project.git");
config.setString("url", "https://server/repos/", "name", "short:");
RemoteConfig rc = new RemoteConfig(config, "origin");
assertFalse(rc.getPushURIs().isEmpty());
assertEquals("short:project.git", rc.getPushURIs().get(0).toASCIIString());
Run Code Online (Sandbox Code Playgroud)PushCommandTest.java说明了各种推送方案,使用RemoteConfig
.
见testTrackingUpdate()
一个完整的例子推动了跟踪远程分支.
摘录:
String trackingBranch = "refs/remotes/" + remote + "/master";
RefUpdate trackingBranchRefUpdate = db.updateRef(trackingBranch);
trackingBranchRefUpdate.setNewObjectId(commit1.getId());
trackingBranchRefUpdate.update();
URIish uri = new URIish(db2.getDirectory().toURI().toURL());
remoteConfig.addURI(uri);
remoteConfig.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/"
+ remote + "/*"));
remoteConfig.update(config);
config.save();
RevCommit commit2 = git.commit().setMessage("Commit to push").call();
RefSpec spec = new RefSpec(branch + ":" + branch);
Iterable<PushResult> resultIterable = git.push().setRemote(remote)
.setRefSpecs(spec).call();
Run Code Online (Sandbox Code Playgroud)