barectf: reflow licence headers for 72 columns
[deliverable/barectf.git] / barectf / cli.py
CommitLineData
dcdbb941
PP
1# The MIT License (MIT)
2#
4a90140d 3# Copyright (c) 2014-2020 Philippe Proulx <pproulx@efficios.com>
dcdbb941 4#
1378f213
PP
5# Permission is hereby granted, free of charge, to any person obtaining
6# a copy of this software and associated documentation files (the
7# "Software"), to deal in the Software without restriction, including
8# without limitation the rights to use, copy, modify, merge, publish,
9# distribute, sublicense, and/or sell copies of the Software, and to
10# permit persons to whom the Software is furnished to do so, subject to
11# the following conditions:
dcdbb941 12#
1378f213
PP
13# The above copyright notice and this permission notice shall be
14# included in all copies or substantial portions of the Software.
dcdbb941 15#
1378f213
PP
16# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0f5c653b 23
79750125 24from pkg_resources import resource_filename
dcdbb941 25from termcolor import cprint, colored
e5aa0be3
PP
26import barectf.tsdl182gen
27import barectf.config
28import barectf.gen
e9094528 29import argparse
e5aa0be3 30import os.path
0f5c653b 31import barectf
dcdbb941
PP
32import sys
33import os
34import re
35
36
e5aa0be3
PP
37def _perror(msg):
38 cprint('Error: ', 'red', end='', file=sys.stderr)
39 cprint(msg, 'red', attrs=['bold'], file=sys.stderr)
40 sys.exit(1)
dcdbb941
PP
41
42
6b5a6c2f 43def _pconfig_error(exc):
e5aa0be3
PP
44 cprint('Error:', 'red', file=sys.stderr)
45
6b5a6c2f
PP
46 for ctx in reversed(exc.ctx):
47 if ctx.msg is not None:
48 msg = ' {}'.format(ctx.msg)
49 else:
50 msg = ''
51 cprint(' {}:{}'.format(ctx.name, msg), 'red', attrs=['bold'],
52 file=sys.stderr)
e5aa0be3
PP
53
54 sys.exit(1)
6b1365c7
PP
55
56
57def _psuccess(msg):
58 cprint('{}'.format(msg), 'green', attrs=['bold'])
dcdbb941
PP
59
60
61def _parse_args():
62 ap = argparse.ArgumentParser()
63
e5aa0be3
PP
64 ap.add_argument('-c', '--code-dir', metavar='DIR', action='store',
65 default=os.getcwd(),
66 help='output directory of C source file')
f58be68f
PP
67 ap.add_argument('--dump-config', action='store_true',
68 help='also dump the effective YAML configuration file used for generation')
e5aa0be3
PP
69 ap.add_argument('-H', '--headers-dir', metavar='DIR', action='store',
70 default=os.getcwd(),
71 help='output directory of C header files')
f58be68f
PP
72 ap.add_argument('-I', '--include-dir', metavar='DIR', action='append',
73 default=[],
74 help='add directory DIR to the list of directories to be searched for include files')
75 ap.add_argument('--ignore-include-not-found', action='store_true',
76 help='continue to process the configuration file when included files are not found')
e5aa0be3 77 ap.add_argument('-m', '--metadata-dir', metavar='DIR', action='store',
dcdbb941 78 default=os.getcwd(),
e5aa0be3 79 help='output directory of CTF metadata')
dcdbb941 80 ap.add_argument('-p', '--prefix', metavar='PREFIX', action='store',
e5aa0be3 81 help='override configuration\'s prefix')
0f5c653b 82 ap.add_argument('-V', '--version', action='version',
e5aa0be3
PP
83 version='%(prog)s {}'.format(barectf.__version__))
84 ap.add_argument('config', metavar='CONFIG', action='store',
85 help='barectf YAML configuration file')
dcdbb941
PP
86
87 # parse args
88 args = ap.parse_args()
89
e5aa0be3 90 # validate output directories
f58be68f 91 for d in [args.code_dir, args.headers_dir, args.metadata_dir] + args.include_dir:
e5aa0be3 92 if not os.path.isdir(d):
1bf9d86d 93 _perror('`{}` is not an existing directory'.format(d))
dcdbb941 94
e5aa0be3
PP
95 # validate that configuration file exists
96 if not os.path.isfile(args.config):
1bf9d86d 97 _perror('`{}` is not an existing, regular file'.format(args.config))
dcdbb941 98
79750125
PP
99 # append current working directory and provided include directory
100 args.include_dir += [os.getcwd(), resource_filename(__name__, 'include')]
101
dcdbb941
PP
102 return args
103
104
e5aa0be3
PP
105def _write_file(d, name, content):
106 with open(os.path.join(d, name), 'w') as f:
107 f.write(content)
e9094528 108
67bd189f 109
e5aa0be3
PP
110def run():
111 # parse arguments
112 args = _parse_args()
8a70d9fb 113
e5aa0be3
PP
114 # create configuration
115 try:
7f4429f2
PP
116 config = barectf.config.from_file(args.config, args.include_dir,
117 args.ignore_include_not_found,
118 args.dump_config)
119 except barectf.config.ConfigParseError as e:
e5aa0be3
PP
120 _pconfig_error(e)
121 except Exception as e:
f74236f8
PP
122 import traceback
123
124 traceback.print_exc()
79659d8e 125 _perror('Unknown exception: {}'.format(e))
6b1365c7 126
e5aa0be3
PP
127 # replace prefix if needed
128 if args.prefix:
7f4429f2
PP
129 config = barectf.config.Config(config.metadata,
130 args.prefix,
131 config.options)
e5aa0be3
PP
132
133 # generate metadata
134 metadata = barectf.tsdl182gen.from_metadata(config.metadata)
135
136 try:
137 _write_file(args.metadata_dir, 'metadata', metadata)
138 except Exception as e:
79659d8e 139 _perror('Cannot write metadata file: {}'.format(e))
e5aa0be3
PP
140
141 # create generator
142 generator = barectf.gen.CCodeGenerator(config)
143
144 # generate C headers
145 header = generator.generate_header()
146 bitfield_header = generator.generate_bitfield_header()
147
148 try:
149 _write_file(args.headers_dir, generator.get_header_filename(), header)
150 _write_file(args.headers_dir, generator.get_bitfield_header_filename(),
151 bitfield_header)
152 except Exception as e:
79659d8e 153 _perror('Cannot write header files: {}'.format(e))
e5aa0be3
PP
154
155 # generate C source
156 c_src = generator.generate_c_src()
157
158 try:
159 _write_file(args.code_dir, '{}.c'.format(config.prefix.rstrip('_')),
160 c_src)
161 except Exception as e:
79659d8e 162 _perror('Cannot write C source file: {}'.format(e))
This page took 0.041728 seconds and 4 git commands to generate.