[PATCH 06/20] gitignore: Make sure each line ends with a \n

Mathieu Bridon bochecha at fedoraproject.org
Wed Oct 29 12:57:04 UTC 2014


When loading an existing file, if its last line didn't end with a \n
character, then we'd load it as it is.

Then, if we added a new line, it would be appended to the last existing
line, as one line, which is clearly not what we want.

So we must ensure every line ends with a \n character when we load an
existing file.

While we're at it, if we're going to check for \n in 2 places, we might
as well make that a new function.
---
 src/pyrpkg/__init__.py | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/src/pyrpkg/__init__.py b/src/pyrpkg/__init__.py
index 1f097d3..660d327 100644
--- a/src/pyrpkg/__init__.py
+++ b/src/pyrpkg/__init__.py
@@ -2372,21 +2372,27 @@ class GitIgnore(object):
         self.__lines = []
         if os.path.exists(self.path):
             gitignore_file = open(self.path, 'r')
-            self.__lines = gitignore_file.readlines()
+            for line in gitignore_file:
+                self.__lines.append(self.__ensure_newline(line))
+
             gitignore_file.close()
 
         # Set to True if we end up making any modifications, used to
         # prevent unnecessary writes.
         self.modified = False
 
+    def __ensure_newline(self, line):
+        """Append a newline character if the given line didn't have one"""
+        if line.endswith('\n'):
+            return line
+
+        return '%s\n' % line
+
     def add(self, line):
         """
         Add a line to .gitignore, but check if it's a duplicate first.
         """
-
-        # Append a newline character if the given line didn't have one:
-        if line[-1] != '\n':
-            line = "%s\n" % line
+        line = self.__ensure_newline(line)
 
         # Add this line if it doesn't already exist:
         if not line in self.__lines:
-- 
2.1.0



More information about the rel-eng mailing list