Fix import of single_plural.
[bzr-fastimport.git] / user_mapper.py
blob4fcf4a40ec8e86431911fb42e579b08a4ee9050d
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, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 from email import Utils
20 class UserMapper(object):
22 def __init__(self, lines):
23 """Create a user-mapper from a list of lines.
25 Blank lines and comment lines (starting with #) are ignored.
26 Otherwise lines are of the form:
28 old-id = new-id
30 Each id may be in the following forms:
32 name <email>
33 name
35 If old-id has the value '@', then new-id is the domain to use
36 when generating an email from a user-id.
37 """
38 self._parse(lines)
40 def _parse(self, lines):
41 self._user_map = {}
42 self._default_domain = None
43 for line in lines:
44 line = line.strip()
45 if len(line) == 0 or line.startswith('#'):
46 continue
47 old, new = line.split('=', 1)
48 old = old.strip()
49 new = new.strip()
50 if old == '@':
51 self._default_domain = new
52 continue
53 # Parse each id into a name and email address
54 old_name, old_email = self._parse_id(old)
55 new_name, new_email = self._parse_id(new)
56 #print "found user map: %s => %s" % ((old_name, old_email), (new_name, new_email))
57 self._user_map[(old_name, old_email)] = (new_name, new_email)
59 def _parse_id(self, id):
60 if id.find('<') == -1:
61 return id, None
62 else:
63 return Utils.parseaddr(id)
65 def map_name_and_email(self, name, email):
66 """Map a name and an email to the preferred name and email.
68 :param name: the current name
69 :param email: the current email
70 :result: the preferred name and email
71 """
72 try:
73 new_name, new_email = self._user_map[(name, email)]
74 except KeyError:
75 new_name = name
76 if self._default_domain and not email:
77 new_email = "%s@%s" % (name, self._default_domain)
78 else:
79 new_email = email
80 #print "converted '%s <%s>' to '%s <%s>'" % (name, email, new_name, new_email)
81 return new_name, new_email