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

Signed-off-by: Shawn O. Pearce <sop@google.com>
This commit is contained in:
Shawn O. Pearce 2009-04-18 14:48:03 -07:00
parent accc56d82b
commit 76ca9f8145
4 changed files with 23 additions and 11 deletions

View File

@ -78,7 +78,11 @@ least one of these before using this command."""
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)

View File

@ -219,7 +219,11 @@ class GitConfig(object):
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 @@ class GitConfig(object):
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:

View File

@ -101,7 +101,7 @@ class GitRefs(object):
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 @@ class GitRefs(object):
def _ReadLoose1(self, path, name):
try:
fd = open(path, 'r')
fd = open(path, 'rb')
mtime = os.path.getmtime(path)
except OSError:
return

View File

@ -1070,9 +1070,7 @@ class Project(object):
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 @@ class Project(object):
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]