首页 > 解决方案 > git commit 添加了 2 个新行

问题描述

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

#!/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,但我认为这不是问题。

标签: node.jsgitgithooks

解决方案


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

第二个换行符由 Unix 世界中几乎所有(默认)命令产生。您可以使用以下方法之一删除换行符:如何从字符串中删除所有换行符?


推荐阅读