5

我有一个裸仓库位于main.git并试图foo在另一个仓库中获取一个分支(比方说),该仓库test刚刚被git init'd:

fetchtest/
  |- main.git/
  |- test/
       |- .git/

使用常规 git 命令,我可以执行 a git fetch ../main.git foo:foo,这将创建一个新分支footest/获取分支所需的对象。然后我想做同样的事情,但以编程方式使用 JGit,即不使用 git CLI,而只使用 Java 代码。我无法使用 git CLI:

Git git = Git.init().setDirectory(new File("fetchtest/test/")).call();

git.fetch().setRemote(new File("../main.git"))
           .setRefSpecs(new RefSpec("foo:foo"))
           .call();

但它只是错误:

org.eclipse.jgit.api.errors.TransportException: Remote does not have foo available for fetch.
    at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:137)
    // ......
Caused by: org.eclipse.jgit.errors.TransportException: Remote does not have foo available for fetch.
    at org.eclipse.jgit.transport.FetchProcess.expandSingle(FetchProcess.java:349)
    at org.eclipse.jgit.transport.FetchProcess.executeImp(FetchProcess.java:139)
    at org.eclipse.jgit.transport.FetchProcess.execute(FetchProcess.java:113)
    at org.eclipse.jgit.transport.Transport.fetch(Transport.java:1069)
    at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:128)

我怎样才能让它工作?

4

1 回答 1

5

什么应该起作用:

Git git = Git.init().setDirectory(new File("fetchtest/test/")).call();

git.fetch().setRemote(new File("../main.git"))
           .setRefSpecs(new RefSpec("refs/heads/foo:refs/heads/foo"))
           .call();

注意RefSpec定义。
至少,试试你的例子:

new RefSpec("refs/heads/foo:refs/heads/foo")

RefSpec课堂上提到:

/**
 * Parse a ref specification for use during transport operations.
 * <p>
 * Specifications are typically one of the following forms:
 * <ul>
 * <li><code>refs/head/master</code></li>
 * <li><code>refs/head/master:refs/remotes/origin/master</code></li>
 * <li><code>refs/head/*:refs/remotes/origin/*</code></li>
 * <li><code>+refs/head/master</code></li>
 * <li><code>+refs/head/master:refs/remotes/origin/master</code></li>
 * <li><code>+refs/head/*:refs/remotes/origin/*</code></li>
 * <li><code>:refs/head/master</code></li>
 * </ul>
 *
 * @param spec
 * string describing the specification.
 * @throws IllegalArgumentException
 * the specification is invalid.
*/

所以“ refs/head/”似乎是强制性的。


原答案:

setRemote()on 函数api.FetchCommand采用名称或 URI。

查看FetchCommandTestURI 定义,我更喜欢使远程更可见:
我宁愿test为您的第二个 repo(参考您的第一个 repo)定义一个命名远程(在下面:“”),然后获取。

// setup the first repository to fetch from the second repository
final StoredConfig config = db.getConfig();
RemoteConfig remoteConfig = new RemoteConfig(config, "test");
URIish uri = new URIish(db2.getDirectory().toURI().toURL());
remoteConfig.addURI(uri);
remoteConfig.update(config);
config.save();

// create some refs via commits and tag
RevCommit commit = git2.commit().setMessage("initial commit").call();
Ref tagRef = git2.tag().setName("tag").call();

Git git1 = new Git(db);

RefSpec spec = new RefSpec("refs/heads/master:refs/heads/x");
git1.fetch().setRemote("test").setRefSpecs(spec)
.call();
于 2012-07-03T06:06:15.853 回答