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