|
| 1 | +""" |
| 2 | + Prototyping area for Python code run in Pyodide |
| 3 | +""" |
| 4 | +import ast |
| 5 | +import json |
| 6 | + |
| 7 | +def get_json_step_report(): |
| 8 | + with open("script/reports/feature.json", "r", encoding="utf-8") as file: |
| 9 | + data = file.read() |
| 10 | + return json.loads(data) |
| 11 | + |
| 12 | +def get_step_locations(): |
| 13 | + report = get_json_step_report() |
| 14 | + locations = [] |
| 15 | + if len(report) > 0: |
| 16 | + for element in report[0]["elements"]: |
| 17 | + for step in element["steps"]: |
| 18 | + if "match" in step: |
| 19 | + locations.append(step["match"]["location"]) |
| 20 | + return locations |
| 21 | + |
| 22 | +def get_function_source(filename, step_decorator): |
| 23 | + with open(filename, encoding="utf-8") as file: |
| 24 | + file_contents = file.read() |
| 25 | + node = None |
| 26 | + try: |
| 27 | + node = ast.parse(file_contents, "file", "exec") |
| 28 | + except: # pylint: disable=W0702 |
| 29 | + pass |
| 30 | + if node: |
| 31 | + for body in node.body: |
| 32 | + if isinstance(body, ast.FunctionDef): |
| 33 | + step_text = None |
| 34 | + try: |
| 35 | + step_text = body.decorator_list[0].args[0].value |
| 36 | + except: # pylint: disable=W0702 |
| 37 | + pass |
| 38 | + if step_text and step_text in step_decorator: |
| 39 | + source_snippet = "" |
| 40 | + for decorator in body.decorator_list: |
| 41 | + source_snippet += "@" |
| 42 | + source_snippet += ast.get_source_segment(file_contents, decorator) |
| 43 | + source_snippet += "\\n" |
| 44 | + source_snippet += ast.get_source_segment(file_contents, body) |
| 45 | + return source_snippet |
| 46 | + |
| 47 | +def get_snippets(): |
| 48 | + locations = get_step_locations() |
| 49 | + snippets = [] |
| 50 | + for location in locations: |
| 51 | + parts = location.split(":") |
| 52 | + filename = parts[0] |
| 53 | + line_no = parts[1] |
| 54 | + with open(filename, "r", encoding="utf-8") as source_file: |
| 55 | + file_lines = source_file.readlines() |
| 56 | + step_decorator = file_lines[int(line_no) -1:int(line_no)][0] |
| 57 | + function_source = get_function_source(filename, step_decorator) |
| 58 | + existing_records = [rec for rec in snippets if rec["location"]==location and rec["file_lines"]==function_source] |
| 59 | + if len(existing_records) == 0: |
| 60 | + snippets.append({"location": location, "file_lines": function_source}) |
| 61 | + return snippets |
| 62 | + |
| 63 | +code_snippets = get_snippets() |
| 64 | +global snippet_json # pylint: disable=W0604 |
| 65 | +snippet_json = json.dumps(code_snippets) |
0 commit comments