Github Desktop Smudge / Clean Filter on Windows

Overview

Let's say we want to replace {{BRANCH}} with the name of the current branch:

before
"branch": "{{BRANCH}}"
after
"branch": "master"

Here's a simple smudge script. I keep these in C:\workspace\git-filter-demo. Save them with unix line endings!

#!/bin/sh export BRANCH=`git rev-parse --symbolic --abbrev-ref HEAD` sed -e "s/{{BRANCH}}/$BRANCH/"

and the clean script (use unix line endings):

#!/bin/sh sed -e 's/^\s*"branch"\s*:.*/\t"branch": "{{BRANCH}}"/'

Let's call the filter myFilter in [home]/.gitconfig

[filter "myFilter"] smudge = \"C:/workspace/git-filter-demo/smudge\" clean = \"C:/workspace/git-filter-demo/clean\"

To test it, checkout https://github.com/vinnyjames/git-filter-demo.git

The above repo will run myFilter on myFile via [repo]/.gitattributes

myFile.json filter=myFilter

One problem: switching branches does not trigger a clean and smudge. I.e., your {{BRANCH}} text will not change. This can be worked around with the following post-checkout script that will perform a clean and smudge on the file. This will not destory any changes in your file (assuming the clean and smudge scripts are written correctly).

#!/bin/sh # see https://www.tygertec.com/git-hooks-practical-uses-windows/ # .../bin/sh; C:/Users/first.last/AppData/Local/GitHubDesktop/app-2.7.2/resources/app/git/usr/bin/sh.exe # export LOGFILE=post-checkout.log # date > $LOGFILE # echo --- 1:$1 2:$2 3:$3 >> $LOGFILE # FAIRLY DANGEROUS, ONLY RUN WHEN PARAM 3 = "1", I.E. A BRANCH CHANGE # OTHEWISE THIS SCRIPT CAN BE CALLED INFINITELY # see https://git-scm.com/docs/githooks#_post_checkout if [ "$3" = "1" ]; then export SCRIPT_DIR=/c/workspace/git-filter-demo export CLEAN_SCRIPT=$SCRIPT_DIR/clean export SMUDGE_SCRIPT=$SCRIPT_DIR/smudge export FILE=myFile.json export TMPFILE=_tmp_post-checkout # export BRANCH=`git rev-parse --symbolic --abbrev-ref HEAD` # echo BRANCH:$BRANCH TMPFILE:${TMPFILE} >> $LOGFILE # clean; this script must use #!/bin/sh on windows $CLEAN_SCRIPT < ${FILE} > ${TMPFILE} mv ${TMPFILE} ${FILE} # echo cleaned >> $LOGFILE # smudge; this script must use #!/bin/sh on windows $SMUDGE_SCRIPT < ${FILE} > ${TMPFILE} mv ${TMPFILE} ${FILE} # echo smudged >> $LOGFILE # 2021-04-23 'git status' was saying the file was modified even though it was binary the same # adding it seems to clear this invalid state without losing any local changes git add ${FILE} # else # echo NOT_BRANCH >> $LOGFILE fi #echo done >> $LOGFILE