Last active
April 22, 2018 21:31
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Author
Leedehai
commented
Apr 22, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment