Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git pre-commit bash script on Windows

I've created a simple pre-commit script for git:

#!/bin/sh

if git rev-parse —verify HEAD >/dev/null 2>&1; then
    against=HEAD
else
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

for FILE in `git diff --cached --name-only` ; do
    # Check if the file contains 'DbMigration'
    echo $FILE $against
    if [ -n "grep -E ':\s*DbMigration\s' $FILE" ];
    then
        echo ''
        echo ''
        echo '[**CODEPOLICE**]'
        echo '[**CODEPOLICE**]' $FILE
        echo '[**CODEPOLICE**]'
        echo '[**CODEPOLICE**] This file contains a direct subclass of DbContext! Refactor your migrations to use <...> instead!'
        echo '[**CODEPOLICE**]'
        echo ''
        echo ''
        exit 1
    fi
done

exit

The check if [ -n "grep -E ':\s*DbMigration\s' $FILE" ] fails miserably in the sense that it generates false positives.

Versions involved are:

Windows 10 Enterprise

$ git --version
git version 2.15.1.windows.2

$ bash --version
GNU bash, version 4.4.12(1)-release (x86_64-pc-msys)

What gives?

Update

Some examples:

 public partial class Initial : DbMigration --> we want positive & we get positive --> ok

 public partial class Initial : FoobarDbMigration --> we want negative & we get positive --> not ok

 public partial class Initial : Foobar --> we want negative & we get positive --> not ok

 public partial class Initial : DbMigrationFoobar --> we want negative & we get positive --> also not ok
like image 485
XDS Avatar asked Dec 09 '25 21:12

XDS


1 Answers

You have to start a subshell to execute the command.

To test for an empty string, you have to do it like this:

[ -n "$(grep -E ':\s*DbMigration\s' $FILE)" ]

This yields correct with all the given test cases you provided.

like image 113
Stefan M Avatar answered Dec 11 '25 14:12

Stefan M