git commit get fatal error “fatal: CRLF would be replaced by LF in”

前端 未结 9 1625
渐次进展
渐次进展 2020-11-29 16:10

I\'m using Ubuntu 13.10 x64, and I am working on a project that some developers are using Windows , I recently changed the git config core.eol to \"lf\" and

9条回答
  •  粉色の甜心
    2020-11-29 16:42

    This happened to me on thousands of files. So I wrote a quick bash script to make dos2unix fix it for me. Someone else on Linux or Mac might find it useful.

    #!/usr/bin/env bash
    
    unwindows() {
    
      local errmsg
      local fpath
    
      # base case
      errmsg="$(git add . 2>&1)"
      if [[ $? -eq 0 ]]; then
        echo 'Successfully converted CRLF to LF in all files.'
        echo 'Successfully ran "git add .".'
        echo 'Done.'
        return 0
      fi
    
      fpath="${errmsg#*fatal: CRLF would be replaced by LF in }"
      fpath="${fpath%.*}"
    
      if [[ "${fpath}" == "${errmsg}" ]]; then
        err 'Regex failed. Could not auto-generate filename from stderr.'
        return 1
      fi
    
      if [[ ! -e "${fpath}" ]]; then
        err "Regex failed. '${fpath}' does not exist."
        return 1
      fi
    
      if ! dos2unix "${fpath}"; then
        err "Failed to run \"dos2unix '${fpath}'\"."
        return 1
      fi
    
      # recursive case
      unwindows
    }
    
    err() {
      local -r msg="$1"
      echo "${msg}" >&2
    }
    
    unwindows
    

    Basically, it tries to do git add .. If the command fails, it grabs the name of the incompatible file from the error output. Then it runs dos2unix on that file. It keeps repeating this process until git add . works.

    If you run this, you should see dos2unix: converting file xxx to Unix format... repeatedly. If you don't, it's not working, so just press ctrl+c or command+c to stop it.

提交回复
热议问题