-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdocopt2json.py
More file actions
129 lines (103 loc) · 3.6 KB
/
docopt2json.py
File metadata and controls
129 lines (103 loc) · 3.6 KB
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
"""Generate a dict for docopt."""
from __future__ import annotations
import re
from typing import Any, Iterator
from cli2gui.models import Group, Item, ItemType, ParserRep
def actionToJson(action: tuple[str, str, int, Any, str], widget: ItemType, *, isPos: bool) -> Item:
"""Generate json for an action and set the widget - used by the application."""
if isPos or len(action) < 5:
return Item(
type=widget,
display_name=action[0],
help=action[1],
commands=[action[0]],
dest=action[0],
default=None,
additional_properties={"nargs": ""},
)
default = action[3] if action[3] != "" else None
return Item(
type=widget,
display_name=(action[1] or action[0]).replace("-", " ").strip(),
help=action[4],
commands=[x for x in action[0:2] if x != ""],
dest=action[1] or action[0],
default=default,
additional_properties={"nargs": action[2]},
)
def categorize(
actions: list[tuple[str, str, int, Any, str]], *, isPos: bool = False
) -> Iterator[Item]:
"""Catergorise each action and generate json.
Each action is in the form (short, long, argcount, value, help_message)
"""
for action in actions:
# ('-h', '--help', 0, False, 'show this help message and exit')
if action[0] == "-h" and action[1] == "--help":
pass
elif not isPos and action[2] == 0:
yield actionToJson(action, ItemType.Bool, isPos=isPos)
else:
yield actionToJson(action, ItemType.Text, isPos=isPos)
def extract(parser: Any) -> list[Group]:
"""Get the actions as json for the parser."""
return [
Group(
name="Positional Arguments",
arg_items=list(categorize(parsePos(parser), isPos=True)),
groups=[],
),
Group(name="Optional Arguments", arg_items=list(categorize(parseOpt(parser))), groups=[]),
]
def parseSection(name: str, source: str) -> list[str]:
"""Taken from docopt."""
pattern = re.compile(
"^([^\n]*" + name + "[^\n]*\n?(?:[ \t].*?(?:\n|$))*)",
re.IGNORECASE | re.MULTILINE,
)
return [s.strip() for s in pattern.findall(source)]
def parse(optionDescription: str) -> tuple[str, str, int, Any, str]:
"""Parse an option help text, adapted from docopt."""
short, long, argcount, value = "", "", 0, False
options, _, description = optionDescription.strip().partition(" ")
options = options.replace(",", " ").replace("=", " ")
for section in options.split():
if section.startswith("--"):
long = section
elif section.startswith("-"):
short = section
else:
argcount = 1
if argcount > 0:
matched = re.findall(r"\[default: (.*)\]", description, flags=re.IGNORECASE)
value = matched[0] if matched else ""
return (short, long, argcount, value, description.strip())
def parseOpt(doc: Any) -> list[tuple[str, str, int, Any, str]]:
"""Parse an option help text, adapted from docopt."""
defaults = []
for _section in parseSection("options:", doc):
_, _, section = _section.partition(":")
split = re.split(r"\n[ \t]*(-\S+?)", "\n" + section)[1:]
split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])]
options = [parse(s) for s in split if s.startswith("-")]
defaults += options
return defaults
def parsePos(doc: str) -> list[tuple[str, str]]:
"""Parse positional arguments from docstring."""
defaults = []
for _section in parseSection("arguments:", doc):
_, _, section = _section.partition(":")
defaults.append(
tuple(col.strip() for col in section.strip().partition(" ") if len(col.strip()) > 0)
)
return defaults
def convert(parser: Any) -> ParserRep:
"""Convert getopt to a dict.
Args:
----
parser (Any): docopt parser
Returns:
-------
ParserRep: dictionary representing parser object
"""
return ParserRep(parser_description="", widgets=extract(parser))