1 # The MIT License (MIT)
3 # Copyright (c) 2014-2020 Philippe Proulx <pproulx@efficios.com>
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:
13 # The above copyright notice and this permission notice shall be
14 # included in all copies or substantial portions of the Software.
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.
30 import barectf
.config_parse_common
as barectf_config_parse_common
31 import barectf
.argpar
as barectf_argpar
36 # Colors and prints the error message `msg` and exits with status code
38 def _print_error(msg
):
39 termcolor
.cprint('Error: ', 'red', end
='', file=sys
.stderr
)
40 termcolor
.cprint(msg
, 'red', attrs
=['bold'], file=sys
.stderr
)
44 # Pretty-prints the barectf configuration error `exc` and exits with
46 def _print_config_error(exc
):
47 # reverse: most precise message comes last
48 for ctx
in reversed(exc
.context
):
51 if ctx
.message
is not None:
52 msg
= f
' {ctx.message}'
55 termcolor
.cprint(f
'{ctx.name}', color
, attrs
=['bold'], file=sys
.stderr
, end
='')
56 termcolor
.cprint(':', color
, file=sys
.stderr
, end
='')
57 termcolor
.cprint(msg
, color
, file=sys
.stderr
)
62 # Pretty-prints the unknown exception `exc`.
63 def _print_unknown_exc(exc
):
67 _print_error(f
'Unknown exception: {exc}')
70 # Finds and returns all the option items in `items` having the long name
72 def _find_opt_items(items
, long_name
):
76 if type(item
) is barectf_argpar
._OptItem
and item
.descr
.long_name
== long_name
:
77 ret_items
.append(item
)
84 # For an option item without an argument:
87 # For an option item with an argument:
90 # Uses the last option item having the long name `long_name` found in
93 # Returns `default` if there's no such option item.
94 def _opt_item_val(items
, long_name
, default
=None):
95 opt_items
= _find_opt_items(items
, long_name
)
97 if len(opt_items
) == 0:
100 opt_item
= opt_items
[-1]
102 if opt_item
.descr
.has_arg
:
103 return opt_item
.arg_text
108 class _CliError(Exception):
112 def _cfg_file_path_from_parse_res(parse_res
):
115 for item
in parse_res
.items
:
116 if type(item
) is barectf_argpar
._NonOptItem
:
117 if cfg_file_path
is not None:
118 raise _CliError('Multiple configuration file paths provided')
120 cfg_file_path
= item
.text
122 if cfg_file_path
is None:
123 raise _CliError('Missing configuration file path')
125 if not os
.path
.isfile(cfg_file_path
):
126 raise _CliError(f
'`{cfg_file_path}` is not an existing, regular file')
131 # Returns a `_CfgCmdCfg` object from the command-line parsing results
133 def _cfg_cmd_cfg_from_parse_res(parse_res
):
134 # check configuration file path
135 cfg_file_path
= _cfg_file_path_from_parse_res(parse_res
)
137 # inclusion directories
138 inclusion_dirs
= [item
.arg_text
for item
in _find_opt_items(parse_res
.items
, 'include-dir')]
140 for dir in inclusion_dirs
:
141 if not os
.path
.isdir(dir):
142 raise _CliError(f
'`{dir}` is not an existing directory')
144 inclusion_dirs
.append(os
.getcwd())
147 ignore_inclusion_file_not_found
= _opt_item_val(parse_res
.items
, 'ignore-include-not-found',
150 return _CfgCmdCfg(cfg_file_path
, inclusion_dirs
, ignore_inclusion_file_not_found
)
153 def _print_gen_cmd_usage():
154 print('''Usage: barectf generate [--code-dir=DIR] [--headers-dir=DIR]
155 [--metadata-dir=DIR] [--prefix=PREFIX]
156 [--include-dir=DIR]... [--ignore-include-not-found]
158 barectf generate --help
161 -c DIR, --code-dir=DIR Write C source files to DIR instead of the CWD
162 -H DIR, --headers-dir=DIR Write C header files to DIR instead of the CWD
163 -h, --help Show this help and quit
164 --ignore-include-not-found Continue to process the configuration file when
165 included files are not found
166 -I DIR, --include-dir=DIR Add DIR to the list of directories to be
167 searched for inclusion files
168 -m DIR, --metadata-dir=DIR Write the metadata stream file to DIR instead of
170 -p PREFIX, --prefix=PREFIX Set the configuration prefix to PREFIX''')
173 # Returns a source and metadata stream file generating command object
174 # from the specific command-line arguments `orig_args`.
175 def _gen_cmd_cfg_from_args(orig_args
):
176 # parse original arguments
178 barectf_argpar
.OptDescr('h', 'help'),
179 barectf_argpar
.OptDescr('c', 'code-dir', True),
180 barectf_argpar
.OptDescr('H', 'headers-dir', True),
181 barectf_argpar
.OptDescr('I', 'include-dir', True),
182 barectf_argpar
.OptDescr('m', 'metadata-dir', True),
183 barectf_argpar
.OptDescr('p', 'prefix', True),
184 barectf_argpar
.OptDescr(long_name
='dump-config'),
185 barectf_argpar
.OptDescr(long_name
='ignore-include-not-found'),
187 res
= barectf_argpar
.parse(orig_args
, opt_descrs
)
188 assert len(res
.ingested_orig_args
) == len(orig_args
)
191 if len(_find_opt_items(res
.items
, 'help')) > 0:
192 _print_gen_cmd_usage()
195 # get common configuration file command CLI configuration
196 cfg_cmd_cfg
= _cfg_cmd_cfg_from_parse_res(res
)
199 c_source_dir
= _opt_item_val(res
.items
, 'code-dir', os
.getcwd())
200 c_header_dir
= _opt_item_val(res
.items
, 'headers-dir', os
.getcwd())
201 metadata_stream_dir
= _opt_item_val(res
.items
, 'metadata-dir', os
.getcwd())
203 for dir in [c_source_dir
, c_header_dir
, metadata_stream_dir
]:
204 if not os
.path
.isdir(dir):
205 raise _CliError(f
'`{dir}` is not an existing directory')
208 dump_config
= _opt_item_val(res
.items
, 'dump-config', False)
209 v2_prefix
= _opt_item_val(res
.items
, 'prefix')
211 return _GenCmd(_GenCmdCfg(cfg_cmd_cfg
.cfg_file_path
, c_source_dir
, c_header_dir
,
212 metadata_stream_dir
, cfg_cmd_cfg
.inclusion_dirs
,
213 cfg_cmd_cfg
.ignore_inclusion_file_not_found
, dump_config
, v2_prefix
))
216 def _show_effective_cfg_cmd_usage():
217 print('''Usage: barectf show-effective-configuration [--include-dir=DIR]...
218 [--ignore-include-not-found]
219 [--indent-spaces=COUNT] CONFIG-FILE-PATH
220 barectf show-effective-configuration --help
223 -h, --help Show this help and quit
224 --ignore-include-not-found Continue to process the configuration file when
225 included files are not found
226 -I DIR, --include-dir=DIR Add DIR to the list of directories to be
227 searched for inclusion files
228 --indent-spaces=COUNT Use COUNT spaces at a time to indent YAML lines
232 # Returns an effective configuration showing command object from the
233 # specific command-line arguments `orig_args`.
234 def _show_effective_cfg_cfg_from_args(orig_args
):
235 # parse original arguments
237 barectf_argpar
.OptDescr('h', 'help'),
238 barectf_argpar
.OptDescr('I', 'include-dir', True),
239 barectf_argpar
.OptDescr(long_name
='indent-spaces', has_arg
=True),
240 barectf_argpar
.OptDescr(long_name
='ignore-include-not-found'),
242 res
= barectf_argpar
.parse(orig_args
, opt_descrs
)
243 assert len(res
.ingested_orig_args
) == len(orig_args
)
246 if len(_find_opt_items(res
.items
, 'help')) > 0:
247 _show_effective_cfg_cmd_usage()
250 # get common configuration command CLI configuration
251 cfg_cmd_cfg
= _cfg_cmd_cfg_from_parse_res(res
)
254 indent_space_count
= _opt_item_val(res
.items
, 'indent-spaces', 2)
257 indent_space_count
= int(indent_space_count
)
258 except (ValueError, TypeError):
259 raise _CliError(f
'Invalid `--indent-spaces` option argument: `{indent_space_count}`')
261 if indent_space_count
< 1 or indent_space_count
> 8:
262 raise _CliError(f
'Invalid `--indent-spaces` option argument (`{indent_space_count}`): expecting a value in [1, 8]')
264 return _ShowEffectiveCfgCmd(_ShowEffectiveCfgCmdCfg(cfg_cmd_cfg
.cfg_file_path
,
265 cfg_cmd_cfg
.inclusion_dirs
,
266 cfg_cmd_cfg
.ignore_inclusion_file_not_found
,
270 def _show_cfg_version_cmd_usage():
271 print('''Usage: barectf show-configuration-version CONFIG-FILE-PATH
272 barectf show-configuration-version --help
275 -h, --help Show this help and quit''')
278 # Returns a configuration version showing command object from the
279 # specific command-line arguments `orig_args`.
280 def _show_cfg_version_cfg_from_args(orig_args
):
281 # parse original arguments
283 barectf_argpar
.OptDescr('h', 'help'),
285 res
= barectf_argpar
.parse(orig_args
, opt_descrs
)
286 assert len(res
.ingested_orig_args
) == len(orig_args
)
289 if len(_find_opt_items(res
.items
, 'help')) > 0:
290 _show_cfg_version_cmd_usage()
293 # check configuration file path
294 cfg_file_path
= _cfg_file_path_from_parse_res(res
)
296 return _ShowCfgVersionCmd(_ShowCfgVersionCmdCfg(cfg_file_path
))
299 def _print_general_usage():
300 print('''Usage: barectf COMMAND COMMAND-ARGS
305 -h, --help Show this help and quit
306 -V, --version Show version and quit
311 Generate the C source and CTF metadata files of a tracer from a
314 show-effective-configuration:
315 show-effective-config:
317 Print the effective configuration file for a given configuration
318 file and inclusion directories.
320 show-configuration-version:
323 Print the major version of a given configuration file.
325 Run `barectf COMMAND --help` to show the help of COMMAND.''')
328 # Returns a command object from the command-line arguments `orig_args`.
330 # All the `orig_args` elements are considered.
331 def _cmd_from_args(orig_args
):
332 # We use our `argpar` module here instead of Python's `argparse`
333 # because we need to support the two following use cases:
335 # $ barectf config.yaml
336 # $ barectf generate config.yaml
338 # In other words, the default command is `generate` (for backward
339 # compatibility reasons). The argument parser must not consider
340 # `config.yaml` as being a command name.
341 general_opt_descrs
= [
342 barectf_argpar
.OptDescr('V', 'version'),
343 barectf_argpar
.OptDescr('h', 'help'),
345 res
= barectf_argpar
.parse(orig_args
, general_opt_descrs
, False)
347 # find command name, collecting preceding (common) option items
348 cmd_from_args_funcs
= {
349 'generate': _gen_cmd_cfg_from_args
,
350 'gen': _gen_cmd_cfg_from_args
,
351 'show-effective-configuration': _show_effective_cfg_cfg_from_args
,
352 'show-effective-config': _show_effective_cfg_cfg_from_args
,
353 'show-effective-cfg': _show_effective_cfg_cfg_from_args
,
354 'show-configuration-version': _show_cfg_version_cfg_from_args
,
355 'show-config-version': _show_cfg_version_cfg_from_args
,
356 'show-cfg-version': _show_cfg_version_cfg_from_args
,
358 general_opt_items
= []
359 cmd_first_orig_arg_index
= None
360 cmd_from_args_func
= None
362 for item
in res
.items
:
363 if type(item
) is barectf_argpar
._NonOptItem
:
364 cmd_from_args_func
= cmd_from_args_funcs
.get(item
.text
)
366 if cmd_from_args_func
is None:
367 cmd_first_orig_arg_index
= item
.orig_arg_index
369 cmd_first_orig_arg_index
= item
.orig_arg_index
+ 1
373 assert type(item
) is barectf_argpar
._OptItem
374 general_opt_items
.append(item
)
377 if len(_find_opt_items(general_opt_items
, 'help')) > 0:
378 _print_general_usage()
382 if len(_find_opt_items(general_opt_items
, 'version')) > 0:
383 print(f
'barectf {barectf.__version__}')
387 cmd_orig_args
= orig_args
[cmd_first_orig_arg_index
:]
389 if cmd_from_args_func
is None:
390 # default `generate` command
391 return _gen_cmd_cfg_from_args(cmd_orig_args
)
393 return cmd_from_args_func(cmd_orig_args
)
400 class _CfgCmdCfg(_CmdCfg
):
401 def __init__(self
, cfg_file_path
, inclusion_dirs
, ignore_inclusion_file_not_found
):
402 self
._cfg
_file
_path
= cfg_file_path
403 self
._inclusion
_dirs
= inclusion_dirs
404 self
._ignore
_inclusion
_file
_not
_found
= ignore_inclusion_file_not_found
407 def cfg_file_path(self
):
408 return self
._cfg
_file
_path
411 def inclusion_dirs(self
):
412 return self
._inclusion
_dirs
415 def ignore_inclusion_file_not_found(self
):
416 return self
._ignore
_inclusion
_file
_not
_found
420 def __init__(self
, cfg
):
428 raise NotImplementedError
431 class _GenCmdCfg(_CfgCmdCfg
):
432 def __init__(self
, cfg_file_path
, c_source_dir
, c_header_dir
, metadata_stream_dir
,
433 inclusion_dirs
, ignore_inclusion_file_not_found
, dump_config
, v2_prefix
):
434 super().__init
__(cfg_file_path
, inclusion_dirs
, ignore_inclusion_file_not_found
)
435 self
._c
_source
_dir
= c_source_dir
436 self
._c
_header
_dir
= c_header_dir
437 self
._metadata
_stream
_dir
= metadata_stream_dir
438 self
._dump
_config
= dump_config
439 self
._v
2_prefix
= v2_prefix
442 def c_source_dir(self
):
443 return self
._c
_source
_dir
446 def c_header_dir(self
):
447 return self
._c
_header
_dir
450 def metadata_stream_dir(self
):
451 return self
._metadata
_stream
_dir
454 def dump_config(self
):
455 return self
._dump
_config
459 return self
._v
2_prefix
462 # Source and metadata stream file generating command.
465 # create configuration
467 with
open(self
.cfg
.cfg_file_path
) as f
:
468 if self
.cfg
.dump_config
:
469 # print effective configuration file
470 print(barectf
.effective_configuration_file(f
, True, self
.cfg
.inclusion_dirs
,
471 self
.cfg
.ignore_inclusion_file_not_found
))
473 # barectf.configuration_from_file() reads the file again
477 config
= barectf
.configuration_from_file(f
, True, self
.cfg
.inclusion_dirs
,
478 self
.cfg
.ignore_inclusion_file_not_found
)
479 except barectf
._ConfigurationParseError
as exc
:
480 _print_config_error(exc
)
481 except Exception as exc
:
482 _print_unknown_exc(exc
)
484 if self
.cfg
.v2_prefix
is not None:
487 # For historical reasons, the `--prefix` option applies the
488 # barectf 2 configuration prefix rules. Therefore, get the
489 # equivalent barectf 3 prefixes first.
490 v3_prefixes
= barectf_config_parse_common
._v
3_prefixes
_from
_v
2_prefix
(self
.cfg
.v2_prefix
)
491 cg_opts
= config
.options
.code_generation_options
492 cg_opts
= barectf
.ConfigurationCodeGenerationOptions(v3_prefixes
.identifier
,
493 v3_prefixes
.file_name
,
494 cg_opts
.default_stream_type
,
495 cg_opts
.header_options
,
496 cg_opts
.clock_type_c_types
)
497 config
= barectf
.Configuration(config
.trace
, barectf
.ConfigurationOptions(cg_opts
))
499 # create a barectf code generator
500 code_gen
= barectf
.CodeGenerator(config
)
502 def write_file(dir, file):
503 with
open(os
.path
.join(dir, file.name
), 'w') as f
:
504 f
.write(file.contents
)
506 def write_files(dir, files
):
508 write_file(dir, file)
511 # generate and write metadata stream file
512 write_file(self
.cfg
.metadata_stream_dir
, code_gen
.generate_metadata_stream())
514 # generate and write C header files
515 write_files(self
.cfg
.c_header_dir
, code_gen
.generate_c_headers())
517 # generate and write C source files
518 write_files(self
.cfg
.c_source_dir
, code_gen
.generate_c_sources())
519 except Exception as exc
:
520 # We know `config` is valid, therefore the code generator cannot
521 # fail for a reason known to barectf.
522 _print_unknown_exc(exc
)
525 class _ShowEffectiveCfgCmdCfg(_CfgCmdCfg
):
526 def __init__(self
, cfg_file_path
, inclusion_dirs
, ignore_inclusion_file_not_found
,
528 super().__init
__(cfg_file_path
, inclusion_dirs
, ignore_inclusion_file_not_found
)
529 self
._indent
_space
_count
= indent_space_count
532 def indent_space_count(self
):
533 return self
._indent
_space
_count
536 # Effective configuration showing command.
537 class _ShowEffectiveCfgCmd(_Cmd
):
540 with
open(self
.cfg
.cfg_file_path
) as f
:
541 print(barectf
.effective_configuration_file(f
, True, self
.cfg
.inclusion_dirs
,
542 self
.cfg
.ignore_inclusion_file_not_found
,
543 self
.cfg
.indent_space_count
))
544 except barectf
._ConfigurationParseError
as exc
:
545 _print_config_error(exc
)
546 except Exception as exc
:
547 _print_unknown_exc(exc
)
550 class _ShowCfgVersionCmdCfg(_CmdCfg
):
551 def __init__(self
, cfg_file_path
):
552 self
._cfg
_file
_path
= cfg_file_path
555 def cfg_file_path(self
):
556 return self
._cfg
_file
_path
559 class _ShowCfgVersionCmd(_Cmd
):
562 with
open(self
.cfg
.cfg_file_path
) as f
:
563 print(barectf
.configuration_file_major_version(f
))
564 except barectf
._ConfigurationParseError
as exc
:
565 _print_config_error(exc
)
566 except Exception as exc
:
567 _print_unknown_exc(exc
)
571 # create command from arguments
573 cmd
= _cmd_from_args(sys
.argv
[1:])
574 except barectf_argpar
._Error
as exc
:
575 _print_error(f
'Command-line: For argument `{exc.orig_arg}`: {exc.msg}')
576 except _CliError
as exc
:
577 _print_error(f
'Command-line: {exc}')