[英]How To Use JGit To Do Equivalent Of “git push --mirror …”?
[英]How do I do git push with JGit?
我正在嘗試構建一個 Java 應用程序,允許用戶使用基於 Git 的存儲庫。 我可以使用以下命令從命令行執行此操作:
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
這允許我創建、添加和提交內容到我的本地存儲庫並將內容推送到遠程存儲庫。 我現在正在嘗試使用 JGit 在我的 Java 代碼中做同樣的事情。 我能夠使用 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();
同樣,所有這些都可以正常工作。 我找不到git remote add
和git push
任何示例或等效代碼。 我確實看過這個SO question 。
testPush()
失敗並顯示錯誤消息TransportException: origin not found
。 在其他示例中,我看到https://gist.github.com/2487157在git push
之前執行git clone
,但我不明白為什么有必要這樣做。
任何有關我如何做到這一點的指示將不勝感激。
最簡單的方法是使用 JGit Porcelain API:
Git git = Git.open(localPath);
// 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();
您將在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());
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.