Advertisement
DJSBX

git clean and smudge linter

Feb 8th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.74 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # This script is a git clean filter (https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes#filters_b)
  4. # This will run when files are staged (specifically for all *.py files as defined in the .gitattributes file)
  5. # The point of this script will be to lint our python files with Python Black, and iSort upon committing them
  6.  
  7. # This script takes in stdin data and expects stdout data. So in order to run black and iSort on the input
  8. # data, we need to save the data into a file somewhere, process that, and then output the results
  9.  
  10. # Because this expects stdout, we can't let any of our commands output any data, so we just pipe them to
  11. # /dev/null. Unfortunatley this means that we won't get to see any errors.
  12. # Because of this, this script will fallback to output the original data if any error occurs.
  13.  
  14. # Make a temporary file to store the stdin code
  15. tmpfile=$(mktemp)
  16. tmplint=$(mktemp)
  17.  
  18. # The "file" is either stdin, or an argument (not sure we need this)
  19. file=${1--}
  20.  
  21. # Read in the stdin data into our temp files
  22. while IFS= read -r line ; do
  23.     echo "$line" >> "$tmpfile"
  24.     echo "$line" >> "$tmplint"
  25. done < <(cat -- "$file")
  26.  
  27. # Keep a status variable. If either command returns a non zero
  28. # then we just return the original input
  29. rc=0
  30.  
  31. # Run black and iSort on our modified temp file
  32. isort $tmplint > /dev/null 2>&1
  33. if [ $? -ne 0 ] ; then
  34.     rc=1
  35. fi
  36.  
  37. black $tmplint > /dev/null 2>&1
  38. if [ $? -ne 0 ] ; then
  39.     rc=1
  40. fi
  41.  
  42. # Check the return codes
  43. if [ $rc -ne 0 ] ; then
  44.     # If we had a bad exit, then just cat the original input
  45.     cat $tmpfile
  46. else
  47.     # else we cat the linted contents
  48.     cat $tmplint
  49. fi
  50.  
  51. # Remove the temp files
  52. rm $tmpfile > /dev/null 2>&1
  53. rm $tmplint > /dev/null 2>&1
  54.  
  55. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement