g.search.modules.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: g.search.modules
  5. # AUTHOR(S): Jachym Cepicky <jachym.cepicky gmail.com>
  6. # PURPOSE: g.search.modules in grass modules using keywords
  7. # COPYRIGHT: (C) 2015-2016 by the GRASS Development Team
  8. #
  9. # This program is free software under the GNU General
  10. # Public License (>=v2). Read the file COPYING that
  11. # comes with GRASS for details.
  12. #
  13. #############################################################################
  14. #%module
  15. #% description: Search in GRASS modules using keywords
  16. #% keyword: general
  17. #% keyword: modules
  18. #% keyword: search
  19. #%end
  20. #%option
  21. #% key: keyword
  22. #% multiple: yes
  23. #% type: string
  24. #% description: Keyword to be searched
  25. #% required : yes
  26. #%end
  27. #%flag
  28. #% key: a
  29. #% description: Display only modules where all keywords are available (AND), default: OR
  30. #% guisection: Output
  31. #%end
  32. #%flag
  33. #% key: n
  34. #% description: Invert selection (logical NOT)
  35. #% guisection: Output
  36. #%end
  37. #%flag
  38. #% key: m
  39. #% description: Search in manual pages too (can be slow)
  40. #% guisection: Output
  41. #%end
  42. #%flag
  43. #% key: k
  44. #% label: Search only for the exact keyword in module keyword list
  45. #% description: Instead of full text search, search only in actual keywords
  46. #% guisection: Output
  47. #%end
  48. #%flag
  49. #% key: c
  50. #% description: Use colorized (more readable) output to terminal
  51. #% guisection: Output
  52. #%end
  53. #%flag
  54. #% key: g
  55. #% description: Shell script format
  56. #% guisection: Output
  57. #%end
  58. #%flag
  59. #% key: j
  60. #% description: JSON format
  61. #% guisection: Output
  62. #%end
  63. from __future__ import print_function
  64. import os
  65. import sys
  66. from grass.script.utils import diff_files, try_rmdir
  67. from grass.script import core as grass
  68. # i18N
  69. import gettext
  70. gettext.install('grassmods', os.path.join(os.getenv("GISBASE"), 'locale'))
  71. try:
  72. import xml.etree.ElementTree as etree
  73. except ImportError:
  74. import elementtree.ElementTree as etree # Python <= 2.4
  75. COLORIZE = False
  76. def main():
  77. global COLORIZE
  78. AND = flags['a']
  79. NOT = flags['n']
  80. manpages = flags['m']
  81. exact_keywords = flags['k']
  82. out_format = None
  83. if flags['g']:
  84. out_format = 'shell'
  85. elif flags['j']:
  86. out_format = 'json'
  87. else:
  88. COLORIZE = flags['c']
  89. if exact_keywords:
  90. keywords = options['keyword'].split(',')
  91. else:
  92. keywords = options['keyword'].lower().split(',')
  93. modules = _search_module(keywords, AND, NOT, manpages, exact_keywords)
  94. print_results(modules, out_format)
  95. def print_results(data, out_format=None):
  96. """
  97. Print result of the searching method
  98. each data item should have
  99. {
  100. 'name': name of the item,
  101. 'attributes': {
  102. # list of attributes to be shown too
  103. }
  104. }
  105. :param list.<dict> data: input list of found data items
  106. :param str out_format: output format 'shell', 'json', None
  107. """
  108. if not out_format:
  109. _print_results(data)
  110. elif out_format == 'shell':
  111. _print_results_shell(data)
  112. elif out_format == 'json':
  113. _print_results_json(data)
  114. def _print_results_shell(data):
  115. """Print just the name attribute"""
  116. for item in data:
  117. print(item['name'])
  118. def _print_results_json(data):
  119. """Print JSON output"""
  120. import json
  121. print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
  122. def _print_results(data):
  123. import textwrap
  124. for item in data:
  125. print('\n{0}'.format(colorize(item['name'], attrs=['bold'])))
  126. for attr in item['attributes']:
  127. out = '{0}: {1}'.format(attr, item['attributes'][attr])
  128. out = textwrap.wrap(out, width=79, initial_indent=4 * ' ',
  129. subsequent_indent=4 * ' ' + len(attr) * ' ' + ' ')
  130. for line in out:
  131. print(line)
  132. def colorize(text, attrs=None, pattern=None):
  133. """Colorize given text input
  134. :param string text: input text to be colored
  135. :param list.<string> attrs: list of attributes as defined in termcolor package
  136. :param string pattern: text to be highlighted in input text
  137. :return: colored string
  138. """
  139. if COLORIZE:
  140. try:
  141. from termcolor import colored
  142. except ImportError:
  143. grass.fatal(_("Cannot colorize, python-termcolor is not installed"))
  144. else:
  145. def colored(pattern, attrs):
  146. return pattern
  147. if pattern:
  148. return text.replace(pattern, colored(pattern, attrs=attrs))
  149. else:
  150. return colored(text, attrs=attrs)
  151. def _search_module(keywords, logical_and=False, invert=False, manpages=False,
  152. exact_keywords=False):
  153. """Search modules by given keywords
  154. :param list.<str> keywords: list of keywords
  155. :param boolean logical_and: use AND (default OR)
  156. :param boolean manpages: search in manpages too
  157. :return dict: modules
  158. """
  159. WXGUIDIR = os.path.join(os.getenv("GISBASE"), "gui", "wxpython")
  160. filename = os.path.join(WXGUIDIR, 'xml', 'module_items.xml')
  161. menudata_file = open(filename, 'r')
  162. menudata = etree.parse(menudata_file)
  163. menudata_file.close()
  164. items = menudata.findall('module-item')
  165. found_modules = []
  166. for item in items:
  167. name = item.attrib['name']
  168. description = item.find('description').text
  169. module_keywords = item.find('keywords').text
  170. found = [False]
  171. if logical_and:
  172. found = [False] * len(keywords)
  173. for idx in range(len(keywords)):
  174. keyword = keywords[idx]
  175. keyword_found = False
  176. if exact_keywords:
  177. keyword_found = _exact_search(keyword, module_keywords)
  178. else:
  179. keyword_found = _basic_search(keyword, name, description,
  180. module_keywords)
  181. if not keyword_found and manpages:
  182. keyword_found = _manpage_search(keyword, name)
  183. if keyword_found:
  184. if logical_and:
  185. found[idx] = True
  186. else:
  187. found = [True]
  188. description = colorize(description,
  189. attrs=['underline'],
  190. pattern=keyword)
  191. module_keywords = colorize(module_keywords,
  192. attrs=['underline'],
  193. pattern=keyword)
  194. add = False not in found
  195. if invert:
  196. add = not add
  197. if add:
  198. found_modules.append({
  199. 'name': name,
  200. 'attributes': {
  201. 'keywords': module_keywords,
  202. 'description': description
  203. }
  204. })
  205. return found_modules
  206. def _basic_search(pattern, name, description, module_keywords):
  207. """Search for a string in all the provided strings.
  208. This lowercases the strings before searching in them, so the pattern
  209. string should be lowercased too.
  210. """
  211. if name.lower().find(pattern) > -1 or\
  212. description.lower().find(pattern) > -1 or\
  213. module_keywords.lower().find(pattern) > -1:
  214. return True
  215. else:
  216. return False
  217. def _exact_search(keyword, module_keywords):
  218. """Compare exact keyword with module keywords
  219. :param keyword: exact keyword to find in the list (not lowercased)
  220. :param module_keywords: comma separated list of keywords
  221. """
  222. module_keywords = module_keywords.split(',')
  223. for current in module_keywords:
  224. if keyword == current:
  225. return True
  226. return False
  227. def _manpage_search(pattern, name):
  228. manpage = grass.read_command('g.manual', flags='m', entry=name)
  229. return manpage.lower().find(pattern) > -1
  230. if __name__ == "__main__":
  231. options, flags = grass.parser()
  232. sys.exit(main())