6

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.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
FGI
  • 139
  • 2
  • 8
  • 2
    I stumbled across the same "issue". The git CLI behaves different than jgit with "git add .". jgit sticks to git v1 add's behavior, rather than git v2 add's. See this related answer: https://stackoverflow.com/a/16162511/1143126 – RobertG Apr 27 '18 at 12:06

1 Answers1

13

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.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79