Skip to content

Instantly share code, notes, and snippets.

@jonEbird
Created December 2, 2014 18:42
Show Gist options
  • Save jonEbird/6994eb1560520dd53a05 to your computer and use it in GitHub Desktop.
Save jonEbird/6994eb1560520dd53a05 to your computer and use it in GitHub Desktop.
Stage and commit local file updates
import os
import sys
import stat
import shutil
import tempfile
import logging as log
class UpdateFile(object):
"""Update a file atomically
Iterate over this object to read lines from current file and then use
.write() to make updates to a new copy of the file. These are not being
done to the file directly but instead to a temporary file. To finalize
the update to filename, use .commit() """
def __init__(self, filename):
self.filename = filename
self.committed = False
try:
self.__fh = open(filename, 'rb')
self.__tmp = tempfile.NamedTemporaryFile(delete=False,
dir=os.path.dirname(filename),
prefix='.%s-' % os.path.basename(filename))
# Fix up permissions and ownership upfront
shutil.copymode(self.filename, self.__tmp.name)
s = os.stat(filename)
os.chown(self.__tmp.name, s.st_uid, s.st_gid)
except (IOError, OSError), e:
log.error('Problem setting up tempfile contents for %s: %s',
filename, str(e))
raise
def __del__(self):
self.__tmp.close()
self.__fh.close()
def __repr__(self):
if self.committed:
return '<UpdateFile %s (CLOSED) wrote %d bytes>' % \
(self.filename, self.__tmp.tell())
else:
return '<UpdateFile %s bytes staged=%d>' % \
(self.filename, self.__tmp.tell())
def __iter__(self):
# Makes this object act like other opened files
return self.__fh
def write(self, data):
"""Make updates to the temporary file before committing the final"""
if not self.committed:
self.__tmp.write(data)
def commit(self):
"""Commit the data written to tempfile to original file"""
if not self.committed:
try:
# sync and close file handles
os.fdatasync(self.__tmp.file.fileno())
self.__tmp.close()
self.__fh.close()
# Actual copy is a rename
os.rename(self.__tmp.name, self.filename)
self.committed = True
except (IOError, OSError), e:
log.error('Problem renaming tempfile into %s: %s',
self.filename, str(e))
raise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment