Git 'pre-receive' hook and 'git-clang-format' script to reliably reject pushes that violate code style conventions

后端 未结 2 949
暗喜
暗喜 2021-02-20 05:13

Let\'s immediately start with a scrap of the pre-receive hook that I\'ve already written:

#!/bin/sh
##
  format_bold=\'\\033[1m\'
   format_red=\'\\         


        
2条回答
  •  忘掉有多难
    2021-02-20 05:49

    Condensed

    I had a little bit of trouble understanding the first example, in part due to the length and extra tidbits that make it useful for the OP's specific use case. I combed through and condensed it down to this:

    ref_name=$1
    new_rev=$3
    
    # only check branches, not tags or bare commits
    if [ -z $(echo $ref_name | grep "refs/heads/") ]; then
      exit 0
    fi
    
    # don't check empty branches
    if [ "$(expr "${new_rev}" : '0*$')" -ne 0 ]; then
      exit 0
    fi
    
    # Checkout a copy of the branch (but also changes HEAD)
    my_work_tree=$(mktemp -d -t git-work-tree.XXXXXXXX) 2>/dev/null
    git --work-tree="${my_work_tree}" --git-dir="." checkout $new_rev -f >/dev/null
    
    # Do the formatter check
    echo "Checking code formatting..."
    pushd ${my_work_tree} >/dev/null
    prettier './**/*.{js,css,html,json,md}' --list-different
    my_status=$?
    popd >/dev/null
    
    # reset HEAD to master, and cleanup
    git --work-tree="${my_work_tree}" --git-dir="." checkout master -f >/dev/null
    rm -rf "${my_work_tree}"
    
    # handle error, if any
    if [ "0" != "$my_status" ]; then
      echo "Please format the files listed above and re-commit."
      echo "(and don't forget your .prettierrc, if you have one)"
      exit 1
    fi
    

    This example is using Prettier, but it'll map pretty well to clang-format, eslint, etc. There are a few limitations to the (perhaps oversimplified, but working) example above. I'd recommend diving deeper...

    Better, but longer

    Once you've grok'd that I'd also recommend taking a scroll down towards the bottom of this one:

    • Reject Ugly Commits with Server-Side Git Hooks

提交回复
热议问题