不少開發者可能遇到過這個問題:從git上拉取服務端代碼,然后只修改了一處地方,准備提交時,用diff軟件查看,卻發現整個文件都被修改了。這是git自動轉換換行符導致的問題。
原因
不同操作系統使用的換行符是不一樣的。Unix/Linux使用的是LF,Mac后期也采用了LF,但Windows一直使用CRLF【回車(CR, ASCII 13, \r) 換行(LF, ASCII 10, \n)】作為換行符。而git入庫的代碼采用的是LF格式,它考慮到了跨平台協作的場景,提供了“換行符自動轉換”的功能:如果在Windows下安裝git,在拉取文件時,會自動將LF換行符替換為CRLF;在提交時,又會將CRLF轉回LF。但是這個轉換是有問題的:有時提交時,CRLF轉回LF可能會不工作,尤其是文件中出現中文字符后有換行符時。
解決方案
1.禁用git的自動換行功能:
在本地路徑C:\ Users\ [用戶名] \ .gitconfig下修改git配置[core],如果沒有就直接添加上去:
[core] autocrlf = false filemode = false safecrlf = true
git bash命令行也可以修改,最終也是修改.gitconfig配置文件:
分別執行:
git config --global core.autocrlf false git config --global core.filemode false git config --global core.safecrlf true
2.配置IDE開發環境,將它的換行格式指定為LF,以android studio為例:
原文:https://blog.csdn.net/whsdu929/article/details/52490188
方法二:
當我們pull完代碼時進行修改,修改后提交代碼時會發現一些文件並未修改,但顯示有差異,而且通過git status查看時是Untracked file如下:
$ git status
On branch master
Your branch is behind 'origin/master' by 27 commits, and can be fast-forwarded.
(use "git pull" to update your local branch)
Untracked files:
(use "git add <file>..." to include in what will be committed)
model/src/main/java/
nothing added to commit but untracked files present (use "git add" to track)
如果忽略這些問題有時代碼可以正常的pull和commit,但有時會導致我們pull代碼失敗,並提示:
error: The following untracked working tree files would be overwritten by merge
出錯的文件正是那些不是我們修改的文件,這時候可以用如下方式進行處理:
1、git fetch origin master
把遠端的代碼拉倒本地,並把指針放到FETCH_HEAD中
$ git fetch origin master
connected to center BJ
From ssh:****
* branch master -> FETCH_HEAD
Warning: cannot log into influxdb
2、git reset --hard FETCH_HEAD
把本地的代碼指針切換到剛剛拉下來的那個指針上;
3、git push origin master
把本地的代碼推送到遠端,其實即使不推送也沒問題,因為本地代碼跟遠端已經一致了;
$ git push origin master
connected to center BJ
Warning: cannot log into influxdb
Everything up-to-date
4、git status
再次查看發現那些文件的差異已經沒有了
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean
5、后面可以繼續執行其他操作了
原文:https://blog.csdn.net/weixin_38178584/article/details/81298004