forked from OSGeo/grass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser_standard_options.py
242 lines (222 loc) · 7.35 KB
/
parser_standard_options.py
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
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 26 19:10:58 2015
@author: pietro
"""
from __future__ import print_function
import argparse
import sys
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from build_html import *
def parse_options(lines, startswith="Opt"):
def split_in_groups(lines):
def count_par_diff(line):
open_par = line.count("(")
close_par = line.count(")")
return open_par - close_par
res = None
diff = 0
for line in lines:
if line.startswith("case"):
optname = line.split()[1][:-1]
res = []
# if optname == 'G_OPT_R_BASENAME_INPUT':
# import ipdb; ipdb.set_trace()
elif line == "break;":
diff = 0
yield optname, res
elif line.startswith("G_"):
diff = count_par_diff(line)
elif diff > 0:
diff -= count_par_diff(line)
else:
res.append(line) if res is not None else None
def split_opt_line(line):
index = line.index("=")
key = line[:index].strip()
default = line[index + 1 :].strip()
if default.startswith("_("):
default = default[2:]
return key, default
def parse_glines(glines):
res = {}
key = None
dynamic_answer = False
for line in glines:
if line.strip() == "/* start dynamic answer */":
dynamic_answer = True
if line.strip() == "/* end dynamic answer */":
dynamic_answer = False
if dynamic_answer or line.startswith("/*"):
continue
if line.startswith("/*"):
continue
if line.startswith(startswith) and line.endswith(";"):
key, default = [w.strip() for w in split_opt_line(line[5:])]
res[key] = default
elif line.startswith(startswith):
key, default = split_opt_line(line[5:])
res[key] = [
default,
]
else:
if key is not None:
if key not in res:
res[key] = []
start, end = 0, -1
if line.startswith("_("):
start = 2
if line.endswith(");"):
end = -3
elif line.endswith(";"):
end = -2
res[key].append(line[start:end])
# pprint(glines)
# pprint(res)
return res
def clean_value(val):
if isinstance(val, list):
val = " ".join(val)
return (
(val.replace('"', "").replace("'", "'").strip().strip(";"))
.strip()
.strip("_(")
.strip()
.strip(")")
.strip()
)
# with open(optionfile, mode='r') as optfile:
lines = [line.strip() for line in lines]
result = []
for optname, glines in split_in_groups(lines):
if glines:
res = parse_glines(glines)
if res:
for key, val in res.items():
res[key] = clean_value(val)
result.append((optname, res))
return result
class OptTable(object):
""""""
def __init__(self, list_of_dict):
self.options = list_of_dict
self.columns = sorted(set([key for _, d in self.options for key in d.keys()]))
def csv(self, delimiter=";", endline="\n"):
"""Return a CSV string with the options"""
csv = []
csv.append(delimiter.join(self.columns))
for optname, options in self.options:
opts = [options.get(col, "") for col in self.columns]
csv.append(
delimiter.join(
[
optname,
]
+ opts
)
)
return endline.join(csv)
def html(self, endline="\n", indent=" ", toptions="border=1"):
"""Return a HTML table with the options"""
html = ["<table{0}>".format(" " + toptions if toptions else "")]
# write headers
html.append(indent + "<thead>")
html.append(indent + "<tr>")
html.append(indent * 2 + "<th>{0}</th>".format("option"))
for col in self.columns:
html.append(indent * 2 + "<th>{0}</th>".format(col))
html.append(indent + "</tr>")
html.append(indent + "</thead>")
html.append(indent + "<tbody>")
for optname, options in self.options:
html.append(indent + "<tr>")
html.append(indent * 2 + "<td>{0}</td>".format(optname))
for col in self.columns:
html.append(indent * 2 + "<td>{0}</td>".format(options.get(col, "")))
html.append(indent + "</tr>")
html.append(indent + "</tbody>")
html.append("</table>")
return endline.join(html)
def _repr_html_(self):
"""Method used by IPython notebook"""
return self.html()
if __name__ == "__main__":
URL = (
"https://trac.osgeo.org/grass/browser/grass/"
"trunk/lib/gis/parser_standard_options.c?format=txt"
)
parser = argparse.ArgumentParser(
description="Extract GRASS default " "options from link."
)
parser.add_argument(
"-f",
"--format",
default="html",
dest="format",
choices=["html", "csv", "grass"],
help="Define the output format",
)
parser.add_argument(
"-l",
"--link",
default=URL,
dest="url",
type=str,
help="Provide the url with the file to parse",
)
parser.add_argument(
"-t",
"--text",
dest="text",
type=argparse.FileType("r"),
help="Provide the file to parse",
)
parser.add_argument(
"-o",
"--output",
default=sys.stdout,
dest="output",
type=argparse.FileType("w"),
help="Provide the url with the file to parse",
)
parser.add_argument(
"-s",
"--starts-with",
default="Opt",
dest="startswith",
type=str,
help="Extract only the options that starts with this",
)
parser.add_argument(
"-p",
"--html_params",
default="border=1",
type=str,
dest="htmlparmas",
help="Options for the HTML table",
)
args = parser.parse_args()
cfile = args.text if args.text else urlopen(args.url, proxies=None)
options = OptTable(parse_options(cfile.readlines(), startswith=args.startswith))
outform = args.format
if outform in ["csv", "html"]:
print(getattr(options, outform)(), file=args.output)
args.output.close()
else:
year = os.getenv("VERSION_DATE")
name = args.output.name
args.output.close()
topicsfile = open(name, "w")
topicsfile.write(
header1_tmpl.substitute(
title="GRASS GIS "
"%s Reference Manual: Parser standard options index" % grass_version
)
)
topicsfile.write(headerpso_tmpl)
topicsfile.write(options.html(toptions=args.htmlparmas))
write_html_footer(topicsfile, "index.html", year)
topicsfile.close()