Как мне сделать git push с 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
Это позволило мне создавать, добавлять и фиксировать содержимое в локальном репозитории и отправлять содержимое в удаленный репозиторий.
Теперь я пытаюсь сделать то же самое в своем коде Java, используя JGit. Я смог легко сделать git init, добавить и зафиксировать с помощью Jgit API.
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. Я посмотрел на это , поэтому вопрос .
testPush() сбой с сообщением об ошибке TransportException: origin not found. В других примерах, которые я видел https://gist.github.com/2487157 do git clone раньше git push и я не понимаю, зачем это нужно.
Любые указания на то, как я могу это сделать, будут оценены по достоинству.
2 ответов:
Вы найдете в
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());Пушкомандтест.java иллюстрирует различные сценарии push, используя
RemoteConfig.
ВидишьtestTrackingUpdate()для полного примера pushing an отслеживает удаленную ветвь.
Выдержки: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();
Самый простой способ-использовать 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();
Comments