How can I use JGit to add deleted files to the index?

心已入冬 提交于 2020-12-31 04:40:18

问题


I want to add to the index all the modifications made in a folder:

  • files modified
  • files added
  • files removed
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();
    }
}

Output of this command:

Missing: testGit/test.txt

And output of 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")

Deleted file is not added to the index. How can I achieve this?

I checked testAddRemovedCommittedFile, it seems adding a deletion makes nothing.


回答1:


To add a deleted file to the index so that it will be deleted when committing you need to use the RmCommand.

Just like you would do with native Git

git rm test.txt

you can do in JGit

git.rm().addFilepattern("test.txt").call();

This will add test.txt to the index and mark it as to be deleted. The next revision that is committed will not contain test.txt any more.

If the file(s) specified by addFilepattern() aren't yet deleted from the work directory, the RmCommand will delete them. This is the default behavior. Calling setCached(true) before executing the command, will leave the work directory unaffected.



来源:https://stackoverflow.com/questions/32876426/how-can-i-use-jgit-to-add-deleted-files-to-the-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!