1 # misc.py -- For dealing with python2.4 oddness
2 # Copyright (C) 2008 Canonical Ltd.
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; version 2
7 # of the License or (at your option) a later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18 """Misc utilities to work with python <2.6.
20 These utilities can all be deleted when dulwich decides it wants to stop
21 support for python <2.6.
29 from urlparse import parse_qs
31 from cgi import parse_qs
36 class defaultdict(dict):
37 """A python 2.4 equivalent of collections.defaultdict."""
39 def __init__(self, default_factory=None, *a, **kw):
40 if (default_factory is not None and
41 not hasattr(default_factory, '__call__')):
42 raise TypeError('first argument must be callable')
43 dict.__init__(self, *a, **kw)
44 self.default_factory = default_factory
46 def __getitem__(self, key):
48 return dict.__getitem__(self, key)
50 return self.__missing__(key)
52 def __missing__(self, key):
53 if self.default_factory is None:
55 self[key] = value = self.default_factory()
59 if self.default_factory is None:
62 args = self.default_factory,
63 return type(self), args, None, None, self.items()
66 return self.__copy__()
69 return type(self)(self.default_factory, self)
71 def __deepcopy__(self, memo):
73 return type(self)(self.default_factory,
74 copy.deepcopy(self.items()))
76 return 'defaultdict(%s, %s)' % (self.default_factory,
80 def make_sha(source=''):
81 """A python2.4 workaround for the sha/hashlib module fiasco."""
83 return hashlib.sha1(source)
85 sha1 = sha.sha(source)
89 def unpack_from(fmt, buf, offset=0):
90 """A python2.4 workaround for struct missing unpack_from."""
92 return struct.unpack_from(fmt, buf, offset)
93 except AttributeError:
94 b = buf[offset:offset+struct.calcsize(fmt)]
95 return struct.unpack(fmt, b)