2

I've been trying to decipher the git-filter-branch command used here to rewrite the index such that all the repo contents are within a new directory, which is then used to move this to the subdirectory of another repo. Focussing on the specific command:

git filter-branch --index-filter '
        git ls-files -s |
        sed "s,\t,&'"$dir"'/," |
        GIT_INDEX_FILE="$GIT_INDEX_FILE.new" git update-index --index-info &&
        mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"
    ' HEAD

This essentially seems to change the index to look from /folder1/path/to/file to 'newrootfolder'/folder1/path/to/file.

Questions:

  • Where is the GIT_INDEX_FILE variable coming from, what is it set to and how does that entire line work?
  • How does the new folder(say newrootfolder) get automatically created in the repository - does git internally detect and create the directory?
tangy
  • 3,056
  • 2
  • 25
  • 42

1 Answers1

1

GIT_INDEX_FILE is one of the repository environment variables

the path to the index file (non-bare repositories only).

That filter command and example was introduced in June 2007, with this patch

GIT_INDEX_FILE="$GIT_INDEX_FILE.new" git update-index --index-info 

That part forces git to re-create a new index file, with the renamed folder in it.

mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"

Once the new index is created, it can replace the legacy one.


Please note the current option (in python, so cross-platform) is to use git filter-repo, which replaces the old obsolete git filter-branch or BFG

git filter-repo --path <olddirectory>/ --path-rename <olddirectory>/:<newdirectory>/

Example:

If you want two directories to be renamed (and maybe merged if both are renamed to the same location), use --path-rename; for example, to rename both cmds/ and src/scripts/ to tools/:

git filter-repo --path-rename cmds:tools --path-rename src/scripts/:tools/
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Thanks, for this specific task I needed to use `git filter-repo --to-subdirectory-filter ${dir}`. Also would be great for completeness sake to explain how the entire command in the question is working, especially the 2nd half. – tangy Dec 31 '20 at 18:34
  • 1
    @tangy I agree. I have edited the answer to add some explanation about the second part of the old `git filter-branch` command. – VonC Dec 31 '20 at 18:52