1
# Copyright 2012-2014 Canonical Ltd. This software is licensed under the
2
# GNU Affero General Public License version 3 (see the file LICENSE).
4
"""Low-level routines for access to snippets.
6
These are used by the user-data code, but also by `setup.py`. That's why
7
importing this must not pull in any unnecessary framework modules etc.
10
from __future__ import (
23
'get_snippet_context',
24
'get_userdata_template_dir',
29
from provisioningserver.utils import locate_config
30
from provisioningserver.utils.fs import read_text_file
33
USERDATA_BASE_DIR = 'templates/commissioning-user-data'
36
def get_userdata_template_dir():
37
"""Return the absolute location of the userdata
38
template directory."""
39
return locate_config(USERDATA_BASE_DIR)
42
def get_snippet_context(snippets_dir=None, encoding='utf-8'):
43
"""Return the context of all of the snippets."""
44
if snippets_dir is None:
45
snippets_dir = os.path.join(get_userdata_template_dir(), 'snippets')
47
strip_name(name): read_snippet(snippets_dir, name, encoding=encoding)
48
for name in list_snippets(snippets_dir)
53
def read_snippet(snippets_dir, name, encoding='utf-8'):
54
"""Read a snippet file.
58
return read_text_file(os.path.join(snippets_dir, name), encoding=encoding)
61
def is_snippet(filename):
62
"""Does `filename` represent a valid snippet name?"""
64
not filename.startswith('.'),
65
filename != '__init__.py',
67
not filename.endswith('.pyc'),
68
not filename.endswith('~'),
72
def list_snippets(snippets_dir):
73
"""List names of available snippets."""
74
return filter(is_snippet, os.listdir(snippets_dir))
77
def strip_name(snippet_name):
78
"""Canonicalize a snippet name."""
79
# Dot suffixes do not work well in tempita variable names.
80
return snippet_name.replace('.', '_')