6c9b000b34761ea0fb510f42fcab72c45aa5aa0c
[osm/devops.git] / descriptor-packages / tools / charm-generator / generator / generators / metadata_generator.py
1 # Copyright 2019 Whitestack, LLC
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14 #
15 # For those usages not covered by the Apache License, Version 2.0 please
16 # contact: esousa@whitestack.com or glavado@whitestack.com
17 ##
18
19 import functools
20 import logging
21 import os
22 import sys
23
24 import yaml
25
26 from jinja2 import Environment, PackageLoader
27
28
29 class MetadataGenerator:
30 LOGGER = logging.getLogger()
31 ENV = Environment(loader=PackageLoader('generator.metadata', 'templates'))
32
33 def __init__(self, metadata, license=None, options=None):
34 """
35 Creates the object to generate the metadata.yaml file from a template.
36
37 Usage should be:
38
39 1) Create the object.
40 2) Run the generate method.
41
42 :param metadata: metadata information about the charm being generated.
43 :param license: information license to included in the charm being generated.
44 :param options: options to override the normal flow.
45 """
46 self.path = os.getcwd()
47 self.metadata = metadata
48 self.license = license
49 self.options = options
50
51 def generate(self):
52 """
53 Generates the metadata.yaml using templates.
54 """
55 MetadataGenerator.LOGGER.info('Generating the metadata.yaml...')
56
57 standard_metadata = self._read_metadata_yaml()
58 self._update_metadata(standard_metadata)
59 self._rename_metadata_yaml_as_backup()
60 self._write_metadata_yaml()
61
62 MetadataGenerator.LOGGER.info('Generated the metadata.yaml.')
63
64 def get_metadata(self):
65 """
66 Gets the enhanced metadata.
67
68 :return: the enhanced metadata dictionary.
69 """
70 return self.metadata
71
72 def _read_metadata_yaml(self):
73 """
74 Reads the values from the old metadata.yaml and does a cleanup on undesired values.
75 """
76 MetadataGenerator.LOGGER.debug('Reading old metadata.yaml...')
77
78 metadata_yaml_path = self.path + '/metadata.yaml'
79
80 if not os.path.isfile(metadata_yaml_path):
81 MetadataGenerator.LOGGER.error('metadata.yaml must be present. Must be run in the root of the charm')
82 sys.exit(-1)
83
84 with open(metadata_yaml_path, 'r') as f:
85 metadata = yaml.load(f)
86
87 if 'tags' in metadata.keys():
88 del metadata['tags']
89 if 'provides' in metadata.keys():
90 del metadata['provides']
91 if 'requires' in metadata.keys():
92 del metadata['requires']
93 if 'peers' in metadata.keys():
94 del metadata['peers']
95
96 MetadataGenerator.LOGGER.debug('Read old metadata.yaml.')
97
98 return metadata
99
100 def _update_metadata(self, metadata):
101 """
102 Update internal metadata before writing the new metadata.yaml.
103
104 :param metadata: metadata values provided by the user.
105 """
106 MetadataGenerator.LOGGER.debug('Generating the Ansible Charm...')
107
108 if 'name' in metadata:
109 self.metadata['name'] = metadata['name']
110 self.metadata['file'] = '%s.py' % metadata['name'].replace('-', '_')
111
112 self.metadata['subordinate'] = False
113 self.metadata['tags'] = ['misc', 'osm', 'vnf']
114 self.metadata['series'] = ['xenial', 'trusty']
115
116 MetadataGenerator.LOGGER.debug('Generating the Ansible Charm...')
117
118 def _rename_metadata_yaml_as_backup(self):
119 """
120 Renames the metadata.yaml to metadata.yaml.bkp.*.
121 Preserves the history of the charm for the user.
122 """
123 MetadataGenerator.LOGGER.debug('Renaming the metadata.yaml to .bkp.*...')
124
125 metadata_yaml_path = self.path + '/metadata.yaml'
126
127 ids = [int(f.split('.')[-1]) for f in os.listdir(self.path)
128 if f.startswith('metadata.yaml.bkp')]
129
130 id = 0
131 if ids:
132 id = functools.reduce(lambda x, y: x if (x > y) else y, ids)
133 id += 1
134
135 backup_metadata_yaml_path = self.path + ('/metadata.yaml.bkp.%02d' % id)
136 os.rename(metadata_yaml_path, backup_metadata_yaml_path)
137
138 MetadataGenerator.LOGGER.debug('Renamed the metadata.yaml to .bkp.%02d.', id)
139
140 def _write_metadata_yaml(self):
141 """
142 Writes the enriched metadata to metadata.yaml.
143 """
144 MetadataGenerator.LOGGER.debug('Generating metadata.yaml...')
145
146 metadata_yaml_path = self.path + '/metadata.yaml'
147 metadata_yaml_template = MetadataGenerator.ENV.get_template('metadata.yaml.j2')
148
149 with open(metadata_yaml_path, 'w') as f:
150 f.write(metadata_yaml_template.render(metadata=self.metadata, license=self.license))
151
152 MetadataGenerator.LOGGER.debug('Generated metadata.yaml.')