]> rtime.felk.cvut.cz Git - pes-rpp/rpp-simulink.git/blob - rpp/blocks/scripts/doc_parse.py
doc: Formatting and content updates
[pes-rpp/rpp-simulink.git] / rpp / blocks / scripts / doc_parse.py
1 #!/usr/bin/env python3
2
3 # Copyright (C) 2013-2014 Czech Technical University in Prague
4 #
5 # Authors:
6 #     - Michal Sojka <sojkam1@fel.cvut.cz>
7 #
8 # This document contains proprietary information belonging to Czech
9 # Technical University in Prague. Passing on and copying of this
10 # document, and communication of its contents is not permitted
11 # without prior written authorization.
12 #
13 # File : doc_parse.py
14 # Abstract:
15
16 import yaml
17 import argparse
18 import Rx
19 import sys
20 import subprocess
21 import os
22 from string import Template
23
24 parser = argparse.ArgumentParser()
25 parser.add_argument("file", help="file to process", nargs='+')
26 parser.add_argument("--html", help="output block description or help as HTML",
27                     action = 'store_true')
28 parser.add_argument("--latex", help="output block description as LaTeX",
29                     action = 'store_true')
30 parser.add_argument("--latex-table", help="output block status table as LaTeX",
31                     action = 'store_true')
32 parser.add_argument('--printdesc', help="output block description",
33                     action = 'store_true')
34 parser.add_argument('--printhelp', help="output block help",
35                     action = 'store_true')
36 parser.add_argument('--maskpromptstring', help="output prompt strings for Simulink mask",
37                     action = 'store_true')
38 parser.add_argument('--masktype', help="output mask type for Simulink mask",
39                     action = 'store_true')
40 parser.add_argument('--name', help="print block name",
41                     action = 'store_true')
42 args = parser.parse_args()
43
44 mydir = os.path.dirname(os.path.realpath(__file__))
45
46 def print_markdown_as(format, text):
47     sys.stdout.flush()
48     proc = subprocess.Popen(['pandoc', '-f', 'markdown', '-t', format], stdin = subprocess.PIPE)
49     proc.stdin.write(bytes(text, 'UTF-8'))
50     proc.communicate()
51     proc.stdin.close()
52     if proc.returncode:
53         raise Exception("pandoc failed: %d" % proc.returncode)
54
55 def print_latex_desc(doc):
56     def iodef_str(iodef):
57         if iodef is None: return "None"
58         str='%d\n\\begin{enumerate}\n' % len(iodef)
59         for io in iodef:
60             str += Template('\\item {\\bf $name} $type').substitute(io)
61             if 'range' in io:
62                 str += '  %s' % io['range']
63             if 'note' in io:
64                 str += '  %s' % io['note']
65             str += '\n'
66         return str +'\end{enumerate}'
67
68     print("\\newpage\n")
69     print("\\subsection{%s}\n" % doc['Name'])
70     print("\\begin{description}\n")
71     print("\\item[Inputs:]     %s\n" % iodef_str(doc['Inputs']))
72     print("\\item[Outputs:]    %s\n" % iodef_str(doc['Outputs']))
73     print("\\item[Parameters:] %s\n" % iodef_str(doc['Parameters']))
74     print("\\end{description}\n")
75
76     print_markdown_as('latex', doc['Help'])
77
78     if doc.get('RPP API functions used', None) is not None:
79         print("\\paragraph{RPP API functions used:}")
80         print("\\begin{compactitem}")
81         print("\n".join(["\\item \\texttt{%s}" % i.replace('_', '\\_') for i in doc['RPP API functions used']]))
82         print("\\end{compactitem}")
83
84     if doc.get('Relevant demos', None) is not None:
85         print("\\paragraph{Relevant demos:}")
86         print("\\begin{compactitem}")
87         print("\n".join(["\\item %s" % i.replace('_', '\\_') for i in doc['Relevant demos']]))
88         print("\\end{compactitem}")
89
90 def process_file(f):
91     yaml_doc = None
92     for line in open(f, 'r'):
93         if yaml_doc:
94             yaml_doc += line
95         elif line.startswith("%YAML"):
96             yaml_doc = line
97         if line == '...\n':
98             break
99     if yaml_doc is None:
100         raise Exception("No line starting with '%%YAML' found in %s" % f)
101
102     doc = yaml.load(yaml_doc)
103     schema = yaml.load(open(mydir+'/schema.yaml', 'r'))
104
105     rx = Rx.Factory({ "register_core_types": True })
106     rpp_block_doc_schema = rx.make_schema(schema)
107     try:
108         rpp_block_doc_schema.check(doc)
109     except Rx.ValidationError as e:
110         raise Exception("Validation error in %s: %s" % (f, e))
111         #raise
112
113     fmt = 'html' if args.html else 'markdown'
114
115     if args.printdesc:
116         print_markdown_as(fmt, doc['Description'])
117     if args.printhelp:
118         print_markdown_as(fmt, doc['Help'])
119     if args.latex:
120         print_latex_desc(doc)
121     if args.latex_table:
122         global last_category
123         if last_category == doc['Category']: doc['Category']=''
124         doc['Header'] = doc['Header'].replace('_', '\\_')
125         print(Template("$Category & $Name & $Status & $Mnemonic & \\texttt{$Header} \\\\").substitute(doc))
126         if doc['Category']:
127             last_category = doc['Category']
128     if args.masktype:
129         print('RPP {name}'.format(name=doc['Name']))
130     if args.name:
131         print(doc['Name'])
132     if args.maskpromptstring and doc['Parameters'] != None:
133         print('|'.join(['{name}{range}{colon}'.format(name=par['name'],
134                                                       range=(' '+par['range'] if ('range' in par and (par['type'] in ['double'] or
135                                                                                                 'int' in par['type']))
136                                                              else ''),
137                                                       colon=':' if par['type'] != 'bool' else '')
138                         for par in doc['Parameters']]))
139
140 last_category = None
141 for f in args.file:
142     process_file(f)