g.search.module.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: g.search.module
  5. # AUTHOR(S): Jachym Cepicky <jachym.cepicky gmail.com>
  6. # PURPOSE: g.search.module 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. from termcolor import colored
  121. else:
  122. def colored(pattern, attrs):
  123. return pattern
  124. if pattern:
  125. return text.replace(pattern, colored(pattern, attrs=attrs))
  126. else:
  127. return colored(text, attrs=attrs)
  128. def _search_module(keywords, logical_and=False, manpages=False):
  129. """Search modules by given keywords
  130. :param list.<str> keywords: list of keywords
  131. :param boolean logical_and: use AND (default OR)
  132. :param boolean manpages: search in manpages too
  133. :return dict: modules
  134. """
  135. WXGUIDIR = os.path.join(os.getenv("GISBASE"), "gui", "wxpython")
  136. filename = os.path.join(WXGUIDIR, 'xml', 'module_items.xml')
  137. menudata_file = open(filename, 'r')
  138. menudata = etree.parse(menudata_file)
  139. menudata_file.close()
  140. items = menudata.findall('module-item')
  141. found_modules = []
  142. for item in items:
  143. name = item.attrib['name']
  144. description = item.find('description').text
  145. module_keywords = item.find('keywords').text
  146. found = [False]
  147. if logical_and:
  148. found = [False] * len(keywords)
  149. for idx in range(len(keywords)):
  150. keyword = keywords[idx]
  151. keyword_found = False
  152. keyword_found = _basic_search(keyword, name, description, module_keywords)
  153. if not keyword_found and manpages:
  154. keyword_found = _manpage_search(keyword, name)
  155. if keyword_found:
  156. if logical_and:
  157. found[idx] = True
  158. else:
  159. found = [True]
  160. description = colorize(description,
  161. attrs=['underline'],
  162. pattern=keyword)
  163. module_keywords = colorize(module_keywords,
  164. attrs=['underline'],
  165. pattern=keyword)
  166. if False not in found:
  167. found_modules.append({
  168. 'name': name,
  169. 'attributes': {
  170. 'keywords': module_keywords,
  171. 'description': description
  172. }
  173. })
  174. return found_modules
  175. def _basic_search(pattern, name, description, module_keywords):
  176. if name.lower().find(pattern) > -1 or\
  177. description.lower().find(pattern) > -1 or\
  178. module_keywords.lower().find(pattern) > -1:
  179. return True
  180. else:
  181. return False
  182. def _manpage_search(pattern, name):
  183. manpage = grass.read_command('g.manual', flags='m', entry=name)
  184. return manpage.lower().find(pattern) > -1
  185. if __name__ == "__main__":
  186. options, flags = grass.parser()
  187. sys.exit(main())