-
-
Notifications
You must be signed in to change notification settings - Fork 288
/
g.search.modules.py
executable file
·292 lines (232 loc) · 7.67 KB
/
g.search.modules.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
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
#!/usr/bin/env python
############################################################################
#
# MODULE: g.search.modules
# AUTHOR(S): Jachym Cepicky <jachym.cepicky gmail.com>
# PURPOSE: g.search.modules in grass modules using keywords
# COPYRIGHT: (C) 2015-2016 by the GRASS Development Team
#
# This program is free software under the GNU General
# Public License (>=v2). Read the file COPYING that
# comes with GRASS for details.
#
#############################################################################
#%module
#% description: Search in GRASS modules using keywords
#% keyword: general
#% keyword: modules
#% keyword: search
#%end
#%option
#% key: keyword
#% multiple: yes
#% type: string
#% description: Keyword to be searched
#% required : yes
#%end
#%flag
#% key: a
#% description: Display only modules where all keywords are available (AND), default: OR
#% guisection: Output
#%end
#%flag
#% key: n
#% description: Invert selection (logical NOT)
#% guisection: Output
#%end
#%flag
#% key: m
#% description: Search in manual pages too (can be slow)
#% guisection: Output
#%end
#%flag
#% key: k
#% label: Search only for the exact keyword in module keyword list
#% description: Instead of full text search, search only in actual keywords
#% guisection: Output
#%end
#%flag
#% key: c
#% description: Use colorized (more readable) output to terminal
#% guisection: Output
#%end
#%flag
#% key: g
#% description: Shell script format
#% guisection: Output
#%end
#%flag
#% key: j
#% description: JSON format
#% guisection: Output
#%end
from __future__ import print_function
import os
import sys
from grass.script.utils import diff_files, try_rmdir
from grass.script import core as grass
# i18N
import gettext
gettext.install('grassmods', os.path.join(os.getenv("GISBASE"), 'locale'))
try:
import xml.etree.ElementTree as etree
except ImportError:
import elementtree.ElementTree as etree # Python <= 2.4
COLORIZE = False
def main():
global COLORIZE
AND = flags['a']
NOT = flags['n']
manpages = flags['m']
exact_keywords = flags['k']
out_format = None
if flags['g']:
out_format = 'shell'
elif flags['j']:
out_format = 'json'
else:
COLORIZE = flags['c']
if exact_keywords:
keywords = options['keyword'].split(',')
else:
keywords = options['keyword'].lower().split(',')
modules = _search_module(keywords, AND, NOT, manpages, exact_keywords)
print_results(modules, out_format)
def print_results(data, out_format=None):
"""
Print result of the searching method
each data item should have
{
'name': name of the item,
'attributes': {
# list of attributes to be shown too
}
}
:param list.<dict> data: input list of found data items
:param str out_format: output format 'shell', 'json', None
"""
if not out_format:
_print_results(data)
elif out_format == 'shell':
_print_results_shell(data)
elif out_format == 'json':
_print_results_json(data)
def _print_results_shell(data):
"""Print just the name attribute"""
for item in data:
print(item['name'])
def _print_results_json(data):
"""Print JSON output"""
import json
print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
def _print_results(data):
import textwrap
for item in data:
print('\n{0}'.format(colorize(item['name'], attrs=['bold'])))
for attr in item['attributes']:
out = '{0}: {1}'.format(attr, item['attributes'][attr])
out = textwrap.wrap(out, width=79, initial_indent=4 * ' ',
subsequent_indent=4 * ' ' + len(attr) * ' ' + ' ')
for line in out:
print(line)
def colorize(text, attrs=None, pattern=None):
"""Colorize given text input
:param string text: input text to be colored
:param list.<string> attrs: list of attributes as defined in termcolor package
:param string pattern: text to be highlighted in input text
:return: colored string
"""
if COLORIZE:
try:
from termcolor import colored
except ImportError:
grass.fatal(_("Cannot colorize, python-termcolor is not installed"))
else:
def colored(pattern, attrs):
return pattern
if pattern:
return text.replace(pattern, colored(pattern, attrs=attrs))
else:
return colored(text, attrs=attrs)
def _search_module(keywords, logical_and=False, invert=False, manpages=False,
exact_keywords=False):
"""Search modules by given keywords
:param list.<str> keywords: list of keywords
:param boolean logical_and: use AND (default OR)
:param boolean manpages: search in manpages too
:return dict: modules
"""
WXGUIDIR = os.path.join(os.getenv("GISBASE"), "gui", "wxpython")
filename = os.path.join(WXGUIDIR, 'xml', 'module_items.xml')
menudata_file = open(filename, 'r')
menudata = etree.parse(menudata_file)
menudata_file.close()
items = menudata.findall('module-item')
found_modules = []
for item in items:
name = item.attrib['name']
description = item.find('description').text
module_keywords = item.find('keywords').text
found = [False]
if logical_and:
found = [False] * len(keywords)
for idx in range(len(keywords)):
keyword = keywords[idx]
keyword_found = False
if exact_keywords:
keyword_found = _exact_search(keyword, module_keywords)
else:
keyword_found = _basic_search(keyword, name, description,
module_keywords)
if not keyword_found and manpages:
keyword_found = _manpage_search(keyword, name)
if keyword_found:
if logical_and:
found[idx] = True
else:
found = [True]
description = colorize(description,
attrs=['underline'],
pattern=keyword)
module_keywords = colorize(module_keywords,
attrs=['underline'],
pattern=keyword)
add = False not in found
if invert:
add = not add
if add:
found_modules.append({
'name': name,
'attributes': {
'keywords': module_keywords,
'description': description
}
})
return found_modules
def _basic_search(pattern, name, description, module_keywords):
"""Search for a string in all the provided strings.
This lowercases the strings before searching in them, so the pattern
string should be lowercased too.
"""
if name.lower().find(pattern) > -1 or\
description.lower().find(pattern) > -1 or\
module_keywords.lower().find(pattern) > -1:
return True
else:
return False
def _exact_search(keyword, module_keywords):
"""Compare exact keyword with module keywords
:param keyword: exact keyword to find in the list (not lowercased)
:param module_keywords: comma separated list of keywords
"""
module_keywords = module_keywords.split(',')
for current in module_keywords:
if keyword == current:
return True
return False
def _manpage_search(pattern, name):
manpage = grass.read_command('g.manual', flags='m', entry=name)
return manpage.lower().find(pattern) > -1
if __name__ == "__main__":
options, flags = grass.parser()
sys.exit(main())