6

After cloning a git repository from Github, if I open a file, make no changes, and save the file, the following shows up in the output of git diff:

-@import "sync.scss";
\ No newline at end of file
+@import "sync.scss";

As I understand it, \ No newline at end of file is supposed to mark the end of the file when no newline is present. Does this diff mean git thinks the last line has been moved to after the end of the file? Is there any way to avoid this? I'd like to contribute to this project without adding junk whitespace changes to my commits.

This seems like an issue with line endings. I'm fairly confident the file was originally saved on a Mac using Unix line endings. That's the same setup that I'm using, so I'm not sure what is causing the document to change when I save it.

Michael Martin-Smucker
  • 11,927
  • 7
  • 31
  • 36
  • Check if that is still the case with Git 2.17 (Q2 2018): see [my other answer there](https://stackoverflow.com/a/49330963/6309). – VonC Mar 16 '18 at 23:49

2 Answers2

8
  • To avoid this, always do git add -p, and pick only relevant diffs to avoid unwanted changes to be committed.

  • And change your editor settings to match the conventions used in the project.

Sailesh
  • 25,517
  • 4
  • 34
  • 47
  • Hmm, looks like gedit can't be configured to stop magically adding a newline at the end of the file if one doesn't exist. I'll have to look into `git add -p`, that seems like a useful feature. Thanks! – Michael Martin-Smucker Jul 10 '12 at 16:36
  • 9 years later and you helped me with this one. Thanks! – A.J Aug 27 '21 at 14:22
5

The \ No newline at end of file belongs to the line above it (meaning the line didn't end with a \n). Your current line seems to have a newline at the end which is why you don't see the 'No newline' message after it; and why there is a change at all.

I'd like to contribute to this project without adding junk whitespace changes to my commits.

(warning: personal oppinion below)

I'd advise you to always end a file with a newline, especially when working in a unix/linux environment. It may be that this is seen as 'junk' by some (ask the project maintainer for his opinion on this to be sure), but when using posix tools - starting with a simple cat - a missing newline will be a nuisance at best and break scripts transforming the code at worst.

l4mpi
  • 5,103
  • 3
  • 34
  • 54
  • Thanks, other articles I've looked at seem to agree with the idea that it's usually best to end files with `\n`. I'll check with the maintainer, but it looks like I may just include that little change as part of my commit. – Michael Martin-Smucker Jul 10 '12 at 16:34