1 # Copyright (C) 2012 W. Trevor King <wking@tremily.us>
3 # This file is part of update-copyright.
5 # update-copyright is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option) any
10 # update-copyright is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 # You should have received a copy of the GNU General Public License along with
16 # update-copyright. If not, see <http://www.gnu.org/licenses/>.
18 """Useful utilities for backend classes."""
20 import email.utils as _email_utils
21 import os.path as _os_path
22 import subprocess as _subprocess
25 from .. import LOG as LOG
26 from ..utils import ENCODING as _ENCODING
29 _MSWINDOWS = _sys.platform == 'win32'
30 _POSIX = not _MSWINDOWS
33 def invoke(args, stdin=None, stdout=_subprocess.PIPE, stderr=_subprocess.PIPE,
34 cwd=None, expect=(0,), unicode_output=False, encoding=None):
35 """Invoke an external program and return the results
37 ``expect`` should be a tuple of allowed exit codes.
39 When ``unicode_output`` is ``True``, convert stdout and stdin
40 strings to unicode before returing them.
42 LOG.debug('{}$ {}'.format(cwd, args))
45 q = _subprocess.Popen(args, stdin=_subprocess.PIPE,
46 stdout=stdout, stderr=stderr,
47 close_fds=True, cwd=cwd)
49 assert _MSWINDOWS == True, 'invalid platform'
50 # win32 don't have os.execvp() so run the command in a shell
51 q = _subprocess.Popen(args, stdin=_subprocess.PIPE,
52 stdout=stdout, stderr=stderr, shell=True,
55 raise ValueError([args, e])
56 stdout,stderr = q.communicate(input=stdin)
58 if unicode_output == True:
61 if stdout is not None:
62 stdout = unicode(stdout, encoding)
63 if stderr is not None:
64 stderr = unicode(stderr, encoding)
65 if status not in expect:
66 raise ValueError([args, status, stdout, stderr])
67 return status, stdout, stderr
70 """Recursively split a path into elements.
76 >>> splitpath(os.path.join('a', 'b', 'c'))
78 >>> splitpath(os.path.join('.', 'a', 'b', 'c'))
81 path = _os_path.normpath(path)
84 dirname,basename = _os_path.split(path)
85 elements.insert(0,basename)
86 if dirname in ['/', '', '.']:
89 return tuple(elements)
91 def strip_email(*args):
92 """Remove email addresses from a series of names.
97 >>> strip_email('J Doe')
99 >>> strip_email('J Doe <jdoe@a.com>')
101 >>> strip_email('J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>')
102 ['J Doe', 'JJJ Smith']
105 for i,arg in enumerate(args):
108 author,addr = _email_utils.parseaddr(arg)
114 def reverse_aliases(aliases):
115 """Reverse an `aliases` dict.
117 Input: key: canonical name, value: list of aliases
118 Output: key: alias, value: canonical name
124 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>', 'J'],
125 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
126 ... None:['Anonymous <a@a.com>'],
128 >>> r = reverse_aliases(aliases)
129 >>> for item in sorted(r.items()):
131 ('Anonymous <a@a.com>', None)
132 ('J', 'J Doe <jdoe@a.com>')
133 ('Jingly <jjjs@b.edu>', 'JJJ Smith <jjjs@a.com>')
134 ('Johnny <jdoe@b.edu>', 'J Doe <jdoe@a.com>')
137 for canonical_name,_aliases in aliases.items():
138 for alias in _aliases:
139 output[alias] = canonical_name
142 def replace_aliases(authors, with_email=True, aliases=None):
143 """Consolidate and sort `authors`.
145 Make the replacements listed in the `aliases` dict (key: canonical
146 name, value: list of aliases). If `aliases` is ``None``, default
150 ... 'J Doe <jdoe@a.com>':['Johnny <jdoe@b.edu>'],
151 ... 'JJJ Smith <jjjs@a.com>':['Jingly <jjjs@b.edu>'],
152 ... None:['Anonymous <a@a.com>'],
155 ... 'JJJ Smith <jjjs@a.com>', 'Johnny <jdoe@b.edu>',
156 ... 'Jingly <jjjs@b.edu>', 'J Doe <jdoe@a.com>', 'Anonymous <a@a.com>']
157 >>> replace_aliases(authors, with_email=True, aliases=aliases)
158 ['J Doe <jdoe@a.com>', 'JJJ Smith <jjjs@a.com>']
159 >>> replace_aliases(authors, with_email=False, aliases=aliases)
160 ['J Doe', 'JJJ Smith']
164 rev_aliases = reverse_aliases(aliases)
165 for i,author in enumerate(authors):
166 if author in rev_aliases:
167 authors[i] = rev_aliases[author]
168 authors = sorted(list(set(authors)))
171 if with_email == False:
172 authors = strip_email(*authors)