g.search.modules.py 6.2 KB

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