Rewriting history – changing a single file

In this example, we'll see how we can use Git filter-branch to remove sensitive data from a file throughout the repository history.

Getting ready

For simplicity, we'll use a very simple example repository. It contains a few files. One among them is .credentials, which contains a username and password. Start by cloning the repository and changing the directory, as shown in the following command:

$ git clone https://github.com/dvaske/remove-credentials.git
$ cd remove-credentials

How to do it...

  1. As we need to modify a file when rewriting the history of this repository, we'll use the tree-filter option to filter branch. The .credentials file looks as follows:
    username = foobar
    password = verysecret
    
  2. All we need to do is to remove everything after the equals sign on each line of the file. We can use the following sed command to do this:
    sed -i '' 's/^(.*=).*$/1/'
    
  3. We can now run the filter branch with the following command:
    $ git filter-branch --prune-empty  --tree-filter "test -f .credentials && sed -i '' 's/^(.*=).*$/1/' .credentials || true" -- --all
    
  4. If we look at the file now, we can see the username and password are gone:
    $ cat .credentials
    username =
    password =
    
  5. As we saw in the last example, we still need to clean up after the filter-branch, by deleting original references, expiring the reflog, and triggering garbage collection.

How it works…

For each commit in the repository, Git will check the contents of that commit and run tree-filter. If the filter fails, non zero the exit code, filter-branch will fail. Therefore, it is important to remember to handle the cases where tree-filter might fail. This is why the previous tree-filter checks whether the .credentials file exists, runs the sed command if it does, and otherwise returns true to continue the filter-branch.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset