1

I have configured my repo to use a hooks directory instead of the .git/hooks directory so that it can be managed from within the repo

I want to run sed to redact a password before a commit occurs. I am using this code in my hooks/pre-commit script which I have also made executable.

#!/bin/bash

FNAME=smbclient.conf
sed -i -e 's/password=.*/password=See_Thycotic/g' ${FNAME}

grep -c See_Thycotic ${FNAME}
if [ "$?" -ne "0" ] ; then
    echo Failed to redact password in ${FNAME}
    exit 1
fi
echo Password was redacted in ${FNAME} before commit

When I run this command:

git commit smbclient.conf -m "changed something"

I see this message (as expected):

1
Password was redacted in smbclient.conf before commit

The problem is that the file is committed before the contents are changed by the pre-commit script. If I then run git status, it tells me modified: smbclient.conf.

1) How can I change this file before the commit occurs and then also have it committed?

2) Is it possible to have the pre-commit script run when committing only the smbclient.conf file and no other files?

jftuga
  • 1,913
  • 5
  • 26
  • 49
  • From the attached `pre-commit` hook, it seems like you forgot to run `git add` on the updated file? – Alderath Aug 20 '19 at 14:34
  • @Alderath: it has already been added and previously committed. I just need to run `sed` on the file before the commit occurs. – jftuga Aug 20 '19 at 14:45
  • Even if `git add` has been executed before `git commit` you also need to `git add` the updates which were made by `sed` inside the `pre-commit` hook. – Alderath Aug 20 '19 at 14:49

1 Answers1

1

1) You should let the pre-commit hook do git add $FNAME if the $FNAME file was updated by sed.

2) No. It is not possible to define pre-commit hooks which will only execute for a specific file.

The proper way to do this would probably be to let the script run on every commit, but let it start by doing something along the lines of:

    if [[ "$(git diff --name-only --staged -- $FNAME)" == "" ]] #If $FNAME file is not updated in this commit
    then
        exit 0 #Stop execution of this hook, and consider hook execution successful
    fi

    #Rest of pre-commit hook script here
Alderath
  • 3,761
  • 1
  • 25
  • 43