首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >处理只更改空格的块

处理只更改空格的块
EN

Stack Overflow用户
提问于 2020-01-12 17:28:04
回答 1查看 124关注 0票数 3

在我维护的代码中,我有时会收到pull请求,提交者只是在没有明显原因的情况下重排了一个段落。下面是一个示例:

代码语言:javascript
复制
diff --git a/knuth.tex b/knuth.tex
index 2f6a2f8..7b0827d 100644
--- a/knuth.tex
+++ b/knuth.tex
@@ -1,6 +1,6 @@
 Thus, I came to the conclusion that the designer of a new
 system must not only be the implementer and first
-large||scale user; the designer should also write the first
+large-scale user; the designer should also write the first
 user manual.

 The separation of any of these four components would have
@@ -9,8 +9,7 @@ all these activities, literally hundreds of improvements
 would never have been made, because I would never have
 thought of them or perceived why they were important.

-But a system cannot be successful if it is too strongly
-influenced by a single person. Once the initial design is
-complete and fairly robust, the real test begins as people
-with many different viewpoints undertake their own
-experiments.
+But a system cannot be successful if it is too strongly influenced by
+a single person. Once the initial design is complete and fairly
+robust, the real test begins as people with many different viewpoints
+undertake their own experiments.

正如您所看到的,第一个块引入了一个实际的更改,用-替换了||,而第二个块除了换行符和空格之外没有更改任何内容。事实上,第二个块的word-diff将是空的。

是否可以设置一个策略(例如在GitHub上或在我的CI中)来拒绝包含这种“空”块的提交,或者重新格式化补丁以完全忽略这些块,以便我可以在没有它们的情况下git apply它?

相关:How to git-apply a git word diff

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-21 10:22:21

如果你正在寻找一个内置的解决方案,我不知道。然而,这并不意味着这不能相对容易地构建到CI系统中。

您可以将适当的git diff命令的输出通过管道传输到如下脚本中,如果输入包含如上第二个块的补丁,则该脚本将退出1。

代码语言:javascript
复制
#!/usr/bin/env ruby

def filter(arr)
  arr.join.split("\n\n").map { |x| x.gsub(/\s+/, ' ') }.join("\n\n")
end

def should_reject(before, after)
  return false if before.empty? && after.empty?
  before = filter(before)
  after = filter(after)
  return true if before == after
  false
end

chunk = nil
before = []
after = []
while (line = gets)
  trimmed = line[1..-1]
  case line
  when /^(\+\+\+|---)/
    # Do nothing.
  when /^@@ /
    if should_reject(before, after)
      warn "Useless change to hunk #{chunk}"
      exit 1
    end
    chunk = line
    before = []
    after = []
  when /^ /
    before << trimmed
    after << trimmed
  when /^\+/
    after << trimmed
  when /^-/
    before << trimmed
  end
end

if should_reject(before, after)
  warn "Useless change to hunk #{chunk}"
  exit 1
end

它基本上将每个块拆分为块,块之间有一个空行,将所有空格转换为空格,然后对它们进行比较。如果它们相等,它会报错并退出非零。您可能希望将其修改为更健壮,就像处理CRLF结尾之类的,但这种方法是可行的。

顺便说一句,让这类更改更容易发现的一种方法是使用逐行语句样式。每个句子,无论长度如何,都在一行上,并且每行只有一个句子。这使得区分任何类型的更改变得容易得多,并完全避免了包装问题。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59702503

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档