Make usage of open safer by setting binary mode and closing fds

Signed-off-by: Shawn O. Pearce <sop@google.com>
diff --git a/editor.py b/editor.py
index a297470..34c9ad1 100644
--- a/editor.py
+++ b/editor.py
@@ -78,7 +78,11 @@
 
       if subprocess.Popen(editor + [path]).wait() != 0:
         raise EditorError()
-      return open(path).read()
+      fd = open(path)
+      try:
+        return read()
+      finally:
+        fd.close()
     finally:
       if fd:
         os.close(fd)
diff --git a/git_config.py b/git_config.py
index 7aad80d..7e642a4 100644
--- a/git_config.py
+++ b/git_config.py
@@ -219,7 +219,11 @@
       return None
     try:
       Trace(': unpickle %s', self.file)
-      return cPickle.load(open(self._pickle, 'r'))
+      fd = open(self._pickle, 'rb')
+      try:
+        return cPickle.load(fd)
+      finally:
+        fd.close()
     except IOError:
       os.remove(self._pickle)
       return None
@@ -229,9 +233,11 @@
 
   def _SavePickle(self, cache):
     try:
-      cPickle.dump(cache,
-                   open(self._pickle, 'w'),
-                   cPickle.HIGHEST_PROTOCOL)
+      fd = open(self._pickle, 'wb')
+      try:
+        cPickle.dump(cache, fd, cPickle.HIGHEST_PROTOCOL)
+      finally:
+        fd.close()
     except IOError:
       os.remove(self._pickle)
     except cPickle.PickleError:
diff --git a/git_refs.py b/git_refs.py
index 2476091..ac8ed0c 100644
--- a/git_refs.py
+++ b/git_refs.py
@@ -101,7 +101,7 @@
   def _ReadPackedRefs(self):
     path = os.path.join(self._gitdir, 'packed-refs')
     try:
-      fd = open(path, 'r')
+      fd = open(path, 'rb')
       mtime = os.path.getmtime(path)
     except IOError:
       return
@@ -138,7 +138,7 @@
 
   def _ReadLoose1(self, path, name):
     try:
-      fd = open(path, 'r')
+      fd = open(path, 'rb')
       mtime = os.path.getmtime(path)
     except OSError:
       return
diff --git a/project.py b/project.py
index 8d6e4b6..0a761ef 100644
--- a/project.py
+++ b/project.py
@@ -1070,9 +1070,7 @@
       rev = self.GetRemote(self.remote.name).ToLocal(self.revision)
       rev = self.bare_git.rev_parse('%s^0' % rev)
 
-      f = open(os.path.join(dotgit, HEAD), 'wb')
-      f.write("%s\n" % rev)
-      f.close()
+      _lwrite(os.path.join(dotgit, HEAD), '%s\n' % rev)
 
       cmd = ['read-tree', '--reset', '-u']
       cmd.append('-v')
@@ -1167,7 +1165,11 @@
         path = os.path.join(self._project.gitdir, HEAD)
       else:
         path = os.path.join(self._project.worktree, '.git', HEAD)
-      line = open(path, 'r').read()
+      fd = open(path, 'rb')
+      try:
+        line = fd.read()
+      finally:
+        fd.close()
       if line.startswith('ref: '):
         return line[5:-1]
       return line[:-1]