jGit - 如何将所有文件添加到临时区域

caa*_*os0 16 java git jgit

我尝试了很多方法用jGit克隆一个repo(它有效).然后,我写的一些库存档,并尝试添加所有(一个git add *,git add -A或者类似的东西)..但它不工作.文件简单不会添加到临时区域.

我的代码是这样的:

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(new File(folder))
            .readEnvironment().findGitDir().setup().build();
    CloneCommand clone = Git.cloneRepository();
    clone.setBare(false).setCloneAllBranches(true);
    clone.setDirectory(f).setURI("git@192.168.2.43:test.git");
    try {
        clone.call();
    } catch (GitAPIException e) {
        e.printStackTrace();
    }
    Files.write("testing it...", new File(folder + "/test2.txt"),
            Charsets.UTF_8);
    Git g = new Git(repository);
    g.add().addFilepattern("*").call();
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?谢谢.


尝试使用addFilePattern(".")时遇到异常:

Exception in thread "main" org.eclipse.jgit.errors.NoWorkTreeException: Bare Repository has neither a working tree, nor an index
    at org.eclipse.jgit.lib.Repository.getIndexFile(Repository.java:850)
    at org.eclipse.jgit.dircache.DirCache.lock(DirCache.java:264)
    at org.eclipse.jgit.lib.Repository.lockDirCache(Repository.java:906)
    at org.eclipse.jgit.api.AddCommand.call(AddCommand.java:138)
    at net.ciphersec.git.GitTests.main(GitTests.java:110)
Run Code Online (Sandbox Code Playgroud)

Von*_*onC 20

调试这个的一个简单方法是查看JGit 仓库AddCommand的测试:AddCommandTest.java

您将看到,为了添加所有文件,模式" *"从不使用,但" ."是.
它用于名为...的测试函数testAddWholeRepo()(!)

git.add().addFilepattern(".").call();
Run Code Online (Sandbox Code Playgroud)

例外情况:

Exception in thread "main" org.eclipse.jgit.errors.NoWorkTreeException: 
Bare Repository has neither a working tree, nor an index
Run Code Online (Sandbox Code Playgroud)

非常明确:您需要在非裸仓库中添加文件.

请参阅测试方法testCloneRepository()以与您自己的克隆进行比较,并查看是否存在任何差异.


hip*_*ndy 5

我不得不将文件f1从当前目录移动到另一个名为“ temp”的目录。移动文件后,调用git.add()。addFilePattern(“。”)。call()的行为很奇怪,因为git status给出了以下结果:

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   temp/f1.html

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    f1.html
Run Code Online (Sandbox Code Playgroud)

它认识到已创建了新文件temp / f1,但未检测到该文件已首先删除。这可能是因为可以如下所示移动文件

  • 删除/剪切文件f1
  • 创建一个名为temp的文件夹
  • 创建/粘贴文件f1

然后,我遇到了setUpdate(true),它寻找已被跟踪且不会暂存新文件的文件更新。(有关更多信息,请查看java-doc)

因此,我必须将代码更改为两行,以便git识别添加和修改的文件(包括删除):

git.add().addFilepattern(".").call();
git.add().setUpdate(true).addFilepattern(".").call();
Run Code Online (Sandbox Code Playgroud)

git status现在给出了预期的结果:

renamed:    f1.hml -> temp/f1.html
Run Code Online (Sandbox Code Playgroud)