Skip to content

Instantly share code, notes, and snippets.

@postmodern
Last active April 1, 2022 23:13
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save postmodern/5659d3828e443002ee95 to your computer and use it in GitHub Desktop.
Save postmodern/5659d3828e443002ee95 to your computer and use it in GitHub Desktop.
A `git filter-branch` script for extracting arbitrary files in a repo.
#!/bin/bash
#
# usage: git filter-branch --force --prune-empty --index-filter "$(cat git_file_filter.sh)" --tag-name-filter cat -- --all
#
shopt -s globstar
whitelist=(
# files and globs go here
)
function whitelisted()
{
for path in "${whitelist[@]}"; do
if [[ "$1" == "$path" ]]; then
return 0
fi
done
return 1
}
delete=()
for file in $(git ls-files); do
if ! whitelisted "$file"; then
delete+=("$file")
fi
done
git rm --cached --ignore-unmatch "${delete[@]}"
@postmodern
Copy link
Author

Apparently foo/{,**/}*.rb globs do not work in this script. Had to explicitly expand them.

@postmodern
Copy link
Author

In the year 2021 git filter-branch is kind of discouraged due to performance and gotchas. Use git filter-repo or BFG. I successfully used:

git filter-repo --force --path PATH1 --path PATH2 ... --tag-rename '':'old-repo-'

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