~mailman-coders/mailman/2.1

1779 by Mark Sapiro
Bump copyright dates.
1
# Copyright (C) 1998-2018 by the Free Software Foundation, Inc.
1 by
This commit was manufactured by cvs2svn to create branch
2
#
3
# This program is free software; you can redistribute it and/or
4
# modify it under the terms of the GNU General Public License
5
# as published by the Free Software Foundation; either version 2
6
# of the License, or (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
749 by tkikuchi
FSF office has moved to 51 Franklin Street.
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1 by
This commit was manufactured by cvs2svn to create branch
16
17
"""A `safe' dictionary for string interpolation."""
18
19
from types import StringType
20
from UserDict import UserDict
21
22
COMMASPACE = ', '
23
24
25

26
class SafeDict(UserDict):
27
    """Dictionary which returns a default value for unknown keys.
28
29
    This is used in maketext so that editing templates is a bit more robust.
30
    """
31
    def __getitem__(self, key):
32
        try:
33
            return self.data[key]
34
        except KeyError:
35
            if isinstance(key, StringType):
36
                return '%('+key+')s'
37
            else:
38
                return '<Missing key: %s>' % `key`
39
40
    def interpolate(self, template):
41
        return template % self
42
43
44

45
class MsgSafeDict(SafeDict):
46
    def __init__(self, msg, dict=None):
47
        self.__msg = msg
48
        SafeDict.__init__(self, dict)
49
50
    def __getitem__(self, key):
51
        if key.startswith('msg_'):
52
            return self.__msg.get(key[4:], 'n/a')
53
        elif key.startswith('allmsg_'):
54
            missing = []
55
            all = self.__msg.get_all(key[7:], missing)
56
            if all is missing:
57
                return 'n/a'
58
            return COMMASPACE.join(all)
59
        else:
60
            return SafeDict.__getitem__(self, key)
61
62
    def copy(self):
63
        d = self.data.copy()
64
        for k in self.__msg.keys():
65
            vals = self.__msg.get_all(k)
66
            if len(vals) == 1:
67
                d['msg_'+k.lower()] = vals[0]
68
            else:
69
                d['allmsg_'+k.lower()] = COMMASPACE.join(vals)
70
        return d