OLD | NEW |
| (Empty) |
1 # Copyright (c) 2013 The Chromium Authors. All rights reserved. | |
2 # Use of this source code is governed by a BSD-style license that can be | |
3 # found in the LICENSE file. | |
4 | |
5 import collections | |
6 import email.utils | |
7 | |
8 | |
9 def lazy_property(func): | |
10 """A decorator for lazy properties.""" | |
11 name = '__lazy_' + func.__name__ | |
12 | |
13 def get_property(self, *args, **kwargs): | |
14 if not hasattr(self, name): | |
15 setattr(self, name, func(self, *args, **kwargs)) | |
16 return getattr(self, name) | |
17 | |
18 return property(get_property) | |
19 | |
20 | |
21 class LazyDict(collections.Mapping): | |
22 """A simple immutable and lazy dictionary. | |
23 | |
24 This looks up the actual key values on first access to the key and caches the | |
25 value to speed up subsequent accesses. | |
26 """ | |
27 | |
28 def __init__(self, lookup_fn): | |
29 self.items = {} | |
30 self.lookup = lookup_fn | |
31 | |
32 def __getitem__(self, name): | |
33 if name not in self.items.keys(): | |
34 self.items[name] = self.lookup(name) | |
35 return self.items[name] | |
36 | |
37 def __iter__(self): | |
38 return self.items.iterkeys() | |
39 | |
40 def __len__(self): | |
41 return len(self.items) | |
42 | |
43 def __repr__(self): | |
44 return repr(self.items) | |
45 | |
46 | |
47 class ObjectDict(collections.Mapping): | |
48 """Wraps a dictionary to allow value retrieval in dot notation.""" | |
49 | |
50 def __init__(self, data): | |
51 self.__data = data | |
52 | |
53 def __getitem__(self, name): | |
54 val = self.__data[name] | |
55 return ObjectDict.wrap(val) | |
56 | |
57 def __getattr__(self, name): | |
58 try: | |
59 return self[name] | |
60 except KeyError as e: | |
61 raise AttributeError(e) | |
62 | |
63 def __iter__(self): | |
64 return self.__data.iterkeys() | |
65 | |
66 def __len__(self): | |
67 return len(self.__data) | |
68 | |
69 def __repr__(self): | |
70 return repr(self.__data) | |
71 | |
72 @staticmethod | |
73 def wrap(val): | |
74 if isinstance(val, dict): | |
75 return ObjectDict(val) | |
76 return val | |
77 | |
78 | |
79 def get_emails(string): | |
80 """Normalizes a string containing a list of email recepients. | |
81 | |
82 Takes a string in the format present in mail headers and returns a list of | |
83 email addresses. For example, the input | |
84 'test@example.com, committers <committers@chromium.org> | |
85 will produce this return value: | |
86 [ 'test@example.com', 'committers@chromium.org' ] | |
87 """ | |
88 return [entry[1] for entry in email.utils.getaddresses([string])] | |
89 | |
90 | |
91 def canonicalize_email(address): | |
92 """Takes an email address and returns its canonicalized form.""" | |
93 emails = get_emails(address) | |
94 assert len(emails) == 1 | |
95 return emails[0] | |
OLD | NEW |