g.search.modules.py 6.5 KB

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