Search code examples
gitnormalizationgitattributesend-of-line

Ensure that all committed text files have only LF newlines


.gitattributes file with * text=auto followed by git add --renormalize . appears to be a good way to purge CRLF from repository.

But still (according to https://git-scm.com/docs/gitattributes )

When the file has been committed with CRLF, no conversion is done.

Is there a way to specify in repository that all CRLF will be converted to LF in text files on commit?


Solution

  • Yes, you can do it. You can use hooks like this to prevent several files to be committed or for any other purpose like in your case to "convert" them and verify the EOF.

    pre-receive hook

    #!/bin/sh
    
    # Redirect output to screen.
    exec 1>&2
    
    # Get the list of files in the commit and "update" the file EOF as you wish
    # Loop over the files and do your stuff......
    for file in $( git diff-tree -r --name-only ); do
            ..... <do your stuff here > 
        done        
    
    # Some personal message
    red='\033[0;31m';
    green='\033[0;32m';
    yellow='\033[0;33m';
    default='\033[0;m';
    
    echo "${red}"
    echo "                                         "
    echo "                   |ZZzzz                "
    echo "                   |                     "
    echo "                   |                     "
    echo "      |ZZzzz      /^\            |ZZzzz  "
    echo "      |          |~~~|           |       "
    echo "      |        |-     -|        / \      "
    echo "     /^\       |[]+    |       |^^^|     "
    echo "  |^^^^^^^|    |    +[]|       |   |     "
    echo "  |    +[]|/\/\/\/\^/\/\/\/\/|^^^^^^^|   "
    echo "  |+[]+   |~~~~~~~~~~~~~~~~~~|    +[]|   "
    echo "  |       |  []   /^\   []   |+[]+   |   "
    echo "  |   +[]+|  []  || ||  []   |   +[]+|   "
    echo "  |[]+    |      || ||       |[]+    |   "
    echo "  |_______|------------------|_______|   "
    echo "                                         "
    echo "                                         "
    echo "  ${green}All text are fixed             " 
    echo "                                         "
    echo "${default}"
    
    
    # set the exit code to 0 or 1 based upon your needs
    # 0 = good to push
    exit 0;
    

    Note:

    Github does not support using hooks in this way.
    They have their own WebHooks

    In this case, you can use hooks as well but on the client side.
    The same code can be placed inside pre-commit hook on the client side.