summaryrefslogtreecommitdiff
path: root/scripts/xls_to_doc.py
blob: 696fccd64a2b757a53293976799086d4af42e3f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#!/usr/bin/env python3
# pylint: disable=C0301,R0912,R0913,R0914,R0915,C0116
# SPDX-License-Identifier: (GPL-2.0 OR MIT)

## Copyright (C) 2023    Intel Corporation                 ##
## Author: Mauro Carvalho Chehab <mchehab@kernel.org>      ##

"""Import contents of a XLS file into testplan documentation."""

import argparse
import json
import os
import re
import sys

from openpyxl import load_workbook

from test_list import TestList

EPILOG = ""

#
# FillTests class definition
#


class FillTests(TestList):
    """
    Fill documentation source code test comments from a spreadsheet.
    """

    def __init__(self, config_path):
        self.tests = {}
        self.spreadsheet_data = {}
        self.ignore_fields = []

        TestList.__init__(self, config_path)

        self.testname_regex = re.compile(r'^\s*(igt@[^\n\@]+)\@?(\S*)\s*')
        self.key_has_wildcard = re.compile(r'\%?arg\[(\d+)\]')
        self.field_re = re.compile(r"(" + '|'.join(self.field_list.keys()) + r'):\s*(.*)', re.I)

        for test in self.doc:                   # pylint: disable=C0206
            fname = self.doc[test]["File"]

            name = re.sub(r'.*/', '', fname)
            name = re.sub(r'\.[\w+]$', '', name)
            name = "igt@" + name

            subtest_array = self.expand_subtest(fname, name, test, True, True, True)
            for subtest_dict in subtest_array:
                name = subtest_dict["_summary_"]
                del subtest_dict["_summary_"]

                match = self.testname_regex.match(name)
                if not match:
                    sys.exit(f"Error: can't parse {name}")

                testname = match.group(1)
                if match.group(2):
                    subtest = match.group(2)
                else:
                    subtest = ''

                if testname not in self.tests:
                    self.tests[testname] = {}
                    self.tests[testname]["subtests"] = {}

                    self.tests[testname]["Test"] = test
                    self.tests[testname]["File"] = fname

                self.tests[testname]["subtests"][subtest] = subtest_dict

        for field, item in self.props.items():
            if "sublevel" in item["_properties_"]:
                update = item["_properties_"].get("update-from-file")
                if update:
                    self.ignore_fields.append(field)

    def add_field(self, dic, field, value):
        if field in dic and dic[field] != '':
            fields = sorted(dic[field].split(", "))
            fields.append(value)
            value = ", ".join(sorted(fields))

        dic[field] = value

    def process_spreadsheet_sheet(self, sheet):

        column_list = []
        for cell in sheet[1]:
            column_list.append(cell.value)

        for row in range(2, sheet.max_row):
            if sheet[row][0].value is None:
                print(f"Ignoring sheet after A{row} row, as test name is empty")
                return
            if not isinstance(sheet[row][0].value, str):
                print(f"Ignoring A{row} row on {sheet.title}: test name is not a string: {sheet[row][0].value}")
                continue
            test_name = sheet[row][0].value.strip()
            if not re.match(r'^igt\@', test_name):
                print(f"Ignoring A{row} row on {sheet.title}: not a valid test name: {test_name}")
                continue

            if test_name not in self.spreadsheet_data:
                self.spreadsheet_data[test_name] = {}

            i = 1
            for col in range(2, sheet.max_column + 1):
                val = sheet.cell(row=row, column=col).value
                if val:
                    if isinstance(val, str):
                        val = val.strip()

                    self.spreadsheet_data[test_name][column_list[i]] = val

                i += 1

    def read_spreadsheet_file(self, fname, sheets):

        # Iterate the loop to read the cell values
        wb = load_workbook(filename=fname)

        # Handle first "normal" sheets
        for sheet in wb:
            if sheets and sheet.title not in sheets:
                continue

            self.process_spreadsheet_sheet(sheet)

        return dict(sorted(self.spreadsheet_data.items()))

    def change_value(self, content, subtest, line, field, value):

        current_field = None
        i = line
        while True:
            i += 1
            if i >= len(content):
                break

            file_line = content[i]

            if re.match(r'^\s*\*\/\s*$', file_line):
                break

            file_line = re.sub(r'^\s*\* ?', '', file_line)

            match = re.match(r'^SUBTESTS?:\s*(.*)', file_line)
            if match and match.group(1) != subtest:
                break

            match = re.match(r'^TEST:\s*(.*)', file_line)
            if match and match.group(1) != subtest:
                break

            match = re.match(r'arg\[(\d+)\]:\s*(.*)', file_line)
            if match:
                break

            match = re.match(r'\@(\S+):\s*(.*)', file_line)
            if match:
                break

            match = re.match(r'arg\[(\d+)\]\.values:\s*(.*)', file_line)
            if match:
                break

            match = re.match(self.field_re, file_line)
            if match:
                current_field = self.field_list[match.group(1).lower()]
                if current_field != field:
                    continue
                content[i] = ""

            # Handle continuation lines
            if current_field:
                match = re.match(r'\s+(.*)', file_line)
                if match:
                    if current_field != field:
                        continue

                    content[i] = ""

        content.insert(i, f' * {field}: {value}\n')

    def parse_spreadsheet(self, fname, sheets=None):
        if not os.path.isfile(fname):
            print(f'Warning: {fname} not found. Skipping spreadsheet parser')
            return

        data = self.read_spreadsheet_file(fname, sheets)

        for test, row in data.items():
            match = self.testname_regex.match(test)
            if not match:
                sys.exit(f"Error: can't parse {test}")

            testname = match.group(1)
            if match.group(2):
                subtest = match.group(2)
            else:
                subtest = ''

            if testname not in self.tests:
                print(f"Ignoring {test}, as test is not documented.")
                continue

            if subtest not in self.tests[testname]["subtests"]:
                self.tests[testname]["subtests"][subtest] = {}

            for key, value in row.items():
                self.tests[testname]["subtests"][subtest][key] = value

    def update_test_file(self, testname, args):
        try:
            sourcename = self.tests[testname]["File"]
            with open(sourcename, 'r', encoding='utf8') as in_fp:
                content = in_fp.read().splitlines(True)
        except EnvironmentError:
            sys.exit(f'Failed to read {sourcename}')

        try:

            test_nr = self.tests[testname]["Test"]

            for subtest, subtest_content in sorted(self.tests[testname]["subtests"].items()):
                if "line" not in subtest_content:
                    print(f"Warning: didn't find where {subtest} is documented.")
                    continue

                line = subtest_content['line']
                subtest_nr = subtest_content['subtest_nr']

                if subtest_nr not in self.doc[test_nr]["subtest"]:
                    print(f"Error: missing subtest {subtest_nr} at {self.doc[test_nr]['subtest']}")
                    continue

                doc_content = self.doc[test_nr]["subtest"][subtest_nr]

                # Handling wildcards is not easy. Let's just skip those
                for field, value in sorted(subtest_content.items()):
                    if field in ['line', 'subtest_nr']:
                        continue

                    if args.ignore_lists:
                        if field in self.ignore_fields:
                            continue

                    doc_value = doc_content.get(field)
                    if doc_value:
                        if self.key_has_wildcard.search(doc_value):
                            print(f"Warning: {subtest} field {field} has wildcards.")
                            continue
                        if doc_value == value:
                            print(f"{testname}@{subtest} field {field}: Value unchanged. Ignoring it")
                            continue

                    print(f"Update {testname}@{subtest} field {field} on line {line}:")
                    print(f"  Change from {doc_value} to {value}")

                    # Just in case, handle continuation lines
                    value = re.sub(r"\n", "\n *   ", value)

                    self.change_value(content, subtest, line, field, value)

                    # Update line numbers after insert
                    skip = True
                    for sub, sub_content in sorted(self.tests[testname]["subtests"].items()):
                        if sub == subtest:
                            skip = False
                            continue
                        if skip:
                            continue
                        sub_line = sub_content['line']
                        if sub_line >= line:
                            sub_content['line'] += 1

        except EnvironmentError as err:
            sys.exit(f'Error: {err}')

        # Write changes
        try:
            print(f"Writing to {sourcename}")
            with open(sourcename, 'w', encoding='utf8') as out_fp:
                out_fp.write("".join(content))
        except EnvironmentError:
            print(f'Failed to write to {sourcename}')

    def update_test_files(self, args):
        """ Populate documentation """

        for testname in self.tests:
            self.update_test_file(testname, args)

######
# Main
######


def main():
    parser = argparse.ArgumentParser(description=__doc__,
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                     argument_default=argparse.SUPPRESS,
                                     epilog=EPILOG)
    parser.add_argument("--config", required=True,
                        help="JSON file describing the test plan template")
    parser.add_argument("--xls", required=True,
                        help="Input XLS file.")
    parser.add_argument("--sheets", nargs="*",
                        help="Input only some specific sheets from the XLS file.")
    parser.add_argument('--ignore-lists', action='store_false', default=True,
                        help='Ignore fields that are updated via test lists')

    parse_args = parser.parse_args()

    fill_test = FillTests(parse_args.config)

    if "sheets" not in parse_args:
        parse_args.sheets = None

    fill_test.parse_spreadsheet(parse_args.xls, parse_args.sheets)

    # DEBUG: remove it later on
    with open("fill_test.json", "w", encoding='utf8') as write_file:
        json.dump(fill_test.tests, write_file, indent=4)
    with open("doc.json", "w", encoding='utf8') as write_file:
        json.dump(fill_test.doc, write_file, indent=4)

    fill_test.update_test_files(parse_args)


if __name__ == '__main__':
    main()