transaction.py
74 lines
| 2.1 KiB
| text/x-python
|
PythonLexer
/ mercurial / transaction.py
|
r0 | # transaction.py - simple journalling scheme for mercurial | ||
# | ||||
# This transaction scheme is intended to gracefully handle program | ||||
# errors and interruptions. More serious failures like system crashes | ||||
# can be recovered with an fsck-like tool. As the whole repository is | ||||
# effectively log-structured, this should amount to simply truncating | ||||
# anything that isn't referenced in the changelog. | ||||
# | ||||
# Copyright 2005 Matt Mackall <mpm@selenic.com> | ||||
# | ||||
# This software may be used and distributed according to the terms | ||||
# of the GNU General Public License, incorporated herein by reference. | ||||
import os | ||||
|
r421 | import util | ||
|
r0 | |||
class transaction: | ||||
|
r95 | def __init__(self, opener, journal, after = None): | ||
|
r162 | self.journal = None | ||
# abort here if the journal already exists | ||||
if os.path.exists(journal): | ||||
raise "journal already exists - run hg recover" | ||||
|
r0 | self.opener = opener | ||
|
r95 | self.after = after | ||
|
r0 | self.entries = [] | ||
|
r42 | self.map = {} | ||
|
r0 | self.journal = journal | ||
self.file = open(self.journal, "w") | ||||
def __del__(self): | ||||
if self.entries: self.abort() | ||||
|
r13 | try: os.unlink(self.journal) | ||
except: pass | ||||
|
r0 | |||
def add(self, file, offset): | ||||
|
r42 | if file in self.map: return | ||
|
r0 | self.entries.append((file, offset)) | ||
|
r42 | self.map[file] = 1 | ||
|
r0 | # add enough data to the journal to do the truncate | ||
self.file.write("%s\0%d\n" % (file, offset)) | ||||
self.file.flush() | ||||
def close(self): | ||||
self.file.close() | ||||
self.entries = [] | ||||
|
r95 | if self.after: | ||
|
r421 | util.rename(self.journal, self.after) | ||
|
r95 | else: | ||
os.unlink(self.journal) | ||||
|
r0 | |||
def abort(self): | ||||
if not self.entries: return | ||||
print "transaction abort!" | ||||
for f, o in self.entries: | ||||
|
r108 | try: | ||
self.opener(f, "a").truncate(o) | ||||
except: | ||||
print "failed to truncate", f | ||||
|
r0 | |||
self.entries = [] | ||||
print "rollback completed" | ||||
|
r515 | |||
|
r162 | def rollback(opener, file): | ||
for l in open(file).readlines(): | ||||
f, o = l.split('\0') | ||||
opener(f, "a").truncate(int(o)) | ||||
os.unlink(file) | ||||
|
r0 | |||