CSIT-1189: Add suite setup to source code documentation
[csit.git] / resources / tools / doc_gen / gen_rst.py
1 # Copyright (c) 2018 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14
15 from os import walk, listdir
16 from os.path import isfile, isdir, join, getsize
17
18 # Temporary working directory. It is created and deleted by run_doc.sh
19 WORKING_DIR = "tmp"
20
21 # Directory with resources to be documented.
22 RESOURCES_DIR = "resources"
23
24 # Directory with libraries (python, robot) to be documented.
25 LIB_DIR = "libraries"
26
27 # Directory with tests (func, perf) to be documented.
28 TESTS_DIR = "tests"
29
30 PY_EXT = ".py"
31 RF_EXT = ".robot"
32
33 PATH_PY_LIBS = join(WORKING_DIR, RESOURCES_DIR, LIB_DIR, "python")
34 PATH_RF_LIBS = join(WORKING_DIR, RESOURCES_DIR, LIB_DIR, "robot")
35 PATH_TESTS = join(WORKING_DIR, TESTS_DIR)
36
37 # Sections in rst files
38 rst_toc = """
39 .. toctree::
40 """
41
42 rst_py_module = """
43 .. automodule:: {}.{}
44     :members:
45     :undoc-members:
46     :show-inheritance:
47 """
48
49 rst_rf_suite_setup = """
50 .. robot-settings::
51    :source: {}
52 """
53
54 rst_rf_variables = """
55 .. robot-variables::
56    :source: {}
57 """
58
59 rst_rf_keywords = """
60 .. robot-keywords::
61    :source: {}
62 """
63
64 rst_rf_tests = """
65 .. robot-tests::
66    :source: {}
67 """
68
69
70 def get_files(path, extension):
71     """Generates the list of files to process.
72
73     :param path: Path to files.
74     :param extension: Extension of files to process. If it is the empty string,
75     all files will be processed.
76     :type path: str
77     :type extension: str
78     :returns: List of files to process.
79     :rtype: list
80     """
81
82     file_list = list()
83     for root, dirs, files in walk(path):
84         for filename in files:
85             if extension:
86                 if filename.endswith(extension):
87                     file_list.append(join(root, filename))
88             else:
89                 file_list.append(join(root, filename))
90
91     return file_list
92
93
94 def create_file_name(path, start):
95     """Create the name of rst file.
96
97     Example:
98     resources.libraries.python.honeycomb.rst
99     tests.perf.rst
100
101     :param path: Path to a module to be documented.
102     :param start: The first directory in path which is used in the file name.
103     :type path: str
104     :type start: str
105     :returns: File name.
106     :rtype: str
107     """
108     dir_list = path.split('/')
109     start_index = dir_list.index(start)
110     return ".".join(dir_list[start_index:-1]) + ".rst"
111
112
113 def create_rst_file_names_set(files, start):
114     """Generate a set of unique rst file names.
115
116     :param files: List of all files to be documented with path beginning in the
117     working directory.
118     :param start: The first directory in path which is used in the file name.
119     :type files: list
120     :type start: str
121     :returns: Set of unique rst file names.
122     :rtype: set
123     """
124     file_names = set()
125     for file in files:
126         file_names.add(create_file_name(file, start))
127     return file_names
128
129
130 def scan_dir(path):
131     """Create a list of files and directories in the given directory.
132
133     :param path: Path to the directory.
134     :type path: str
135     :returns: List of directories and list of files sorted in alphabetical
136     order.
137     :rtype: tuple of two lists
138     """
139     files = list()
140     dirs = list()
141     items = listdir(path)
142     for item in items:
143         if isfile(join(path, item)) and "__init__" not in item:
144             files.append(item)
145         elif isdir(join(path, item)):
146             dirs.append(item)
147     return sorted(dirs), sorted(files)
148
149
150 def write_toc(fh, path, dirs):
151     """Write a table of contents to given rst file.
152
153     :param fh: File handler of the rst file.
154     :param path: Path to package.
155     :param dirs: List of directories to be included in ToC.
156     :type fh: BinaryIO
157     :type path: str
158     :type dirs: list
159     """
160     fh.write(rst_toc)
161     for dir in dirs:
162         fh.write("    {}.{}\n".format('.'.join(path), dir))
163
164
165 def write_module_title(fh, module_name):
166     """Write the module title to the given rst file. The title will be on the
167     second level.
168
169     :param fh: File handler of the rst file.
170     :param module_name: The name of module used for title.
171     :type fh: BinaryIO
172     :type module_name: str
173     """
174     title = "{} suite".format(module_name)
175     fh.write("\n{}\n{}\n".format(title, '-' * len(title)))
176
177
178 def generate_py_rst_files():
179     """Generate all rst files for all python modules."""
180
181     dirs_ignore_list = ["__pycache__", ]
182
183     py_libs = get_files(PATH_PY_LIBS, PY_EXT)
184     file_names = create_rst_file_names_set(py_libs, RESOURCES_DIR)
185
186     for file_name in file_names:
187         path = join(WORKING_DIR, *file_name.split('.')[:-1])
188         dirs, files = scan_dir(path)
189
190         for item in dirs_ignore_list:
191             while True:
192                 try:
193                     dirs.remove(item)
194                 except ValueError:
195                     break
196
197         full_path = join(WORKING_DIR, file_name)
198         with open(full_path, mode='a') as fh:
199             if getsize(full_path) == 0:
200                 package = file_name.split('.')[-2]
201                 fh.write("{}\n".format(package))
202                 fh.write('=' * len("{}".format(package)))
203             module_path = file_name.split('.')[:-1]
204             if dirs:
205                 write_toc(fh, module_path, dirs)
206             for file in files:
207                 module_name = file.split('.')[0]
208                 write_module_title(fh, module_name)
209                 fh.write(rst_py_module.format('.'.join(module_path),
210                                               module_name))
211
212
213 def generate_rf_rst_files(file_names, incl_tests=True, incl_keywords=True,
214                           incl_suite_setup=False, incl_variables=False):
215     """Generate rst files for the given robot modules.
216
217     :param file_names: List of file names to be included in the documentation
218     (rst files).
219     :param incl_tests: If True, tests will be included in the documentation.
220     :param incl_keywords: If True, keywords will be included in the
221     documentation.
222     :param incl_suite_setup: If True, the suite setup will be included in the
223     documentation.
224     :param incl_variables: If True, the variables will be included in the
225     documentation.
226     :type file_names: set
227     :type incl_tests: bool
228     :type incl_keywords: bool
229     :type incl_suite_setup: bool
230     :type incl_variables: bool
231     """
232
233     for file_name in file_names:
234         path = join(WORKING_DIR, *file_name.split('.')[:-1])
235         dirs, files = scan_dir(path)
236
237         full_path = join(WORKING_DIR, file_name)
238         with open(full_path, mode='a') as fh:
239             if getsize(full_path) == 0:
240                 package = file_name.split('.')[-2]
241                 fh.write("{}\n".format(package))
242                 fh.write('=' * len("{}".format(package)) + '\n')
243             module_path = file_name.split('.')[:-1]
244             if dirs:
245                 write_toc(fh, module_path, dirs)
246             for file in files:
247                 module_name = file.split('.')[0]
248                 write_module_title(fh, module_name)
249                 path = join(join(*module_path), module_name + RF_EXT)
250                 if incl_suite_setup:
251                     fh.write(rst_rf_suite_setup.format(path))
252                 if incl_variables:
253                     fh.write(rst_rf_variables.format(path))
254                 if incl_keywords:
255                     fh.write(rst_rf_keywords.format(path))
256                 if incl_tests:
257                     fh.write(rst_rf_tests.format(path))
258
259
260 def generate_kw_rst_files():
261     """Generate all rst files for all robot modules with keywords in libraries
262     directory (no tests)."""
263
264     rf_libs = get_files(PATH_RF_LIBS, RF_EXT)
265     file_names = create_rst_file_names_set(rf_libs, RESOURCES_DIR)
266
267     generate_rf_rst_files(file_names, incl_tests=False)
268
269
270 def generate_tests_rst_files():
271     """Generate all rst files for all robot modules with tests in tests
272     directory. Include also keywords defined in these modules."""
273
274     tests = get_files(PATH_TESTS, RF_EXT)
275     file_names = create_rst_file_names_set(tests, TESTS_DIR)
276
277     generate_rf_rst_files(file_names,
278                           incl_suite_setup=True,
279                           incl_variables=True)
280
281
282 if __name__ == '__main__':
283
284     # Generate all rst files:
285     generate_py_rst_files()
286     generate_kw_rst_files()
287     generate_tests_rst_files()