Skip to content

Instantly share code, notes, and snippets.

@Leedehai
Last active April 22, 2018 21:31
Show Gist options
  • Save Leedehai/cd2dd2378f3ffae048959028d7a155e8 to your computer and use it in GitHub Desktop.
Save Leedehai/cd2dd2378f3ffae048959028d7a155e8 to your computer and use it in GitHub Desktop.
Python script: better git-filter-branch to remove sensitive file from all branches
#!/usr/bin/env python
# usage: git-filter.py PATH_TO_TARGET_FILE
# (or make an alias for "git-filter-branch.py")
# Prototype:
# git filter-branch --force --index-filter \
# 'git rm --cached --ignore-unmatch PATH_TO_TARGET_FILE' \
# --prune-empty --tag-name-filter cat -- --all
# Reference: https://help.github.com/articles/removing-sensitive-data-from-a-repository/
# https://git-scm.com/docs/git-filter-branch
import sys, subprocess
if len(sys.argv[1:]) != 1:
print("the input should be one path to the target file")
sys.exit(1)
path_to_target = sys.argv[1]
cmd_part1 = ["git", "filter-branch", "--force", "--index-filter"]
cmd_part2 = ["'git rm --cached --ignore-unmatch %s' " % path_to_target]
cmd_part3 = ["--prune-empty", "--tag-name-filter", "cat --", "--all"] # "--all" indicates all branches
cmd = cmd_part1 + cmd_part2 + cmd_part3
print("command to execute:\n\033[32m%s\033[0;m" % ' '.join(cmd))
consent = raw_input("Remove %s from the history of all branches?\n>> " % path_to_target)
if consent.lower() not in ["y", "yes"]:
print("Abort.")
sys.exit(1)
# fork a subprocess, execute command.
sp = subprocess.Popen(' '.join(cmd), shell=True) # warning: shell=True makes your system vulnerable to malicious input, so
# don't deploy this on a server! Yet, shell=True is necessary to correctly
# run this command in the child process.
# wait the subprocess, get its return code
ret = sp.wait()
if ret is 0: # success
print("Done. You may want to run git gc --auto to cleanup.")
sys.exit(ret)
@Leedehai
Copy link
Author

screen shot 2018-04-22 at 14 30 46

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment