YPCrumble YPCrumble - 3 months ago 10
Git Question

How can I tell if my editor is adding or removing newlines at the end of a file from the diff?

If I have the following diff:

diff --git a/file.txt b/file.txt
index abcdef..ghijkl mnopqr
--- a/file.txt
+++ b/file.txt
@@ -2,4 +2,4 @@

-This is a line of code.
\ No newline at end of file
+This is a line of code


I understand that I want the newline at the end of the file. However, from this diff, is my editor adding or removing the newline at the end of the file?

I can't tell if the
\No newline at end of file
refers to what my text editor removed (above) or what it added (below).

Answer

The message cited in your question indicates the newline was added in the newer version of the file being diffed.

If instead the newline had been removed in the newer version of the file being diffed, you’d see this:

diff --git a/file.txt b/file.txt
index abcdef..ghijkl mnopqr
--- a/file.txt
+++ b/file.txt
@@ -2,4 +2,4 @@
-This is a line of code.
+This is a line of code.
\ No newline at end of file

That is, the \ No newline at end of file part would be the very last line of the diff.


If you want to test this yourself, here are two files you can run diff -u on:

  • noeol.txt (which has no newline at the end of file)
  • eol.txt (which has a newline at the end of file)

diff -u noeol.txt eol.txt will give you this:

--- noeol.txt   2016-08-13 12:55:16.000000000 +0900
+++ eol.txt 2016-08-13 12:55:23.000000000 +0900
@@ -1 +1 @@
-This is a line of code.
\ No newline at end of file
+This is a line of code.

diff -u eol.txt noeol.txt will give you this:

--- eol.txt 2016-08-13 12:55:23.000000000 +0900
+++ noeol.txt   2016-08-13 12:55:16.000000000 +0900
@@ -1 +1 @@
-This is a line of code.
+This is a line of code.
\ No newline at end of file
Comments