3

I'm writing a post-commit hook script with nodeJS on Windows. The following code calls the last commit message:

#!/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'
});

Why are there 2 new lines? I read on how Unix and non-Unix systems treat CR and LF. A bit on git config core.autocrlf too, but I don't think that's the issue.

Bruno
  • 613
  • 1
  • 7
  • 8
  • can you describe your use case? I was interested in it, and i can extend my https://pypi.org/project/hooks4git/ app to have such kind of call built in. So you just need to tell on the .ini file that you wanna show last logs. – Lovato Oct 18 '18 at 18:49
  • A bit of a late reply, sorry. My aim was to get the commit message, format it and store it in a text file. My problem was that I ended up with unwanted new lines. Moreover, Windows' Notepad treats CR and LF differently than Notepad++, for example. I.e. the stored commit messages appeared on the same line. Notepad++ shows each message on a new line. – Bruno Dec 05 '18 at 21:38
  • I see. Ideally you need to normalize CRLF... To me, Windows is "wrong", so I keep everything linux-like. Not sure if this would end creating another problem for you. – Lovato Dec 07 '18 at 11:14

1 Answers1

3

The first newline char is produced by your format --pretty=%B. Git per default uses tformat for the formatting, which uses a terminator syntax (as opposed to the separator syntax, called format). You could use --pretty=format:%B to avoid that newline, and consider man git-log for more details.

The second newline is produced by almost all (default) commands in the Unix world. You can remove the newlines using one of these methods: How to remove all line breaks from a string?

alfunx
  • 3,080
  • 1
  • 12
  • 23
  • 1
    So terminator syntax (`tformat`) always adds a new line while the separator syntax (`format`) would want us to add one *explicitly* (provided that the new line we get by default from the Unix command is not enough). I think I get it now. Thanks for clearing that up. :) – Bruno Oct 13 '18 at 17:34