This commit was manufactured by cvs2svn to create tag 'r22a4-fork'.
[python/dscho.git] / Lib / whichdb.py
blob8687b719b21a62075e8644f3977f53dc95646e87
1 """Guess which db package to use to open a db file."""
3 import os
5 if os.sep==".":
6 endsep = "/"
7 else:
8 endsep = "."
10 def whichdb(filename):
11 """Guess which db package to use to open a db file.
13 Return values:
15 - None if the database file can't be read;
16 - empty string if the file can be read but can't be recognized
17 - the module name (e.g. "dbm" or "gdbm") if recognized.
19 Importing the given module may still fail, and opening the
20 database using that module may still fail.
21 """
23 import struct
25 # Check for dbm first -- this has a .pag and a .dir file
26 try:
27 f = open(filename + endsep + "pag", "rb")
28 f.close()
29 f = open(filename + endsep + "dir", "rb")
30 f.close()
31 return "dbm"
32 except IOError:
33 pass
35 # Check for dumbdbm next -- this has a .dir and and a .dat file
36 try:
37 f = open(filename + endsep + "dat", "rb")
38 f.close()
39 f = open(filename + endsep + "dir", "rb")
40 try:
41 if f.read(1) in ["'", '"']:
42 return "dumbdbm"
43 finally:
44 f.close()
45 except IOError:
46 pass
48 # See if the file exists, return None if not
49 try:
50 f = open(filename, "rb")
51 except IOError:
52 return None
54 # Read the start of the file -- the magic number
55 s16 = f.read(16)
56 f.close()
57 s = s16[0:4]
59 # Return "" if not at least 4 bytes
60 if len(s) != 4:
61 return ""
63 # Convert to 4-byte int in native byte order -- return "" if impossible
64 try:
65 (magic,) = struct.unpack("=l", s)
66 except struct.error:
67 return ""
69 # Check for GNU dbm
70 if magic == 0x13579ace:
71 return "gdbm"
73 # Check for BSD hash
74 if magic in (0x00061561, 0x61150600):
75 return "dbhash"
77 # BSD hash v2 has a 12-byte NULL pad in front of the file type
78 try:
79 (magic,) = struct.unpack("=l", s16[-4:])
80 except struct.error:
81 return ""
83 # Check for BSD hash
84 if magic in (0x00061561, 0x61150600):
85 return "dbhash"
87 # Unknown
88 return ""