Как мне сделать git push с помощью JGit? - программирование
Подтвердить что ты не робот

Как мне сделать 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. Я посмотрел на этот вопрос SO.

testPush() выходит из строя с сообщением об ошибке TransportException: origin not found. В других примерах я видел https://gist.github.com/2487157 do git clone до git push, и я не знаю, t понять, зачем это необходимо.

Любые указания на то, как я могу это сделать, будут оценены.

4b9b3361

Ответ 1

Вы найдете в 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 иллюстрирует различные сценарии push, используя 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();
    

Ответ 2

Самый простой способ - использовать API-интерфейс JGit Porcelain:

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