1#!/usr/bin/env python32# -*- coding: utf-8 -*-34import argparse5import sys6import os7from pathlib import Path89script_path = Path(__file__).absolute()1011sys.path.insert(0, str(script_path.parent.parent)) # to find wireviz module12from wireviz import wireviz, __version__, APP_NAME13from wv_helper import open_file_write, open_file_read, open_file_append141516dir = script_path.parent.parent.parent17readme = 'readme.md'18groups = {19 'examples': {20 'path': dir / 'examples',21 'prefix': 'ex',22 readme: [], # Include no files23 'title': 'Example Gallery',24 },25 'tutorial' : {26 'path': dir / 'tutorial',27 'prefix': 'tutorial',28 readme: ['md', 'yml'], # Include .md and .yml files29 'title': f'{APP_NAME} Tutorial',30 },31 'demos' : {32 'path': dir / 'examples',33 'prefix': 'demo',34 },35}3637input_extensions = ['.yml']38extensions_not_containing_graphviz_output = ['.gv', '.bom.tsv']39extensions_containing_graphviz_output = ['.png', '.svg', '.html']40generated_extensions = extensions_not_containing_graphviz_output + extensions_containing_graphviz_output414243def collect_filenames(description, groupkey, ext_list):44 path = groups[groupkey]['path']45 patterns = [f"{groups[groupkey]['prefix']}*{ext}" for ext in ext_list]46 if ext_list != input_extensions and readme in groups[groupkey]:47 patterns.append(readme)48 sys.stderr.write(f'{description} {groupkey} in "{path}"')49 return sorted([filename for pattern in patterns for filename in path.glob(pattern)])505152def build_generated(groupkeys):53 for key in groupkeys:54 # preparation55 path = groups[key]['path']56 build_readme = readme in groups[key]57 if build_readme:58 include_readme = 'md' in groups[key][readme]59 include_source = 'yml' in groups[key][readme]60 with open_file_write(path / readme) as out:61 out.write(f'# {groups[key]["title"]}\n\n')62 # collect and iterate input YAML files63 for yaml_file in collect_filenames('Building', key, input_extensions):64 sys.stderr.write(f' "{yaml_file}"')65 wireviz.parse_file(yaml_file)6667 if build_readme:68 i = ''.join(filter(str.isdigit, yaml_file.stem))6970 with open_file_append(path / readme) as out:71 if include_readme:72 with open_file_read(yaml_file.with_suffix('.md')) as info:73 for line in info:74 out.write(line.replace('## ', f'## {i} - '))75 out.write('\n\n')76 else:77 out.write(f'## Example {i}\n')7879 if include_source:80 with open_file_read(yaml_file) as src:81 out.write('```yaml\n')82 for line in src:83 out.write(line)84 out.write('```\n')85 out.write('\n')8687 out.write(f'\n\n')88 out.write(f'[Source]({yaml_file.name}) - [Bill of Materials]({yaml_file.stem}.bom.tsv)\n\n\n')899091def clean_generated(groupkeys):92 for key in groupkeys:93 # collect and remove files94 for filename in collect_filenames('Cleaning', key, generated_extensions):95 if filename.is_file():96 sys.stderr.write(f' rm "{filename}"')97 os.remove(filename)9899100def compare_generated(groupkeys, branch = '', include_graphviz_output = False):101 if branch:102 branch = f' {branch.strip()}'103 compare_extensions = generated_extensions if include_graphviz_output else extensions_not_containing_graphviz_output104 for key in groupkeys:105 # collect and compare files106 for filename in collect_filenames('Comparing', key, compare_extensions):107 cmd = f'git --no-pager diff{branch} -- "{filename}"'108 sys.stderr.write(f' {cmd}')109 os.system(cmd)110111112def restore_generated(groupkeys, branch = ''):113 if branch:114 branch = f' {branch.strip()}'115 for key in groupkeys:116 # collect input YAML files117 filename_list = collect_filenames('Restoring', key, input_extensions)118 # collect files to restore119 filename_list = [fn.with_suffix(ext) for fn in filename_list for ext in generated_extensions]120 if readme in groups[key]:121 filename_list.append(groups[key]['path'] / readme)122 # restore files123 for filename in filename_list:124 cmd = f'git checkout{branch} -- "{filename}"'125 sys.stderr.write(f' {cmd}')126 os.system(cmd)127128129def parse_args():130 parser = argparse.ArgumentParser(description=f'{APP_NAME} Example Manager',)131 parser.add_argument('-V', '--version', action='version', version=f'%(prog)s - {APP_NAME} {__version__}')132 parser.add_argument('action', nargs='?', action='store',133 choices=['build','clean','compare','diff','restore'], default='build',134 help='what to do with the generated files (default: build)')135 parser.add_argument('-c', '--compare-graphviz-output', action='store_true',136 help='the Graphviz output is also compared (default: False)')137 parser.add_argument('-b', '--branch', action='store', default='',138 help='branch or commit to compare with or restore from')139 parser.add_argument('-g', '--groups', nargs='+',140 choices=groups.keys(), default=groups.keys(),141 help='the groups of generated files (default: all)')142 return parser.parse_args()143144145def main():146 args = parse_args()147 if args.action == 'build':148 build_generated(args.groups)149 elif args.action == 'clean':150 clean_generated(args.groups)151 elif args.action == 'compare' or args.action == 'diff':152 compare_generated(args.groups, args.branch, args.compare_graphviz_output)153 elif args.action == 'restore':154 restore_generated(args.groups, args.branch)155156157if __name__ == '__main__':158 main()