Debian Codegraph @

pecan/scaffolds/__init__.py

raw
1 import sys
2 import importlib.resources
3 import os
4 import re
5 from string import Template
6
7 DEFAULT_SCAFFOLD = 'base'
8 _bad_chars_re = re.compile('[^a-zA-Z0-9_]')
9
10
11 class PecanScaffold(object):
12 """
13 A base Pecan scaffold. New scaffolded implementations should extend this
14 class and define a ``_scaffold_dir`` attribute, e.g.,
15
16 class CoolAddOnScaffold(PecanScaffold):
17
18 _scaffold_dir = ('package', os.path.join('scaffolds', 'scaffold_name'))
19
20 ...where...
21
22 importlib.resources.files(_scaffold_dir[0]).joinpath(_scaffold_dir[1])
23
24 ...points to some scaffold directory root.
25 """
26
27 def normalize_output_dir(self, dest):
28 return os.path.abspath(os.path.normpath(dest))
29
30 def normalize_pkg_name(self, dest):
31 return _bad_chars_re.sub('', dest.lower())
32
33 def copy_to(self, dest, **kw):
34 output_dir = self.normalize_output_dir(dest)
35 pkg_name = self.normalize_pkg_name(dest)
36 copy_dir(self._scaffold_dir, output_dir, {'package': pkg_name}, **kw)
37
38
39 class BaseScaffold(PecanScaffold):
40 _scaffold_dir = ('pecan', os.path.join('scaffolds', 'base'))
41
42
43 class RestAPIScaffold(PecanScaffold):
44 _scaffold_dir = ('pecan', os.path.join('scaffolds', 'rest-api'))
45
46
47 def copy_dir(source, dest, variables, out_=sys.stdout, i=0):
48 """
49 Copies the ``source`` directory to the ``dest`` directory, where
50 ``source`` is some tuple representing an installed package and a
51 subdirectory in the package, e.g.,
52
53 ('pecan', os.path.join('scaffolds', 'base'))
54 ('pecan_extension', os.path.join('scaffolds', 'scaffold_name'))
55
56 ``variables``: A dictionary of variables to use in any substitutions.
57 Substitution is performed via ``string.Template``.
58
59 ``out_``: File object to write to (default is sys.stdout).
60 """
61 def out(msg):
62 out_.write('%s%s' % (' ' * (i * 2), msg))
63 out_.write('\n')
64 out_.flush()
65
66 if not os.path.exists(dest):
67 out('Creating %s' % dest)
68 makedirs(dest)
69 else:
70 out('%s already exists' % dest)
71 return
72
73 data_dir = importlib.resources.files(source[0])
74 for path in data_dir.joinpath(source[1]).iterdir():
75
76 full = os.path.join(source[1], path.name)
77 dest_full = os.path.join(
78 dest, substitute_filename(path.name, variables))
79
80 sub_file = False
81 if dest_full.endswith('_tmpl'):
82 dest_full = dest_full[:-5]
83 sub_file = True
84
85 if (data_dir.joinpath(full)).is_dir():
86 out('Recursing into %s' % os.path.basename(full))
87 copy_dir((source[0], full), dest_full, variables, out_, i + 1)
88 continue
89 else:
90 content = importlib.resources.files(source[0]).joinpath(full)\
91 .read_bytes()
92
93 if sub_file:
94 content = render_template(content, variables)
95 if content is None:
96 continue # pragma: no cover
97
98 out('Copying %s to %s' % (full, dest_full))
99
100 f = open(dest_full, 'wb')
101 f.write(content)
102 f.close()
103
104
105 def makedirs(directory):
106 """ Resursively create a named directory. """
107 parent = os.path.dirname(os.path.abspath(directory))
108 if not os.path.exists(parent):
109 makedirs(parent)
110 os.mkdir(directory)
111
112
113 def substitute_filename(fn, variables):
114 """ Substitute +variables+ in file directory names. """
115 for var, value in variables.items():
116 fn = fn.replace('+%s+' % var, str(value))
117 return fn
118
119
120 def render_template(content, variables):
121 """
122 Return a bytestring representing a templated file based on the
123 input (content) and the variable names defined (vars).
124 """
125 fsenc = sys.getfilesystemencoding()
126
127 def to_native(s, encoding='latin-1', errors='strict'):
128 if isinstance(s, str):
129 return s
130 return str(s, encoding, errors)
131
132 output = Template(
133 to_native(content, fsenc)
134 ).substitute(variables)
135 if isinstance(output, str):
136 output = output.encode(fsenc, 'strict')
137 return output