ยปCore Development>Code coverage>Lib/dbm/__init__.py

Python code coverage for Lib/dbm/__init__.py

#countcontent
1n/a"""Generic interface to all dbm clones.
2n/a
3n/aUse
4n/a
5n/a import dbm
6n/a d = dbm.open(file, 'w', 0o666)
7n/a
8n/aThe returned object is a dbm.gnu, dbm.ndbm or dbm.dumb object, dependent on the
9n/atype of database being opened (determined by the whichdb function) in the case
10n/aof an existing dbm. If the dbm does not exist and the create or new flag ('c'
11n/aor 'n') was specified, the dbm type will be determined by the availability of
12n/athe modules (tested in the above order).
13n/a
14n/aIt has the following interface (key and data are strings):
15n/a
16n/a d[key] = data # store data at key (may override data at
17n/a # existing key)
18n/a data = d[key] # retrieve data at key (raise KeyError if no
19n/a # such key)
20n/a del d[key] # delete data stored at key (raises KeyError
21n/a # if no such key)
22n/a flag = key in d # true if the key exists
23n/a list = d.keys() # return a list of all existing keys (slow!)
24n/a
25n/aFuture versions may change the order in which implementations are
26n/atested for existence, and add interfaces to other dbm-like
27n/aimplementations.
28n/a"""
29n/a
30n/a__all__ = ['open', 'whichdb', 'error']
31n/a
32n/aimport io
33n/aimport os
34n/aimport struct
35n/aimport sys
36n/a
37n/a
38n/aclass error(Exception):
39n/a pass
40n/a
41n/a_names = ['dbm.gnu', 'dbm.ndbm', 'dbm.dumb']
42n/a_defaultmod = None
43n/a_modules = {}
44n/a
45n/aerror = (error, OSError)
46n/a
47n/atry:
48n/a from dbm import ndbm
49n/aexcept ImportError:
50n/a ndbm = None
51n/a
52n/a
53n/adef open(file, flag='r', mode=0o666):
54n/a """Open or create database at path given by *file*.
55n/a
56n/a Optional argument *flag* can be 'r' (default) for read-only access, 'w'
57n/a for read-write access of an existing database, 'c' for read-write access
58n/a to a new or existing database, and 'n' for read-write access to a new
59n/a database.
60n/a
61n/a Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
62n/a only if it doesn't exist; and 'n' always creates a new database.
63n/a """
64n/a global _defaultmod
65n/a if _defaultmod is None:
66n/a for name in _names:
67n/a try:
68n/a mod = __import__(name, fromlist=['open'])
69n/a except ImportError:
70n/a continue
71n/a if not _defaultmod:
72n/a _defaultmod = mod
73n/a _modules[name] = mod
74n/a if not _defaultmod:
75n/a raise ImportError("no dbm clone found; tried %s" % _names)
76n/a
77n/a # guess the type of an existing database, if not creating a new one
78n/a result = whichdb(file) if 'n' not in flag else None
79n/a if result is None:
80n/a # db doesn't exist or 'n' flag was specified to create a new db
81n/a if 'c' in flag or 'n' in flag:
82n/a # file doesn't exist and the new flag was used so use default type
83n/a mod = _defaultmod
84n/a else:
85n/a raise error[0]("need 'c' or 'n' flag to open new db")
86n/a elif result == "":
87n/a # db type cannot be determined
88n/a raise error[0]("db type could not be determined")
89n/a elif result not in _modules:
90n/a raise error[0]("db type is {0}, but the module is not "
91n/a "available".format(result))
92n/a else:
93n/a mod = _modules[result]
94n/a return mod.open(file, flag, mode)
95n/a
96n/a
97n/adef whichdb(filename):
98n/a """Guess which db package to use to open a db file.
99n/a
100n/a Return values:
101n/a
102n/a - None if the database file can't be read;
103n/a - empty string if the file can be read but can't be recognized
104n/a - the name of the dbm submodule (e.g. "ndbm" or "gnu") if recognized.
105n/a
106n/a Importing the given module may still fail, and opening the
107n/a database using that module may still fail.
108n/a """
109n/a
110n/a # Check for ndbm first -- this has a .pag and a .dir file
111n/a try:
112n/a f = io.open(filename + ".pag", "rb")
113n/a f.close()
114n/a f = io.open(filename + ".dir", "rb")
115n/a f.close()
116n/a return "dbm.ndbm"
117n/a except OSError:
118n/a # some dbm emulations based on Berkeley DB generate a .db file
119n/a # some do not, but they should be caught by the bsd checks
120n/a try:
121n/a f = io.open(filename + ".db", "rb")
122n/a f.close()
123n/a # guarantee we can actually open the file using dbm
124n/a # kind of overkill, but since we are dealing with emulations
125n/a # it seems like a prudent step
126n/a if ndbm is not None:
127n/a d = ndbm.open(filename)
128n/a d.close()
129n/a return "dbm.ndbm"
130n/a except OSError:
131n/a pass
132n/a
133n/a # Check for dumbdbm next -- this has a .dir and a .dat file
134n/a try:
135n/a # First check for presence of files
136n/a os.stat(filename + ".dat")
137n/a size = os.stat(filename + ".dir").st_size
138n/a # dumbdbm files with no keys are empty
139n/a if size == 0:
140n/a return "dbm.dumb"
141n/a f = io.open(filename + ".dir", "rb")
142n/a try:
143n/a if f.read(1) in (b"'", b'"'):
144n/a return "dbm.dumb"
145n/a finally:
146n/a f.close()
147n/a except OSError:
148n/a pass
149n/a
150n/a # See if the file exists, return None if not
151n/a try:
152n/a f = io.open(filename, "rb")
153n/a except OSError:
154n/a return None
155n/a
156n/a with f:
157n/a # Read the start of the file -- the magic number
158n/a s16 = f.read(16)
159n/a s = s16[0:4]
160n/a
161n/a # Return "" if not at least 4 bytes
162n/a if len(s) != 4:
163n/a return ""
164n/a
165n/a # Convert to 4-byte int in native byte order -- return "" if impossible
166n/a try:
167n/a (magic,) = struct.unpack("=l", s)
168n/a except struct.error:
169n/a return ""
170n/a
171n/a # Check for GNU dbm
172n/a if magic in (0x13579ace, 0x13579acd, 0x13579acf):
173n/a return "dbm.gnu"
174n/a
175n/a # Later versions of Berkeley db hash file have a 12-byte pad in
176n/a # front of the file type
177n/a try:
178n/a (magic,) = struct.unpack("=l", s16[-4:])
179n/a except struct.error:
180n/a return ""
181n/a
182n/a # Unknown
183n/a return ""
184n/a
185n/a
186n/aif __name__ == "__main__":
187n/a for filename in sys.argv[1:]:
188n/a print(whichdb(filename) or "UNKNOWN", filename)