Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../lib64/python3..../dbm
File: dumb.py
"""A dumb and slow but simple dbm clone.
[0] Fix | Delete
[1] Fix | Delete
For database spam, spam.dir contains the index (a text file),
[2] Fix | Delete
spam.bak *may* contain a backup of the index (also a text file),
[3] Fix | Delete
while spam.dat contains the data (a binary file).
[4] Fix | Delete
[5] Fix | Delete
XXX TO DO:
[6] Fix | Delete
[7] Fix | Delete
- seems to contain a bug when updating...
[8] Fix | Delete
[9] Fix | Delete
- reclaim free space (currently, space once occupied by deleted or expanded
[10] Fix | Delete
items is never reused)
[11] Fix | Delete
[12] Fix | Delete
- support concurrent access (currently, if two processes take turns making
[13] Fix | Delete
updates, they can mess up the index)
[14] Fix | Delete
[15] Fix | Delete
- support efficient access to large databases (currently, the whole index
[16] Fix | Delete
is read when the database is opened, and some updates rewrite the whole index)
[17] Fix | Delete
[18] Fix | Delete
- support opening for read-only (flag = 'm')
[19] Fix | Delete
[20] Fix | Delete
"""
[21] Fix | Delete
[22] Fix | Delete
import ast as _ast
[23] Fix | Delete
import io as _io
[24] Fix | Delete
import os as _os
[25] Fix | Delete
import collections
[26] Fix | Delete
[27] Fix | Delete
__all__ = ["error", "open"]
[28] Fix | Delete
[29] Fix | Delete
_BLOCKSIZE = 512
[30] Fix | Delete
[31] Fix | Delete
error = OSError
[32] Fix | Delete
[33] Fix | Delete
class _Database(collections.MutableMapping):
[34] Fix | Delete
[35] Fix | Delete
# The on-disk directory and data files can remain in mutually
[36] Fix | Delete
# inconsistent states for an arbitrarily long time (see comments
[37] Fix | Delete
# at the end of __setitem__). This is only repaired when _commit()
[38] Fix | Delete
# gets called. One place _commit() gets called is from __del__(),
[39] Fix | Delete
# and if that occurs at program shutdown time, module globals may
[40] Fix | Delete
# already have gotten rebound to None. Since it's crucial that
[41] Fix | Delete
# _commit() finish successfully, we can't ignore shutdown races
[42] Fix | Delete
# here, and _commit() must not reference any globals.
[43] Fix | Delete
_os = _os # for _commit()
[44] Fix | Delete
_io = _io # for _commit()
[45] Fix | Delete
[46] Fix | Delete
def __init__(self, filebasename, mode, flag='c'):
[47] Fix | Delete
self._mode = mode
[48] Fix | Delete
self._readonly = (flag == 'r')
[49] Fix | Delete
[50] Fix | Delete
# The directory file is a text file. Each line looks like
[51] Fix | Delete
# "%r, (%d, %d)\n" % (key, pos, siz)
[52] Fix | Delete
# where key is the string key, pos is the offset into the dat
[53] Fix | Delete
# file of the associated value's first byte, and siz is the number
[54] Fix | Delete
# of bytes in the associated value.
[55] Fix | Delete
self._dirfile = filebasename + '.dir'
[56] Fix | Delete
[57] Fix | Delete
# The data file is a binary file pointed into by the directory
[58] Fix | Delete
# file, and holds the values associated with keys. Each value
[59] Fix | Delete
# begins at a _BLOCKSIZE-aligned byte offset, and is a raw
[60] Fix | Delete
# binary 8-bit string value.
[61] Fix | Delete
self._datfile = filebasename + '.dat'
[62] Fix | Delete
self._bakfile = filebasename + '.bak'
[63] Fix | Delete
[64] Fix | Delete
# The index is an in-memory dict, mirroring the directory file.
[65] Fix | Delete
self._index = None # maps keys to (pos, siz) pairs
[66] Fix | Delete
[67] Fix | Delete
# Handle the creation
[68] Fix | Delete
self._create(flag)
[69] Fix | Delete
self._update()
[70] Fix | Delete
[71] Fix | Delete
def _create(self, flag):
[72] Fix | Delete
if flag == 'n':
[73] Fix | Delete
for filename in (self._datfile, self._bakfile, self._dirfile):
[74] Fix | Delete
try:
[75] Fix | Delete
_os.remove(filename)
[76] Fix | Delete
except OSError:
[77] Fix | Delete
pass
[78] Fix | Delete
# Mod by Jack: create data file if needed
[79] Fix | Delete
try:
[80] Fix | Delete
f = _io.open(self._datfile, 'r', encoding="Latin-1")
[81] Fix | Delete
except OSError:
[82] Fix | Delete
if flag not in ('c', 'n'):
[83] Fix | Delete
import warnings
[84] Fix | Delete
warnings.warn("The database file is missing, the "
[85] Fix | Delete
"semantics of the 'c' flag will be used.",
[86] Fix | Delete
DeprecationWarning, stacklevel=4)
[87] Fix | Delete
with _io.open(self._datfile, 'w', encoding="Latin-1") as f:
[88] Fix | Delete
self._chmod(self._datfile)
[89] Fix | Delete
else:
[90] Fix | Delete
f.close()
[91] Fix | Delete
[92] Fix | Delete
# Read directory file into the in-memory index dict.
[93] Fix | Delete
def _update(self):
[94] Fix | Delete
self._index = {}
[95] Fix | Delete
try:
[96] Fix | Delete
f = _io.open(self._dirfile, 'r', encoding="Latin-1")
[97] Fix | Delete
except OSError:
[98] Fix | Delete
self._modified = not self._readonly
[99] Fix | Delete
else:
[100] Fix | Delete
self._modified = False
[101] Fix | Delete
with f:
[102] Fix | Delete
for line in f:
[103] Fix | Delete
line = line.rstrip()
[104] Fix | Delete
key, pos_and_siz_pair = _ast.literal_eval(line)
[105] Fix | Delete
key = key.encode('Latin-1')
[106] Fix | Delete
self._index[key] = pos_and_siz_pair
[107] Fix | Delete
[108] Fix | Delete
# Write the index dict to the directory file. The original directory
[109] Fix | Delete
# file (if any) is renamed with a .bak extension first. If a .bak
[110] Fix | Delete
# file currently exists, it's deleted.
[111] Fix | Delete
def _commit(self):
[112] Fix | Delete
# CAUTION: It's vital that _commit() succeed, and _commit() can
[113] Fix | Delete
# be called from __del__(). Therefore we must never reference a
[114] Fix | Delete
# global in this routine.
[115] Fix | Delete
if self._index is None or not self._modified:
[116] Fix | Delete
return # nothing to do
[117] Fix | Delete
[118] Fix | Delete
try:
[119] Fix | Delete
self._os.unlink(self._bakfile)
[120] Fix | Delete
except OSError:
[121] Fix | Delete
pass
[122] Fix | Delete
[123] Fix | Delete
try:
[124] Fix | Delete
self._os.rename(self._dirfile, self._bakfile)
[125] Fix | Delete
except OSError:
[126] Fix | Delete
pass
[127] Fix | Delete
[128] Fix | Delete
with self._io.open(self._dirfile, 'w', encoding="Latin-1") as f:
[129] Fix | Delete
self._chmod(self._dirfile)
[130] Fix | Delete
for key, pos_and_siz_pair in self._index.items():
[131] Fix | Delete
# Use Latin-1 since it has no qualms with any value in any
[132] Fix | Delete
# position; UTF-8, though, does care sometimes.
[133] Fix | Delete
entry = "%r, %r\n" % (key.decode('Latin-1'), pos_and_siz_pair)
[134] Fix | Delete
f.write(entry)
[135] Fix | Delete
[136] Fix | Delete
sync = _commit
[137] Fix | Delete
[138] Fix | Delete
def _verify_open(self):
[139] Fix | Delete
if self._index is None:
[140] Fix | Delete
raise error('DBM object has already been closed')
[141] Fix | Delete
[142] Fix | Delete
def __getitem__(self, key):
[143] Fix | Delete
if isinstance(key, str):
[144] Fix | Delete
key = key.encode('utf-8')
[145] Fix | Delete
self._verify_open()
[146] Fix | Delete
pos, siz = self._index[key] # may raise KeyError
[147] Fix | Delete
with _io.open(self._datfile, 'rb') as f:
[148] Fix | Delete
f.seek(pos)
[149] Fix | Delete
dat = f.read(siz)
[150] Fix | Delete
return dat
[151] Fix | Delete
[152] Fix | Delete
# Append val to the data file, starting at a _BLOCKSIZE-aligned
[153] Fix | Delete
# offset. The data file is first padded with NUL bytes (if needed)
[154] Fix | Delete
# to get to an aligned offset. Return pair
[155] Fix | Delete
# (starting offset of val, len(val))
[156] Fix | Delete
def _addval(self, val):
[157] Fix | Delete
with _io.open(self._datfile, 'rb+') as f:
[158] Fix | Delete
f.seek(0, 2)
[159] Fix | Delete
pos = int(f.tell())
[160] Fix | Delete
npos = ((pos + _BLOCKSIZE - 1) // _BLOCKSIZE) * _BLOCKSIZE
[161] Fix | Delete
f.write(b'\0'*(npos-pos))
[162] Fix | Delete
pos = npos
[163] Fix | Delete
f.write(val)
[164] Fix | Delete
return (pos, len(val))
[165] Fix | Delete
[166] Fix | Delete
# Write val to the data file, starting at offset pos. The caller
[167] Fix | Delete
# is responsible for ensuring that there's enough room starting at
[168] Fix | Delete
# pos to hold val, without overwriting some other value. Return
[169] Fix | Delete
# pair (pos, len(val)).
[170] Fix | Delete
def _setval(self, pos, val):
[171] Fix | Delete
with _io.open(self._datfile, 'rb+') as f:
[172] Fix | Delete
f.seek(pos)
[173] Fix | Delete
f.write(val)
[174] Fix | Delete
return (pos, len(val))
[175] Fix | Delete
[176] Fix | Delete
# key is a new key whose associated value starts in the data file
[177] Fix | Delete
# at offset pos and with length siz. Add an index record to
[178] Fix | Delete
# the in-memory index dict, and append one to the directory file.
[179] Fix | Delete
def _addkey(self, key, pos_and_siz_pair):
[180] Fix | Delete
self._index[key] = pos_and_siz_pair
[181] Fix | Delete
with _io.open(self._dirfile, 'a', encoding="Latin-1") as f:
[182] Fix | Delete
self._chmod(self._dirfile)
[183] Fix | Delete
f.write("%r, %r\n" % (key.decode("Latin-1"), pos_and_siz_pair))
[184] Fix | Delete
[185] Fix | Delete
def __setitem__(self, key, val):
[186] Fix | Delete
if self._readonly:
[187] Fix | Delete
import warnings
[188] Fix | Delete
warnings.warn('The database is opened for reading only',
[189] Fix | Delete
DeprecationWarning, stacklevel=2)
[190] Fix | Delete
if isinstance(key, str):
[191] Fix | Delete
key = key.encode('utf-8')
[192] Fix | Delete
elif not isinstance(key, (bytes, bytearray)):
[193] Fix | Delete
raise TypeError("keys must be bytes or strings")
[194] Fix | Delete
if isinstance(val, str):
[195] Fix | Delete
val = val.encode('utf-8')
[196] Fix | Delete
elif not isinstance(val, (bytes, bytearray)):
[197] Fix | Delete
raise TypeError("values must be bytes or strings")
[198] Fix | Delete
self._verify_open()
[199] Fix | Delete
self._modified = True
[200] Fix | Delete
if key not in self._index:
[201] Fix | Delete
self._addkey(key, self._addval(val))
[202] Fix | Delete
else:
[203] Fix | Delete
# See whether the new value is small enough to fit in the
[204] Fix | Delete
# (padded) space currently occupied by the old value.
[205] Fix | Delete
pos, siz = self._index[key]
[206] Fix | Delete
oldblocks = (siz + _BLOCKSIZE - 1) // _BLOCKSIZE
[207] Fix | Delete
newblocks = (len(val) + _BLOCKSIZE - 1) // _BLOCKSIZE
[208] Fix | Delete
if newblocks <= oldblocks:
[209] Fix | Delete
self._index[key] = self._setval(pos, val)
[210] Fix | Delete
else:
[211] Fix | Delete
# The new value doesn't fit in the (padded) space used
[212] Fix | Delete
# by the old value. The blocks used by the old value are
[213] Fix | Delete
# forever lost.
[214] Fix | Delete
self._index[key] = self._addval(val)
[215] Fix | Delete
[216] Fix | Delete
# Note that _index may be out of synch with the directory
[217] Fix | Delete
# file now: _setval() and _addval() don't update the directory
[218] Fix | Delete
# file. This also means that the on-disk directory and data
[219] Fix | Delete
# files are in a mutually inconsistent state, and they'll
[220] Fix | Delete
# remain that way until _commit() is called. Note that this
[221] Fix | Delete
# is a disaster (for the database) if the program crashes
[222] Fix | Delete
# (so that _commit() never gets called).
[223] Fix | Delete
[224] Fix | Delete
def __delitem__(self, key):
[225] Fix | Delete
if self._readonly:
[226] Fix | Delete
import warnings
[227] Fix | Delete
warnings.warn('The database is opened for reading only',
[228] Fix | Delete
DeprecationWarning, stacklevel=2)
[229] Fix | Delete
if isinstance(key, str):
[230] Fix | Delete
key = key.encode('utf-8')
[231] Fix | Delete
self._verify_open()
[232] Fix | Delete
self._modified = True
[233] Fix | Delete
# The blocks used by the associated value are lost.
[234] Fix | Delete
del self._index[key]
[235] Fix | Delete
# XXX It's unclear why we do a _commit() here (the code always
[236] Fix | Delete
# XXX has, so I'm not changing it). __setitem__ doesn't try to
[237] Fix | Delete
# XXX keep the directory file in synch. Why should we? Or
[238] Fix | Delete
# XXX why shouldn't __setitem__?
[239] Fix | Delete
self._commit()
[240] Fix | Delete
[241] Fix | Delete
def keys(self):
[242] Fix | Delete
try:
[243] Fix | Delete
return list(self._index)
[244] Fix | Delete
except TypeError:
[245] Fix | Delete
raise error('DBM object has already been closed') from None
[246] Fix | Delete
[247] Fix | Delete
def items(self):
[248] Fix | Delete
self._verify_open()
[249] Fix | Delete
return [(key, self[key]) for key in self._index.keys()]
[250] Fix | Delete
[251] Fix | Delete
def __contains__(self, key):
[252] Fix | Delete
if isinstance(key, str):
[253] Fix | Delete
key = key.encode('utf-8')
[254] Fix | Delete
try:
[255] Fix | Delete
return key in self._index
[256] Fix | Delete
except TypeError:
[257] Fix | Delete
if self._index is None:
[258] Fix | Delete
raise error('DBM object has already been closed') from None
[259] Fix | Delete
else:
[260] Fix | Delete
raise
[261] Fix | Delete
[262] Fix | Delete
def iterkeys(self):
[263] Fix | Delete
try:
[264] Fix | Delete
return iter(self._index)
[265] Fix | Delete
except TypeError:
[266] Fix | Delete
raise error('DBM object has already been closed') from None
[267] Fix | Delete
__iter__ = iterkeys
[268] Fix | Delete
[269] Fix | Delete
def __len__(self):
[270] Fix | Delete
try:
[271] Fix | Delete
return len(self._index)
[272] Fix | Delete
except TypeError:
[273] Fix | Delete
raise error('DBM object has already been closed') from None
[274] Fix | Delete
[275] Fix | Delete
def close(self):
[276] Fix | Delete
try:
[277] Fix | Delete
self._commit()
[278] Fix | Delete
finally:
[279] Fix | Delete
self._index = self._datfile = self._dirfile = self._bakfile = None
[280] Fix | Delete
[281] Fix | Delete
__del__ = close
[282] Fix | Delete
[283] Fix | Delete
def _chmod(self, file):
[284] Fix | Delete
if hasattr(self._os, 'chmod'):
[285] Fix | Delete
self._os.chmod(file, self._mode)
[286] Fix | Delete
[287] Fix | Delete
def __enter__(self):
[288] Fix | Delete
return self
[289] Fix | Delete
[290] Fix | Delete
def __exit__(self, *args):
[291] Fix | Delete
self.close()
[292] Fix | Delete
[293] Fix | Delete
[294] Fix | Delete
def open(file, flag='c', mode=0o666):
[295] Fix | Delete
"""Open the database file, filename, and return corresponding object.
[296] Fix | Delete
[297] Fix | Delete
The flag argument, used to control how the database is opened in the
[298] Fix | Delete
other DBM implementations, supports only the semantics of 'c' and 'n'
[299] Fix | Delete
values. Other values will default to the semantics of 'c' value:
[300] Fix | Delete
the database will always opened for update and will be created if it
[301] Fix | Delete
does not exist.
[302] Fix | Delete
[303] Fix | Delete
The optional mode argument is the UNIX mode of the file, used only when
[304] Fix | Delete
the database has to be created. It defaults to octal code 0o666 (and
[305] Fix | Delete
will be modified by the prevailing umask).
[306] Fix | Delete
[307] Fix | Delete
"""
[308] Fix | Delete
[309] Fix | Delete
# Modify mode depending on the umask
[310] Fix | Delete
try:
[311] Fix | Delete
um = _os.umask(0)
[312] Fix | Delete
_os.umask(um)
[313] Fix | Delete
except AttributeError:
[314] Fix | Delete
pass
[315] Fix | Delete
else:
[316] Fix | Delete
# Turn off any bits that are set in the umask
[317] Fix | Delete
mode = mode & (~um)
[318] Fix | Delete
if flag not in ('r', 'w', 'c', 'n'):
[319] Fix | Delete
import warnings
[320] Fix | Delete
warnings.warn("Flag must be one of 'r', 'w', 'c', or 'n'",
[321] Fix | Delete
DeprecationWarning, stacklevel=2)
[322] Fix | Delete
return _Database(file, mode, flag=flag)
[323] Fix | Delete
[324] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function