如何使用JGit将已删除的文件添加到索引中?

FGI*_*FGI 3 jgit

我想在索引中添加所有在文件夹中进行的修改:

  • 文件已修改
  • 文件已添加
  • 文件已删除
File gitDir = new File("/home/franck/Repositories/Git/Sandbox/.git");
try (Repository repo = new RepositoryBuilder().setGitDir(gitDir).build()){
    try (Git git = new Git(repo)){
        final Status status = git.status().addPath("testGit").call();
        final AddCommand addCommand = git.add();

        Set<String> removed = status.getRemoved();
        for (final String s : removed) {
            System.out.print("removed: "+s);
            addCommand.addFilepattern(s);
        }

        Set<String> missing =  status.getMissing();
        for (final String s : missing) {
            System.out.print("Missing: "+s);
            addCommand.addFilepattern(s);
        }

        addCommand.call();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出此命令:

Missing: testGit/test.txt
Run Code Online (Sandbox Code Playgroud)

并输出git status:

On branch master  
Your branch is ahead of 'origin/master' by 1 commit.  
  (use "git push" to publish your local commits)  
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:    testGit/test.txt  

no changes added to commit (use "git add" and/or "git commit -a")
Run Code Online (Sandbox Code Playgroud)

删除的文件未添加到索引中.我怎样才能做到这一点?

我检查了testAddRemovedCommittedFile,似乎添加删除什么都没做.

Rüd*_*ann 8

要将已删除的文件添加到索引中,以便在提交时将其删除,您需要使用RmCommand.

就像你对原生Git一样

git rm test.txt
Run Code Online (Sandbox Code Playgroud)

你可以在JGit做

git.rm().addFilepattern("test.txt").call();
Run Code Online (Sandbox Code Playgroud)

这将添加test.txt到索引并将其标记为要删除.提交的下一个修订版将不再包含test.txt.

如果addFilepattern()尚未从工作目录中删除指定的文件,RmCommand则将删除它们.这是默认行为.setCached(true)在执行命令之前调用将使工作目录不受影响.