Henesnarfel
Henesnarfel

Reputation: 2139

Make Git ignore 'No newline at end of file' when committing

I'm working on bugs that will be integrated back into the original repo and a lot of the files do not have a newline at the end of the file.

Is there any way to make Git ignore this and allow me to make commits without that showing up?

I know with git diff you can do --ignore-space-at-eof to hide that but how can I make this happen when I do a git add?

The files need to be committed and pushed without adding a newline to the file as well as not have the commit show the need for a newline at the end.

I understand that there isn't a newline being added to the file but I need a way to suppress the warning message of 'no newline at end of file'

Upvotes: 3

Views: 9458

Answers (1)

nulltoken
nulltoken

Reputation: 67669

The files need to be committed and pushed without adding a newline to the file as well as not have the commit add the newline at the end.

The "No newline at end of file" message is only a warning. This message doesn't prevent one from committing.

Indeed, the code below just does this. A file is created without a newline (the -n option takes care of this). The file is staged then committed. Then, the same file is altered, still without adding a newline, and a new commit is made.

$ cd /d/temp
$ mkdir test && cd test
$ git init .
Initialized empty Git repository in d:/temp/test/.git/

$ echo -n test > file.txt # Create a file without a trailing newline 
$ git add .
$ git commit -m "Initial commit"
[master (root-commit) b99fc8b] Initial commit
 1 file changed, 1 insertion(+)
 create mode 100644 file.txt

$ echo -n ing... >> file.txt # Append some text to the same file (still without a newline)
$ git add .
$ git commit -m "Fixing bug without adding a trailing newline"
[master f0be668] Fixing bug without adding a trailing newline
 1 file changed, 1 insertion(+), 1 deletion(-)

Taking a peek at the latest commit will show that no newline has been added in the process

$ git show HEAD
commit f0be6684dafa85384984e7a725c2fa854183d1d0
Author: nulltoken <[email protected]>
Date:   Sat Oct 5 12:32:08 2013 +0200

    Fixing bug without adding a trailing newline

diff --git a/file.txt b/file.txt
index 30d74d2..2ae6cf4 100644
--- a/file.txt
+++ b/file.txt
@@ -1 +1 @@
-test
\ No newline at end of file
+testing...
\ No newline at end of file

So Git won't automatically add a newline for you. However, if you see this happening, there's a strong possibility that your IDE or text editor does this for you, before saving your files. In that case, browse the options and make the appropriate changes.

Upvotes: 1

Related Questions