3
# Copyright (C) 2014 Canonical Ltd.
5
# This program is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation, either version 3 of the License, or
8
# (at your option) any later version.
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
# GNU General Public License for more details.
15
# You should have received a copy of the GNU General Public License
16
# along with this program. If not, see <http://www.gnu.org/licenses/>.
20
import os.path as path
26
from Cheetah.Template import Template
27
from stat import ST_MODE
29
from charmtools.generators import (
33
log = logging.getLogger(__name__)
36
class AnsibleCharmTemplate(CharmTemplate):
37
skip_parsing = ['README.ex', 'Makefile']
39
def create_charm(self, config, output_dir):
40
self._copy_files(output_dir)
42
for root, dirs, files in os.walk(output_dir):
44
if outfile in self.skip_parsing:
47
self._template_file(config, path.join(root, outfile))
49
self._cleanup_hooks(config, output_dir)
50
self._install_charmhelpers(output_dir)
52
def _copy_files(self, output_dir):
53
here = path.abspath(path.dirname(__file__))
54
template_dir = path.join(here, 'files')
55
if os.path.exists(output_dir):
56
shutil.rmtree(output_dir)
57
shutil.copytree(template_dir, output_dir)
59
def _template_file(self, config, outfile):
60
if path.islink(outfile):
63
mode = os.stat(outfile)[ST_MODE]
64
t = Template(file=outfile, searchList=(config))
65
o = tempfile.NamedTemporaryFile(
66
dir=path.dirname(outfile), delete=False)
67
os.chmod(o.name, mode)
70
backupname = outfile + str(time.time())
71
os.rename(outfile, backupname)
72
os.rename(o.name, outfile)
75
def _cleanup_hooks(self, config, output_dir):
76
# Symlinks must be relative so that they are copied properly
77
# when output_dir is moved to it's final location.
78
for link in ['config-changed', 'install', 'start', 'stop',
80
os.symlink('hooks.py', os.path.join(output_dir, 'hooks', link))
82
def _install_charmhelpers(self, output_dir):
83
helpers_dest = os.path.join(output_dir, 'lib', 'charmhelpers')
84
if not os.path.exists(helpers_dest):
85
os.makedirs(helpers_dest)
87
cmd = './scripts/charm_helpers_sync.py -c charm-helpers.yaml'
88
subprocess.check_call(cmd.split(), cwd=output_dir)