1
""" a module to convert between the old (Python script) segment format,
2
and the new (JSON) one
3
"""
4 1
from typing import Dict, Tuple  # noqa: F401
5 1
import os
6 1
import ast
7 1
import json
8

9

10 1
def assess_syntax(path):
11

12 1
    with open(path) as file_obj:
13 1
        content = file_obj.read()
14

15 1
    syntax_tree = ast.parse(content)
16

17 1
    docstring = ""  # docstring = ast.get_docstring(syntaxTree)
18 1
    dct = None
19 1
    dtype = None
20 1
    for i, child in enumerate(ast.iter_child_nodes(syntax_tree)):
21 1
        if i == 0 and isinstance(child, ast.Expr) and isinstance(child.value, ast.Str):
22 0
            docstring = child.value.s
23 1
        elif isinstance(child, ast.Assign):
24 1
            targets = child.targets
25 1
            if len(targets) > 1:
26 0
                continue
27 1
            target = child.targets[0]  # type: ast.Name
28 1
            dtype = target.id
29 1
            if dtype not in ["tpl_dict", "tplx_dict"]:
30 0
                continue
31 1
            if not isinstance(child.value, ast.Dict):
32 0
                raise ValueError(
33
                    "expected {} to be of type Dict: {}".format(dtype, child.value)
34
                )
35 1
            dct = child.value
36 1
            break
37

38 1
    if dct is None:
39 0
        raise IOError("could not find tpl(x)_dict")
40

41 1
    output = {}
42 1
    for key, value in zip(dct.keys, dct.values):
43 1
        if not isinstance(key, ast.Str):
44 0
            raise ValueError("expected {} key to be of type Str: {}".format(dtype, key))
45 1
        if not isinstance(value, ast.Str):
46 0
            raise ValueError(
47
                "expected {} value be of type Str: {}".format(dtype, value)
48
            )
49 1
        output[key.s] = value.s
50

51 1
    return {
52
        "identifier": os.path.splitext(os.path.basename(path))[0],
53
        "description": docstring,
54
        "segments": output,
55
        "$schema": "../../schema/segment.schema.json",
56
    }
57

58

59 1
def py_to_json(path, outpath=None):
60 1
    output = assess_syntax(path)
61 1
    if outpath:
62 0
        with open(outpath, "w") as file_obj:
63 0
            json.dump(output, file_obj, indent=2)
64 1
    return json.dumps(output, indent=2)
65

66

67 1
if __name__ == "__main__":
68 0
    import glob
69

70 0
    _dir_path = os.path.dirname(os.path.realpath(__file__))
71 0
    _ext = ".tpl.json"
72

73 0
    for _path in glob.glob(os.path.join(_dir_path, "**", "*.py")):
74

75 0
        _name = os.path.splitext(os.path.basename(_path))[0]
76 0
        _folder = os.path.basename(os.path.dirname(_path))
77 0
        if _folder == "ipypublish":
78 0
            _prefix = "ipy-"
79
        else:
80 0
            _prefix = "std-"
81

82 0
        _outpath = os.path.join(os.path.dirname(_path), _prefix + _name + _ext)
83

84 0
        py_to_json(_path, _outpath)

Read our documentation on viewing source code .

Loading