Fix bzr-fastimport when used with newer versions of python-fastimport.(Jelmer Vernooij)
[bzr-fastimport.git] / user_mapper.py
blobd5d17080290fd77e9526cc30a9bfe7f28982b0e7
1 # Copyright (C) 2009 Canonical Ltd
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
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.
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 from email import Utils
19 class UserMapper(object):
21 def __init__(self, lines):
22 """Create a user-mapper from a list of lines.
24 Blank lines and comment lines (starting with #) are ignored.
25 Otherwise lines are of the form:
27 old-id = new-id
29 Each id may be in the following forms:
31 name <email>
32 name
34 If old-id has the value '@', then new-id is the domain to use
35 when generating an email from a user-id.
36 """
37 self._parse(lines)
39 def _parse(self, lines):
40 self._user_map = {}
41 self._default_domain = None
42 for line in lines:
43 line = line.strip()
44 if len(line) == 0 or line.startswith('#'):
45 continue
46 old, new = line.split('=', 1)
47 old = old.strip()
48 new = new.strip()
49 if old == '@':
50 self._default_domain = new
51 continue
52 # Parse each id into a name and email address
53 old_name, old_email = self._parse_id(old)
54 new_name, new_email = self._parse_id(new)
55 #print "found user map: %s => %s" % ((old_name, old_email), (new_name, new_email))
56 self._user_map[(old_name, old_email)] = (new_name, new_email)
58 def _parse_id(self, id):
59 if id.find('<') == -1:
60 return id, ""
61 else:
62 return Utils.parseaddr(id)
64 def map_name_and_email(self, name, email):
65 """Map a name and an email to the preferred name and email.
67 :param name: the current name
68 :param email: the current email
69 :result: the preferred name and email
70 """
71 try:
72 new_name, new_email = self._user_map[(name, email)]
73 except KeyError:
74 new_name = name
75 if self._default_domain and not email:
76 new_email = "%s@%s" % (name, self._default_domain)
77 else:
78 new_email = email
79 return new_name, new_email