【问题标题】:git commit adds 2 new linesgit commit 添加了 2 个新行
【发布时间】:2019-03-18 10:44:37
【问题描述】:

我正在 Windows 上使用 nodeJS 编写 post-commit 挂钩脚本。以下代码调用最后一条提交消息:

#!/bin/env node

require('child_process').exec('git log -1 --pretty=%B', function(err, commit) {
    console.log(commit); // prints message in command prompt with 2 empty lines  
    var messages = commit.split(' '); // the delimiter is irrelevant
    console.log(messages); // prints the array and shows '\n\n' at the end of last element
    console.log(messages[messages.length - 1]); // yet this prints the last element WITHOUT '\n\n'
});

为什么有 2 条新线?我阅读了 Unix 和非 Unix 系统如何处理 CR 和 LF。 git config core.autocrlf 也有一点,但我认为这不是问题。

【问题讨论】:

  • 您能描述一下您的用例吗?我对此很感兴趣,我可以扩展我的pypi.org/project/hooks4git 应用程序以内置这种调用。所以你只需要在 .ini 文件中说明你想显示最后的日志。
  • 回复有点晚,抱歉。我的目标是获取提交消息,对其进行格式化并将其存储在文本文件中。我的问题是我最终得到了不需要的新行。此外,例如,Windows 的 Notepad 对待 CR 和 LF 的方式与 Notepad++ 不同。 IE。存储的提交消息出现在同一行。 Notepad++ 在新行上显示每条消息。
  • 我明白了。理想情况下,您需要规范化 CRLF ......对我来说,Windows 是“错误的”,所以我保留所有类似 linux 的东西。不确定这是否会为您带来另一个问题。

标签: node.js git githooks


【解决方案1】:

第一个换行符由--pretty=%B 格式生成。 Git 默认使用tformat 进行格式化,它使用终止符语法(与分隔符语法相反,称为format)。您可以使用--pretty=format:%B 来避免使用该换行符,并考虑使用man git-log 了解更多详细信息。

第二个换行符是 Unix 世界中几乎所有(默认)命令产生的。您可以使用以下方法之一删除换行符:How to remove all line breaks from a string?

【讨论】:

  • 所以终止符语法 (tformat) 总是添加一个新行,而分隔符语法 (format) 希望我们添加一个 显式(前提是新行我们默认从 Unix 得到的命令是不够的)。我想我现在明白了。感谢您清除它。 :)
猜你喜欢
  • 2011-02-15
  • 2011-04-02
  • 2011-07-01
  • 2012-02-15
  • 2011-12-01
  • 2014-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多