g.search.modules.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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: m
  34. #% description: Search in manual pages too (can be slow)
  35. #% guisection: Output
  36. #%end
  37. #%flag
  38. #% key: c
  39. #% description: Use colorized (more readable) output to terminal
  40. #% guisection: Output
  41. #%end
  42. #%flag
  43. #% key: g
  44. #% description: Shell script format
  45. #% guisection: Output
  46. #%end
  47. #%flag
  48. #% key: j
  49. #% description: JSON format
  50. #% guisection: Output
  51. #%end
  52. from __future__ import print_function
  53. import os
  54. import sys
  55. from grass.script.utils import diff_files, try_rmdir
  56. from grass.script import core as grass
  57. try:
  58. import xml.etree.ElementTree as etree
  59. except ImportError:
  60. import elementtree.ElementTree as etree # Python <= 2.4
  61. COLORIZE = False
  62. def main():
  63. global COLORIZE
  64. keywords = options['keyword'].lower().split(',')
  65. AND = flags['a']
  66. manpages = flags['m']
  67. out_format = None
  68. if flags['g']:
  69. out_format = 'shell'
  70. elif flags['j']:
  71. out_format = 'json'
  72. else:
  73. COLORIZE = flags['c']
  74. modules = _search_module(keywords, AND, manpages)
  75. print_results(modules, out_format)
  76. def print_results(data, out_format=None):
  77. """
  78. Print result of the searching method
  79. each data item should have
  80. {
  81. 'name': name of the item,
  82. 'attributes': {
  83. # list of attributes to be shown too
  84. }
  85. }
  86. :param list.<dict> data: input list of found data items
  87. :param str out_format: output format 'shell', 'json', None
  88. """
  89. if not out_format:
  90. _print_results(data)
  91. elif out_format == 'shell':
  92. _print_results_shell(data)
  93. elif out_format == 'json':
  94. _print_results_json(data)
  95. def _print_results_shell(data):
  96. """Print just the name attribute"""
  97. for item in data:
  98. print(item['name'])
  99. def _print_results_json(data):
  100. """Print JSON output"""
  101. import json
  102. print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
  103. def _print_results(data):
  104. import textwrap
  105. for item in data:
  106. print('\n{}'.format(colorize(item['name'], attrs=['bold'])))
  107. for attr in item['attributes']:
  108. out = '{}: {}'.format(attr, item['attributes'][attr])
  109. out = textwrap.wrap(out, width=79, initial_indent=4 * ' ',
  110. subsequent_indent=4 * ' ' + len(attr) * ' ' + ' ')
  111. for line in out:
  112. print(line)
  113. def colorize(text, attrs=None, pattern=None):
  114. """Colorize given text input
  115. :param string text: input text to be colored
  116. :param list.<string> attrs: list of attributes as defined in termcolor package
  117. :param string pattern: text to be highlighted in input text
  118. :return: colored string
  119. """
  120. if COLORIZE:
  121. try:
  122. from termcolor import colored
  123. except ImportError:
  124. grass.fatal(_("Cannot colorize, python-termcolor is not installed"))
  125. else:
  126. def colored(pattern, attrs):
  127. return pattern
  128. if pattern:
  129. return text.replace(pattern, colored(pattern, attrs=attrs))
  130. else:
  131. return colored(text, attrs=attrs)
  132. def _search_module(keywords, logical_and=False, manpages=False):
  133. """Search modules by given keywords
  134. :param list.<str> keywords: list of keywords
  135. :param boolean logical_and: use AND (default OR)
  136. :param boolean manpages: search in manpages too
  137. :return dict: modules
  138. """
  139. WXGUIDIR = os.path.join(os.getenv("GISBASE"), "gui", "wxpython")
  140. filename = os.path.join(WXGUIDIR, 'xml', 'module_items.xml')
  141. menudata_file = open(filename, 'r')
  142. menudata = etree.parse(menudata_file)
  143. menudata_file.close()
  144. items = menudata.findall('module-item')
  145. found_modules = []
  146. for item in items:
  147. name = item.attrib['name']
  148. description = item.find('description').text
  149. module_keywords = item.find('keywords').text
  150. found = [False]
  151. if logical_and:
  152. found = [False] * len(keywords)
  153. for idx in range(len(keywords)):
  154. keyword = keywords[idx]
  155. keyword_found = False
  156. keyword_found = _basic_search(keyword, name, description, module_keywords)
  157. if not keyword_found and manpages:
  158. keyword_found = _manpage_search(keyword, name)
  159. if keyword_found:
  160. if logical_and:
  161. found[idx] = True
  162. else:
  163. found = [True]
  164. description = colorize(description,
  165. attrs=['underline'],
  166. pattern=keyword)
  167. module_keywords = colorize(module_keywords,
  168. attrs=['underline'],
  169. pattern=keyword)
  170. if False not in found:
  171. found_modules.append({
  172. 'name': name,
  173. 'attributes': {
  174. 'keywords': module_keywords,
  175. 'description': description
  176. }
  177. })
  178. return found_modules
  179. def _basic_search(pattern, name, description, module_keywords):
  180. if name.lower().find(pattern) > -1 or\
  181. description.lower().find(pattern) > -1 or\
  182. module_keywords.lower().find(pattern) > -1:
  183. return True
  184. else:
  185. return False
  186. def _manpage_search(pattern, name):
  187. manpage = grass.read_command('g.manual', flags='m', entry=name)
  188. return manpage.lower().find(pattern) > -1
  189. if __name__ == "__main__":
  190. options, flags = grass.parser()
  191. sys.exit(main())