git - 让 'git diff' 忽略 ^M

标签 git newline diff git-diff carriage-return

在一些文件包含 ^M 作为换行符的项目中 分隔符,区分这些文件显然是不可能的,因为 git diff 将整个文件视为一行。

一个git diff在比较当前和以前的时候如何 源代码文件的版本?

是否有类似“区分时将 ^M 视为换行符”之类的选项?

prompt> git-diff "HEAD^" -- MyFile.as 
diff --git a/myproject/MyFile.as b/myproject/MyFile.as
index be78321..a393ba3 100644
--- a/myproject/MyFile.cpp
+++ b/myproject/MyFile.cpp
@@ -1 +1 @@
-<U+FEFF>import flash.events.MouseEvent;^Mimport mx.controls.*;^Mimport mx.utils.Delegate
\ No newline at end of file
+<U+FEFF>import flash.events.MouseEvent;^Mimport mx.controls.*;^Mimport mx.utils.Delegate
\ No newline at end of file
prompt>

更新:

我已经编写了一个 Ruby 脚本来检查最新的 10 个修订并将 CR 转换为 LF。

require 'fileutils'

if ARGV.size != 3
  puts "a git-path must be provided"
  puts "a filename must be provided"
  puts "a result-dir must be provided"
  puts "example:"
  puts "ruby gitcrdiff.rb project/dir1/dir2/dir3/ SomeFile.cpp tmp_somefile"
  exit(1)
end

gitpath = ARGV[0]
filename = ARGV[1]
resultdir = ARGV[2]

unless FileTest.exist?(".git")
  puts "this command must be run in the same dir as where .git resides"
  exit(1)
end

if FileTest.exist?(resultdir)
  puts "the result dir must not exist"
  exit(1)
end
FileUtils.mkdir(resultdir)

10.times do |i|
  revision = "^" * i
  cmd = "git show HEAD#{revision}:#{gitpath}#{filename} | tr '\\r' '\\n' > #{resultdir}/#{filename}_rev#{i}"
  puts cmd 
  system cmd
end

最佳答案

GitHub suggests你应该确保在 git 处理的 repos 中只使用\n 作为换行符。有一个自动转换的选项:

$ git config --global core.autocrlf true

当然,这里说的是crlf转lf,而你要cr转lf。我希望这仍然有效……

然后转换你的文件:

# Remove everything from the index
$ git rm --cached -r .

# Re-add all the deleted files to the index
# You should get lots of messages like: "warning: CRLF will be replaced by LF in <file>."
$ git diff --cached --name-only -z | xargs -0 git add

# Commit
$ git commit -m "Fix CRLF"

core.autocrlf 在 the man page 上有描述.

关于git - 让 'git diff' 忽略 ^M,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1889559/

相关文章:

linux - 如何将 git .diff 文件 merge 到源代码?

git - Visual Studio 2017 中 cherry-pick 提交方法的区别

css - 样式表设置不在 IE 和 Firefox 上的新行中显示 <li> 内容

C# - 统一差异/补丁创建者

git - 如何 git "hides"分支之间的文件?

python - 将多行写入记事本文件python

css - 如何使用 css 将一组元素带到紧邻的下一行

arrays - Perl - 有效区分超大数组的最佳实践

linux - 比较大文件

git - 致命的 : I don't handle protocol '' while pushing to upstream