Repair `stg log` with patches from subdir
[stgit.git] / stgit / templates.py
blob23f4096cb3968f5078c97b3e7ee2796619f0ddec
1 """Template files look-up"""
3 import io
4 import os
5 import sys
7 from stgit.run import Run
9 __copyright__ = """
10 Copyright (C) 2006, Catalin Marinas <catalin.marinas@gmail.com>
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License version 2 as
14 published by the Free Software Foundation.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, see http://www.gnu.org/licenses/.
23 """
26 def get_template(tfile):
27 """Return the string in the template file passed as argument or
28 None if the file wasn't found.
29 """
30 tmpl_dirs = [
31 Run('git', 'rev-parse', '--git-dir').output_one_line(),
32 os.path.join(os.path.expanduser('~'), '.stgit', 'templates'),
33 os.path.join(sys.prefix, 'share', 'stgit', 'templates'),
34 os.path.join(os.path.dirname(__file__), 'templates'),
37 for d in tmpl_dirs:
38 tmpl_path = os.path.join(d, tfile)
39 if os.path.isfile(tmpl_path):
40 with io.open(tmpl_path, 'r') as f:
41 return f.read()
42 else:
43 return None
46 def specialize_template(tmpl, tmpl_dict):
47 """Specialize template string using template dict.
49 Returns specialized template as bytes.
51 Since Python 3.3 and 3.4 do not support the interpolation operator (%) on
52 bytes objects; and since we expect at least one tmpl_dict value (diff) to
53 be bytes (not str); we use a recursive approach to specialize the str
54 specifiers using normal interpolation while handling interpolation of bytes
55 values ourselves.
57 """
58 for k, v in tmpl_dict.items():
59 if v is None:
60 tmpl_dict[k] = ''
61 elif isinstance(v, bytes):
62 tmpl_dict.pop(k)
63 return v.join(
64 specialize_template(part, tmpl_dict)
65 for part in tmpl.split('%%(%s)s' % k)
67 else:
68 return (tmpl % tmpl_dict).encode('utf-8')