Add initial code
[ta/build-tools.git] / tools / script / generate_repo_files.py
1 # Copyright 2019 Nokia
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain 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,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import os
16 import sys
17 import argparse
18 import logging
19
20 from tools.buildconfig import BuildConfigParser
21
22
23 def _parse(args):
24     parser = argparse.ArgumentParser(description='Generate repo files from config ini sections')
25     parser.add_argument('config_sections', metavar='config_section', nargs='+',
26                         help='Config ini section')
27     parser.add_argument('--output-dir', '-d', required=True,
28                         help='Directory to output the repo files')
29     parser.add_argument('--config-ini', '-c', required=True,
30                         help='Path to the config ini to read')
31     args = parser.parse_args(args)
32     return args
33
34
35 class RepoGen(object):
36
37     def __init__(self, output_dir, config_ini, config_sections):
38         self.output_dir = output_dir
39         self.config_sections = config_sections
40         self.config = BuildConfigParser(ini_file=config_ini)
41
42     def run(self):
43         for section in self.config_sections:
44             repo_file_path = os.path.join(self.output_dir, section + '.repo')
45             self._write_repo_file(section, repo_file_path)
46
47     def _write_repo_file(self, section, repo_file_path):
48         with open(repo_file_path, 'w') as f:
49             for repo in self.config.items(section):
50                 name = repo[0]
51                 parts = repo[1].split('#')
52                 url = parts[0]
53                 f.write('[%s]\n' % name)
54                 f.write('name=%s\n' % name)
55                 f.write('baseurl=%s\n' % url)
56                 f.write('enabled=1\n')
57                 f.write('gpgcheck=0\n')
58                 for part in parts[1:]:
59                     f.write('%s\n' % part)
60                 f.write('\n')
61         if os.path.getsize(repo_file_path) == 0:
62             logging.error('Zero size output: {}'.format(repo_file_path))
63             sys.exit(1)
64         logging.info('Wrote repo: {}'.format(repo_file_path))
65
66
67 def main(input_args):
68     logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
69     args = _parse(input_args)
70     RepoGen(args.output_dir, args.config_ini, args.config_sections).run()
71
72
73 if __name__ == "__main__":
74     main(sys.argv[1:])