CI: do apt-get update before install
[stgit.git] / stgit / templates.py
blob6204643bc53401dd6938d402cc69e5ded92fd79e
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 """Get template string from named template file.
29 Several template locations are searched for the named template. If found, the
30 content of the template is returned, otherwise None is returned if the template is
31 not found.
33 """
34 tmpl_dirs = [
35 Run('git', 'rev-parse', '--git-dir').output_one_line(),
36 os.path.join(os.path.expanduser('~'), '.stgit', 'templates'),
37 os.path.join(sys.prefix, 'share', 'stgit', 'templates'),
38 os.path.join(os.path.dirname(__file__), 'templates'),
41 for d in tmpl_dirs:
42 tmpl_path = os.path.join(d, tfile)
43 if os.path.isfile(tmpl_path):
44 with io.open(tmpl_path, 'r') as f:
45 return f.read()
46 else:
47 return None
50 def specialize_template(tmpl, tmpl_dict):
51 """Specialize template string using template dict.
53 Returns specialized template as bytes.
55 Since Python 3.3 and 3.4 do not support the interpolation operator (%) on
56 bytes objects; and since we expect at least one tmpl_dict value (diff) to
57 be bytes (not str); we use a recursive approach to specialize the str
58 specifiers using normal interpolation while handling interpolation of bytes
59 values ourselves.
61 """
62 for k, v in tmpl_dict.items():
63 if v is None:
64 tmpl_dict[k] = ''
65 elif isinstance(v, bytes):
66 tmpl_dict.pop(k)
67 return v.join(
68 specialize_template(part, tmpl_dict)
69 for part in tmpl.split('%%(%s)s' % k)
71 else:
72 return (tmpl % tmpl_dict).encode('utf-8')