task.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. """
  2. Get interface description of GRASS commands
  3. Based on gui/wxpython/gui_modules/menuform.py
  4. Usage:
  5. ::
  6. from grass.script import task as gtask
  7. gtask.command_info('r.info')
  8. (C) 2011 by the GRASS Development Team
  9. This program is free software under the GNU General Public
  10. License (>=v2). Read the file COPYING that comes with GRASS
  11. for details.
  12. .. sectionauthor:: Martin Landa <landa.martin gmail.com>
  13. """
  14. import re
  15. import sys
  16. import string
  17. if sys.version_info.major == 3:
  18. unicode = str
  19. try:
  20. import xml.etree.ElementTree as etree
  21. except ImportError:
  22. import elementtree.ElementTree as etree # Python <= 2.4
  23. from xml.parsers import expat # TODO: works for any Python?
  24. # Get the XML parsing exceptions to catch. The behavior chnaged with Python 2.7
  25. # and ElementTree 1.3.
  26. if hasattr(etree, 'ParseError'):
  27. ETREE_EXCEPTIONS = (etree.ParseError, expat.ExpatError)
  28. else:
  29. ETREE_EXCEPTIONS = (expat.ExpatError)
  30. from .utils import encode, decode, split
  31. from .core import *
  32. class grassTask:
  33. """This class holds the structures needed for filling by the parser
  34. Parameter blackList is a dictionary with fixed structure, eg.
  35. ::
  36. blackList = {'items' : {'d.legend' : { 'flags' : ['m'], 'params' : [] }},
  37. 'enabled': True}
  38. :param str path: full path
  39. :param blackList: hide some options in the GUI (dictionary)
  40. """
  41. def __init__(self, path=None, blackList=None):
  42. self.path = path
  43. self.name = _('unknown')
  44. self.params = list()
  45. self.description = ''
  46. self.label = ''
  47. self.flags = list()
  48. self.keywords = list()
  49. self.errorMsg = ''
  50. self.firstParam = None
  51. if blackList:
  52. self.blackList = blackList
  53. else:
  54. self.blackList = {'enabled': False, 'items': {}}
  55. if path is not None:
  56. try:
  57. processTask(tree=etree.fromstring(get_interface_description(path)),
  58. task=self)
  59. except ScriptError as e:
  60. self.errorMsg = e.value
  61. self.define_first()
  62. def define_first(self):
  63. """Define first parameter
  64. :return: name of first parameter
  65. """
  66. if len(self.params) > 0:
  67. self.firstParam = self.params[0]['name']
  68. return self.firstParam
  69. def get_error_msg(self):
  70. """Get error message ('' for no error)
  71. """
  72. return self.errorMsg
  73. def get_name(self):
  74. """Get task name
  75. """
  76. if sys.platform == 'win32':
  77. name, ext = os.path.splitext(self.name)
  78. if ext in ('.py', '.sh'):
  79. return name
  80. else:
  81. return self.name
  82. return self.name
  83. def get_description(self, full=True):
  84. """Get module's description
  85. :param bool full: True for label + desc
  86. """
  87. if self.label:
  88. if full:
  89. return self.label + ' ' + self.description
  90. else:
  91. return self.label
  92. else:
  93. return self.description
  94. def get_keywords(self):
  95. """Get module's keywords
  96. """
  97. return self.keywords
  98. def get_list_params(self, element='name'):
  99. """Get list of parameters
  100. :param str element: element name
  101. """
  102. params = []
  103. for p in self.params:
  104. params.append(p[element])
  105. return params
  106. def get_list_flags(self, element='name'):
  107. """Get list of flags
  108. :param str element: element name
  109. """
  110. flags = []
  111. for p in self.flags:
  112. flags.append(p[element])
  113. return flags
  114. def get_param(self, value, element='name', raiseError=True):
  115. """Find and return a param by name
  116. :param value: param's value
  117. :param str element: element name
  118. :param bool raiseError: True for raise on error
  119. """
  120. for p in self.params:
  121. val = p.get(element, None)
  122. if val is None:
  123. continue
  124. if isinstance(val, (list, tuple)):
  125. if value in val:
  126. return p
  127. elif isinstance(val, (bytes, unicode)):
  128. if p[element][:len(value)] == value:
  129. return p
  130. else:
  131. if p[element] == value:
  132. return p
  133. if raiseError:
  134. raise ValueError(_("Parameter element '%(element)s' not found: '%(value)s'") % \
  135. { 'element' : element, 'value' : value })
  136. else:
  137. return None
  138. def get_flag(self, aFlag):
  139. """Find and return a flag by name
  140. Raises ValueError when the flag is not found.
  141. :param str aFlag: name of the flag
  142. """
  143. for f in self.flags:
  144. if f['name'] == aFlag:
  145. return f
  146. raise ValueError(_("Flag not found: %s") % aFlag)
  147. def get_cmd_error(self):
  148. """Get error string produced by get_cmd(ignoreErrors = False)
  149. :return: list of errors
  150. """
  151. errorList = list()
  152. # determine if suppress_required flag is given
  153. for f in self.flags:
  154. if f['value'] and f['suppress_required']:
  155. return errorList
  156. for p in self.params:
  157. if not p.get('value', '') and p.get('required', False):
  158. if not p.get('default', ''):
  159. desc = p.get('label', '')
  160. if not desc:
  161. desc = p['description']
  162. errorList.append(_("Parameter '%(name)s' (%(desc)s) is missing.") % \
  163. {'name': p['name'], 'desc': encode(desc)})
  164. return errorList
  165. def get_cmd(self, ignoreErrors=False, ignoreRequired=False,
  166. ignoreDefault=True):
  167. """Produce an array of command name and arguments for feeding
  168. into some execve-like command processor.
  169. :param bool ignoreErrors: True to return whatever has been built so
  170. far, even though it would not be a correct
  171. command for GRASS
  172. :param bool ignoreRequired: True to ignore required flags, otherwise
  173. '@<required@>' is shown
  174. :param bool ignoreDefault: True to ignore parameters with default values
  175. """
  176. cmd = [self.get_name()]
  177. suppress_required = False
  178. for flag in self.flags:
  179. if flag['value']:
  180. if len(flag['name']) > 1: # e.g. overwrite
  181. cmd += ['--' + flag['name']]
  182. else:
  183. cmd += ['-' + flag['name']]
  184. if flag['suppress_required']:
  185. suppress_required = True
  186. for p in self.params:
  187. if p.get('value', '') == '' and p.get('required', False):
  188. if p.get('default', '') != '':
  189. cmd += ['%s=%s' % (p['name'], p['default'])]
  190. elif ignoreErrors and not suppress_required and not ignoreRequired:
  191. cmd += ['%s=%s' % (p['name'], _('<required>'))]
  192. elif p.get('value', '') == '' and p.get('default', '') != '' and not ignoreDefault:
  193. cmd += ['%s=%s' % (p['name'], p['default'])]
  194. elif p.get('value', '') != '' and \
  195. (p['value'] != p.get('default', '') or not ignoreDefault):
  196. # output only values that have been set, and different from defaults
  197. cmd += ['%s=%s' % (p['name'], p['value'])]
  198. errList = self.get_cmd_error()
  199. if ignoreErrors is False and errList:
  200. raise ValueError('\n'.join(errList))
  201. return cmd
  202. def get_options(self):
  203. """Get options
  204. """
  205. return {'flags': self.flags, 'params': self.params}
  206. def has_required(self):
  207. """Check if command has at least one required parameter
  208. """
  209. for p in self.params:
  210. if p.get('required', False):
  211. return True
  212. return False
  213. def set_param(self, aParam, aValue, element='value'):
  214. """Set param value/values.
  215. """
  216. try:
  217. param = self.get_param(aParam)
  218. except ValueError:
  219. return
  220. param[element] = aValue
  221. def set_flag(self, aFlag, aValue, element='value'):
  222. """Enable / disable flag.
  223. """
  224. try:
  225. param = self.get_flag(aFlag)
  226. except ValueError:
  227. return
  228. param[element] = aValue
  229. def set_options(self, opts):
  230. """Set flags and parameters
  231. :param opts list of flags and parameters"""
  232. for opt in opts:
  233. if opt[0] == '-': # flag
  234. self.set_flag(opt.lstrip('-'), True)
  235. else: # parameter
  236. key, value = opt.split('=', 1)
  237. self.set_param(key, value)
  238. class processTask:
  239. """A ElementTree handler for the --interface-description output,
  240. as defined in grass-interface.dtd. Extend or modify this and the
  241. DTD if the XML output of GRASS' parser is extended or modified.
  242. :param tree: root tree node
  243. :param task: grassTask instance or None
  244. :param blackList: list of flags/params to hide
  245. :return: grassTask instance
  246. """
  247. def __init__(self, tree, task=None, blackList=None):
  248. if task:
  249. self.task = task
  250. else:
  251. self.task = grassTask()
  252. if blackList:
  253. self.task.blackList = blackList
  254. self.root = tree
  255. self._process_module()
  256. self._process_params()
  257. self._process_flags()
  258. self.task.define_first()
  259. def _process_module(self):
  260. """Process module description
  261. """
  262. self.task.name = self.root.get('name', default='unknown')
  263. # keywords
  264. for keyword in self._get_node_text(self.root, 'keywords').split(','):
  265. self.task.keywords.append(keyword.strip())
  266. self.task.label = self._get_node_text(self.root, 'label')
  267. self.task.description = self._get_node_text(self.root, 'description')
  268. def _process_params(self):
  269. """Process parameters
  270. """
  271. for p in self.root.findall('parameter'):
  272. # gisprompt
  273. node_gisprompt = p.find('gisprompt')
  274. gisprompt = False
  275. age = element = prompt = None
  276. if node_gisprompt is not None:
  277. gisprompt = True
  278. age = node_gisprompt.get('age', '')
  279. element = node_gisprompt.get('element', '')
  280. prompt = node_gisprompt.get('prompt', '')
  281. # value(s)
  282. values = []
  283. values_desc = []
  284. node_values = p.find('values')
  285. if node_values is not None:
  286. for pv in node_values.findall('value'):
  287. values.append(self._get_node_text(pv, 'name'))
  288. desc = self._get_node_text(pv, 'description')
  289. if desc:
  290. values_desc.append(desc)
  291. # keydesc
  292. key_desc = []
  293. node_key_desc = p.find('keydesc')
  294. if node_key_desc is not None:
  295. for ki in node_key_desc.findall('item'):
  296. key_desc.append(ki.text)
  297. if p.get('multiple', 'no') == 'yes':
  298. multiple = True
  299. else:
  300. multiple = False
  301. if p.get('required', 'no') == 'yes':
  302. required = True
  303. else:
  304. required = False
  305. if self.task.blackList['enabled'] and \
  306. self.task.name in self.task.blackList['items'] and \
  307. p.get('name') in self.task.blackList['items'][self.task.name].get('params', []):
  308. hidden = True
  309. else:
  310. hidden = False
  311. self.task.params.append( {
  312. "name" : p.get('name'),
  313. "type" : p.get('type'),
  314. "required" : required,
  315. "multiple" : multiple,
  316. "label" : self._get_node_text(p, 'label'),
  317. "description" : self._get_node_text(p, 'description'),
  318. 'gisprompt' : gisprompt,
  319. 'age' : age,
  320. 'element' : element,
  321. 'prompt' : prompt,
  322. "guisection" : self._get_node_text(p, 'guisection'),
  323. "guidependency" : self._get_node_text(p, 'guidependency'),
  324. "default" : self._get_node_text(p, 'default'),
  325. "values" : values,
  326. "values_desc" : values_desc,
  327. "value" : '',
  328. "key_desc" : key_desc,
  329. "hidden" : hidden
  330. })
  331. def _process_flags(self):
  332. """Process flags
  333. """
  334. for p in self.root.findall('flag'):
  335. if self.task.blackList['enabled'] and \
  336. self.task.name in self.task.blackList['items'] and \
  337. p.get('name') in self.task.blackList['items'][self.task.name].get('flags', []):
  338. hidden = True
  339. else:
  340. hidden = False
  341. if p.find('suppress_required') is not None:
  342. suppress_required = True
  343. else:
  344. suppress_required = False
  345. self.task.flags.append( {
  346. "name" : p.get('name'),
  347. "label" : self._get_node_text(p, 'label'),
  348. "description" : self._get_node_text(p, 'description'),
  349. "guisection" : self._get_node_text(p, 'guisection'),
  350. "suppress_required" : suppress_required,
  351. "value" : False,
  352. "hidden" : hidden
  353. } )
  354. def _get_node_text(self, node, tag, default=''):
  355. """Get node text"""
  356. p = node.find(tag)
  357. if p is not None:
  358. res = ' '.join(p.text.split())
  359. return res
  360. return default
  361. def get_task(self):
  362. """Get grassTask instance"""
  363. return self.task
  364. def convert_xml_to_utf8(xml_text):
  365. # enc = locale.getdefaultlocale()[1]
  366. # modify: fetch encoding from the interface description text(xml)
  367. # e.g. <?xml version="1.0" encoding="GBK"?>
  368. pattern = re.compile(b'<\?xml[^>]*\Wencoding="([^"]*)"[^>]*\?>')
  369. m = re.match(pattern, xml_text)
  370. if m is None:
  371. return xml_text.encode("utf-8") if xml_text else None
  372. #
  373. enc = m.groups()[0]
  374. # modify: change the encoding to "utf-8", for correct parsing
  375. xml_text_utf8 = xml_text.decode(enc.decode('ascii')).encode("utf-8")
  376. p = re.compile(b'encoding="' + enc + b'"', re.IGNORECASE)
  377. xml_text_utf8 = p.sub(b'encoding="utf-8"', xml_text_utf8)
  378. return xml_text_utf8
  379. def get_interface_description(cmd):
  380. """Returns the XML description for the GRASS cmd (force text encoding to
  381. "utf-8").
  382. The DTD must be located in $GISBASE/gui/xml/grass-interface.dtd,
  383. otherwise the parser will not succeed.
  384. :param cmd: command (name of GRASS module)
  385. """
  386. try:
  387. p = Popen([cmd, '--interface-description'], stdout=PIPE,
  388. stderr=PIPE)
  389. cmdout, cmderr = p.communicate()
  390. # TODO: do it better (?)
  391. if not cmdout and sys.platform == 'win32':
  392. # we in fact expect pure module name (without extension)
  393. # so, lets remove extension
  394. if cmd.endswith('.py'):
  395. cmd = os.path.splitext(cmd)[0]
  396. if cmd == 'd.rast3d':
  397. sys.path.insert(0, os.path.join(os.getenv('GISBASE'),
  398. 'gui', 'scripts'))
  399. p = Popen([sys.executable, get_real_command(cmd),
  400. '--interface-description'],
  401. stdout=PIPE, stderr=PIPE)
  402. cmdout, cmderr = p.communicate()
  403. if cmd == 'd.rast3d':
  404. del sys.path[0] # remove gui/scripts from the path
  405. if p.returncode != 0:
  406. raise ScriptError(_("Unable to fetch interface description for command '<{cmd}>'."
  407. "\n\nDetails: <{det}>").format(cmd=cmd, det=decode(cmderr)))
  408. except OSError as e:
  409. raise ScriptError(_("Unable to fetch interface description for command '<{cmd}>'."
  410. "\n\nDetails: <{det}>").format(cmd=cmd, det=e))
  411. desc = convert_xml_to_utf8(cmdout)
  412. desc = desc.replace(b'grass-interface.dtd',
  413. os.path.join(os.getenv('GISBASE'), 'gui', 'xml',
  414. 'grass-interface.dtd').encode('utf-8'))
  415. return desc
  416. def parse_interface(name, parser=processTask, blackList=None):
  417. """Parse interface of given GRASS module
  418. The *name* is either GRASS module name (of a module on path) or
  419. a full or relative path to an executable.
  420. :param str name: name of GRASS module to be parsed
  421. :param parser:
  422. :param blackList:
  423. """
  424. try:
  425. tree = etree.fromstring(get_interface_description(name))
  426. except ETREE_EXCEPTIONS as error:
  427. raise ScriptError(_("Cannot parse interface description of"
  428. "<{name}> module: {error}").format(name=name, error=error))
  429. task = parser(tree, blackList=blackList).get_task()
  430. # if name from interface is different than the originally
  431. # provided name, then the provided name is likely a full path needed
  432. # to actually run the module later
  433. # (processTask uses only the XML which does not contain the original
  434. # path used to execute the module)
  435. if task.name != name:
  436. task.path = name
  437. return task
  438. def command_info(cmd):
  439. """Returns meta information for any GRASS command as dictionary
  440. with entries for description, keywords, usage, flags, and
  441. parameters, e.g.
  442. >>> command_info('g.tempfile') # doctest: +NORMALIZE_WHITESPACE
  443. {'keywords': ['general', 'support'], 'params': [{'gisprompt': False,
  444. 'multiple': False, 'name': 'pid', 'guidependency': '', 'default': '',
  445. 'age': None, 'required': True, 'value': '', 'label': '', 'guisection': '',
  446. 'key_desc': [], 'values': [], 'values_desc': [], 'prompt': None,
  447. 'hidden': False, 'element': None, 'type': 'integer', 'description':
  448. 'Process id to use when naming the tempfile'}], 'flags': [{'description':
  449. "Dry run - don't create a file, just prints it's file name", 'value':
  450. False, 'label': '', 'guisection': '', 'suppress_required': False,
  451. 'hidden': False, 'name': 'd'}, {'description': 'Print usage summary',
  452. 'value': False, 'label': '', 'guisection': '', 'suppress_required': False,
  453. 'hidden': False, 'name': 'help'}, {'description': 'Verbose module output',
  454. 'value': False, 'label': '', 'guisection': '', 'suppress_required': False,
  455. 'hidden': False, 'name': 'verbose'}, {'description': 'Quiet module output',
  456. 'value': False, 'label': '', 'guisection': '', 'suppress_required': False,
  457. 'hidden': False, 'name': 'quiet'}], 'description': "Creates a temporary
  458. file and prints it's file name.", 'usage': 'g.tempfile pid=integer [--help]
  459. [--verbose] [--quiet]'}
  460. >>> command_info('v.buffer')
  461. ['vector', 'geometry', 'buffer']
  462. :param str cmd: the command to query
  463. """
  464. task = parse_interface(cmd)
  465. cmdinfo = {}
  466. cmdinfo['description'] = task.get_description()
  467. cmdinfo['keywords'] = task.get_keywords()
  468. cmdinfo['flags'] = flags = task.get_options()['flags']
  469. cmdinfo['params'] = params = task.get_options()['params']
  470. usage = task.get_name()
  471. flags_short = list()
  472. flags_long = list()
  473. for f in flags:
  474. fname = f.get('name', 'unknown')
  475. if len(fname) > 1:
  476. flags_long.append(fname)
  477. else:
  478. flags_short.append(fname)
  479. if len(flags_short) > 1:
  480. usage += ' [-' + ''.join(flags_short) + ']'
  481. for p in params:
  482. ptype = ','.join(p.get('key_desc', []))
  483. if not ptype:
  484. ptype = p.get('type', '')
  485. req = p.get('required', False)
  486. if not req:
  487. usage += ' ['
  488. else:
  489. usage += ' '
  490. usage += p['name'] + '=' + ptype
  491. if p.get('multiple', False):
  492. usage += '[,' + ptype + ',...]'
  493. if not req:
  494. usage += ']'
  495. for key in flags_long:
  496. usage += ' [--' + key + ']'
  497. cmdinfo['usage'] = usage
  498. return cmdinfo
  499. def cmdtuple_to_list(cmd):
  500. """Convert command tuple to list.
  501. :param tuple cmd: GRASS command to be converted
  502. :return: command in list
  503. """
  504. cmdList = []
  505. if not cmd:
  506. return cmdList
  507. cmdList.append(cmd[0])
  508. if 'flags' in cmd[1]:
  509. for flag in cmd[1]['flags']:
  510. cmdList.append('-' + flag)
  511. for flag in ('help', 'verbose', 'quiet', 'overwrite'):
  512. if flag in cmd[1] and cmd[1][flag] is True:
  513. cmdList.append('--' + flag)
  514. for k, v in cmd[1].items():
  515. if k in ('flags', 'help', 'verbose', 'quiet', 'overwrite'):
  516. continue
  517. if ' ' in v:
  518. v = '"%s"' % v
  519. cmdList.append('%s=%s' % (k, v))
  520. return cmdList
  521. def cmdlist_to_tuple(cmd):
  522. """Convert command list to tuple for run_command() and others
  523. :param list cmd: GRASS command to be converted
  524. :return: command as tuple
  525. """
  526. if len(cmd) < 1:
  527. return None
  528. dcmd = {}
  529. for item in cmd[1:]:
  530. if '=' in item: # params
  531. key, value = item.split('=', 1)
  532. dcmd[str(key)] = value.replace('"', '')
  533. elif item[:2] == '--': # long flags
  534. flag = item[2:]
  535. if flag in ('help', 'verbose', 'quiet', 'overwrite'):
  536. dcmd[str(flag)] = True
  537. elif len(item) == 2 and item[0] == '-': # -> flags
  538. if 'flags' not in dcmd:
  539. dcmd['flags'] = ''
  540. dcmd['flags'] += item[1]
  541. else: # unnamed parameter
  542. module = parse_interface(cmd[0])
  543. dcmd[module.define_first()] = item
  544. return (cmd[0], dcmd)
  545. def cmdstring_to_tuple(cmd):
  546. """Convert command string to tuple for run_command() and others
  547. :param str cmd: command to be converted
  548. :return: command as tuple
  549. """
  550. return cmdlist_to_tuple(split(cmd))