g.extension.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: g.extension
  5. # AUTHOR(S): Markus Neteler (original shell script)
  6. # Martin Landa <landa.martin gmail com> (Pythonized & upgraded for GRASS 7)
  7. # Vaclav Petras <wenzeslaus gmail com> (support for general sources)
  8. # PURPOSE: Tool to download and install extensions into local installation
  9. #
  10. # COPYRIGHT: (C) 2009-2014 by Markus Neteler, and the GRASS Development Team
  11. #
  12. # This program is free software under the GNU General
  13. # Public License (>=v2). Read the file COPYING that
  14. # comes with GRASS for details.
  15. #
  16. # TODO: add sudo support where needed (i.e. check first permission to write into
  17. # $GISBASE directory)
  18. #############################################################################
  19. #%module
  20. #% label: Maintains GRASS Addons extensions in local GRASS installation.
  21. #% description: Downloads and installs extensions from GRASS Addons repository or other source into the local GRASS installation or removes installed extensions.
  22. #% keyword: general
  23. #% keyword: installation
  24. #% keyword: extensions
  25. #% keyword: addons
  26. #% keyword: download
  27. #%end
  28. #%option
  29. #% key: extension
  30. #% type: string
  31. #% key_desc: name
  32. #% label: Name of extension to install or remove
  33. #% description: Name of toolbox (set of extensions) when -t flag is given
  34. #% required: yes
  35. #%end
  36. #%option
  37. #% key: operation
  38. #% type: string
  39. #% description: Operation to be performed
  40. #% required: yes
  41. #% options: add,remove
  42. #% answer: add
  43. #%end
  44. #%option
  45. #% key: url
  46. #% type: string
  47. #% key_desc: url
  48. #% label: URL or directory to get the extension from (supported only on Linux and Mac)
  49. #% description: The official repository is used by default. User can specify a ZIP file, directory or a repository on common hosting services. If not identified, Subversion repository is assumed. See manual for all options.
  50. #%end
  51. #%option
  52. #% key: prefix
  53. #% type: string
  54. #% key_desc: path
  55. #% description: Prefix where to install extension (ignored when flag -s is given)
  56. #% answer: $GRASS_ADDON_BASE
  57. #% required: no
  58. #%end
  59. #%option
  60. #% key: proxy
  61. #% type: string
  62. #% key_desc: proxy
  63. #% description: Set the proxy with: "http=<value>,ftp=<value>"
  64. #% required: no
  65. #% multiple: yes
  66. #%end
  67. #%flag
  68. #% key: l
  69. #% description: List available extensions in the official GRASS GIS Addons repository
  70. #% guisection: Print
  71. #% suppress_required: yes
  72. #%end
  73. #%flag
  74. #% key: c
  75. #% description: List available extensions in the official GRASS GIS Addons repository including module description
  76. #% guisection: Print
  77. #% suppress_required: yes
  78. #%end
  79. #%flag
  80. #% key: g
  81. #% description: List available extensions in the official GRASS GIS Addons repository (shell script style)
  82. #% guisection: Print
  83. #% suppress_required: yes
  84. #%end
  85. #%flag
  86. #% key: a
  87. #% description: List locally installed extensions
  88. #% guisection: Print
  89. #% suppress_required: yes
  90. #%end
  91. #%flag
  92. #% key: s
  93. #% description: Install system-wide (may need system administrator rights)
  94. #% guisection: Install
  95. #%end
  96. #%flag
  97. #% key: d
  98. #% description: Download source code and exit
  99. #% guisection: Install
  100. #%end
  101. #%flag
  102. #% key: i
  103. #% description: Do not install new extension, just compile it
  104. #% guisection: Install
  105. #%end
  106. #%flag
  107. #% key: f
  108. #% description: Force removal when uninstalling extension (operation=remove)
  109. #% guisection: Remove
  110. #%end
  111. #%flag
  112. #% key: t
  113. #% description: Operate on toolboxes instead of single modules (experimental)
  114. #% suppress_required: yes
  115. #%end
  116. #%rules
  117. #% required: extension, -l, -c, -g, -a
  118. #% exclusive: extension, -l, -c, -g, -a
  119. #%end
  120. # TODO: solve addon-extension(-module) confusion
  121. from __future__ import print_function
  122. import os
  123. import sys
  124. import re
  125. import atexit
  126. import shutil
  127. import zipfile
  128. import tempfile
  129. try:
  130. from urllib2 import HTTPError, URLError
  131. from urllib import urlopen, urlretrieve
  132. except ImportError:
  133. # there is also HTTPException, perhaps change to list
  134. from urllib.request import HTTPError, URLError, \
  135. urlopen, urlretrieve # pylint: disable=E0611
  136. try:
  137. import xml.etree.ElementTree as etree
  138. except ImportError:
  139. import elementtree.ElementTree as etree # Python <= 2.4
  140. # Get the XML parsing exceptions to catch. The behavior changed with Python 2.7
  141. # and ElementTree 1.3.
  142. from xml.parsers import expat # TODO: works for any Python?
  143. if hasattr(etree, 'ParseError'):
  144. ETREE_EXCEPTIONS = (etree.ParseError, expat.ExpatError)
  145. else:
  146. ETREE_EXCEPTIONS = (expat.ExpatError)
  147. import grass.script as gscript
  148. from grass.script.utils import try_rmdir
  149. from grass.script import core as grass
  150. # temp dir
  151. REMOVE_TMPDIR = True
  152. PROXIES = {}
  153. def etree_fromfile(filename):
  154. """Create XML element tree from a given file name"""
  155. with open(filename, 'r') as file_:
  156. return etree.fromstring(file_.read())
  157. def etree_fromurl(url, proxies=None):
  158. """Create XML element tree from a given URL"""
  159. file_ = urlopen(url, proxies=proxies)
  160. return etree.fromstring(file_.read())
  161. def check_progs():
  162. """Check if the necessary programs are available"""
  163. for prog in ('make', 'gcc'):
  164. if not grass.find_program(prog, '--help'):
  165. grass.fatal(_("'%s' required. Please install '%s' first.")
  166. % (prog, prog))
  167. # expand prefix to class name
  168. def expand_module_class_name(class_letters):
  169. """Convert module class (family) letter or letters to class (family) name
  170. The letter or letters are used in module names, e.g. r.slope.aspect.
  171. The names are used in directories in Addons but also in the source code.
  172. >>> expand_module_class_name('r')
  173. 'raster'
  174. >>> expand_module_class_name('v')
  175. 'vector'
  176. """
  177. name = {
  178. 'd': 'display',
  179. 'db': 'database',
  180. 'g': 'general',
  181. 'i': 'imagery',
  182. 'm': 'misc',
  183. 'ps': 'postscript',
  184. 'p': 'paint',
  185. 'r': 'raster',
  186. 'r3': 'raster3d',
  187. 's': 'sites',
  188. 'v': 'vector',
  189. 'wx': 'gui/wxpython'
  190. }
  191. return name.get(class_letters, class_letters)
  192. def get_module_class_name(module_name):
  193. """Return class (family) name for a module
  194. The names are used in directories in Addons but also in the source code.
  195. >>> get_module_class_name('r.slope.aspect')
  196. 'raster'
  197. >>> get_module_class_name('v.to.rast')
  198. 'vector'
  199. """
  200. classchar = module_name.split('.', 1)[0]
  201. return expand_module_class_name(classchar)
  202. def get_installed_extensions(force=False):
  203. """Get list of installed extensions or toolboxes (if -t is set)"""
  204. if flags['t']:
  205. return get_installed_toolboxes(force)
  206. return get_installed_modules(force)
  207. def list_installed_extensions(toolboxes=False):
  208. """List installed extensions"""
  209. elist = get_installed_extensions()
  210. if elist:
  211. if toolboxes:
  212. grass.message(_("List of installed extensions (toolboxes):"))
  213. else:
  214. grass.message(_("List of installed extensions (modules):"))
  215. sys.stdout.write('\n'.join(elist))
  216. sys.stdout.write('\n')
  217. else:
  218. if toolboxes:
  219. grass.info(_("No extension (toolbox) installed"))
  220. else:
  221. grass.info(_("No extension (module) installed"))
  222. def get_installed_toolboxes(force=False):
  223. """Get list of installed toolboxes
  224. Writes toolboxes file if it does not exist.
  225. Creates a new toolboxes file if it is not possible
  226. to read the current one.
  227. """
  228. xml_file = os.path.join(options['prefix'], 'toolboxes.xml')
  229. if not os.path.exists(xml_file):
  230. write_xml_toolboxes(xml_file)
  231. # read XML file
  232. try:
  233. tree = etree_fromfile(xml_file)
  234. except ETREE_EXCEPTIONS + (OSError, IOError):
  235. os.remove(xml_file)
  236. write_xml_toolboxes(xml_file)
  237. return []
  238. ret = list()
  239. for tnode in tree.findall('toolbox'):
  240. ret.append(tnode.get('code'))
  241. return ret
  242. def get_installed_modules(force=False):
  243. """Get list of installed modules.
  244. Writes modules file if it does not exist and *force* is set to ``True``.
  245. Creates a new modules file if it is not possible
  246. to read the current one.
  247. """
  248. xml_file = os.path.join(options['prefix'], 'modules.xml')
  249. if not os.path.exists(xml_file):
  250. if force:
  251. write_xml_modules(xml_file)
  252. else:
  253. grass.debug(1, "No addons metadata file available")
  254. return []
  255. # read XML file
  256. try:
  257. tree = etree_fromfile(xml_file)
  258. except ETREE_EXCEPTIONS + (OSError, IOError):
  259. os.remove(xml_file)
  260. write_xml_modules(xml_file)
  261. return []
  262. ret = list()
  263. for tnode in tree.findall('task'):
  264. ret.append(tnode.get('name').strip())
  265. return ret
  266. # list extensions (read XML file from grass.osgeo.org/addons)
  267. def list_available_extensions(url):
  268. """List available extensions/modules or toolboxes (if -t is given)
  269. For toolboxes it lists also all modules.
  270. """
  271. gscript.debug("list_available_extensions(url={})".format(url))
  272. if flags['t']:
  273. grass.message(_("List of available extensions (toolboxes):"))
  274. tlist = get_available_toolboxes(url)
  275. for toolbox_code, toolbox_data in tlist.iteritems():
  276. if flags['g']:
  277. print('toolbox_name=' + toolbox_data['name'])
  278. print('toolbox_code=' + toolbox_code)
  279. else:
  280. print('%s (%s)' % (toolbox_data['name'], toolbox_code))
  281. if flags['c'] or flags['g']:
  282. list_available_modules(url, toolbox_data['modules'])
  283. else:
  284. if toolbox_data['modules']:
  285. print(os.linesep.join(map(lambda x: '* ' + x,
  286. toolbox_data['modules'])))
  287. else:
  288. grass.message(_("List of available extensions (modules):"))
  289. list_available_modules(url)
  290. def get_available_toolboxes(url):
  291. """Return toolboxes available in the repository"""
  292. tdict = dict()
  293. url = url + "toolboxes.xml"
  294. try:
  295. tree = etree_fromurl(url, proxies=PROXIES)
  296. for tnode in tree.findall('toolbox'):
  297. mlist = list()
  298. clist = list()
  299. tdict[tnode.get('code')] = {'name': tnode.get('name'),
  300. 'correlate': clist,
  301. 'modules': mlist}
  302. for cnode in tnode.findall('correlate'):
  303. clist.append(cnode.get('name'))
  304. for mnode in tnode.findall('task'):
  305. mlist.append(mnode.get('name'))
  306. except (HTTPError, IOError, OSError):
  307. grass.fatal(_("Unable to fetch addons metadata file"))
  308. return tdict
  309. def get_toolbox_modules(url, name):
  310. """Get modules inside a toolbox in toolbox file at given URL
  311. :param url: URL of the directory (file name will be attached)
  312. :param name: toolbox name
  313. """
  314. tlist = list()
  315. url = url + "toolboxes.xml"
  316. try:
  317. tree = etree_fromurl(url, proxies=PROXIES)
  318. for tnode in tree.findall('toolbox'):
  319. if name == tnode.get('code'):
  320. for mnode in tnode.findall('task'):
  321. tlist.append(mnode.get('name'))
  322. break
  323. except (HTTPError, IOError, OSError):
  324. grass.fatal(_("Unable to fetch addons metadata file"))
  325. return tlist
  326. def get_optional_params(mnode):
  327. """Return description and keywords as a tuple
  328. :param mnode: XML node for a module
  329. """
  330. try:
  331. desc = mnode.find('description').text
  332. except AttributeError:
  333. desc = ''
  334. if desc is None:
  335. desc = ''
  336. try:
  337. keyw = mnode.find('keywords').text
  338. except AttributeError:
  339. keyw = ''
  340. if keyw is None:
  341. keyw = ''
  342. return desc, keyw
  343. def list_available_modules(url, mlist=None):
  344. """List modules available in the repository
  345. Tries to use XML metadata file first. Fallbacks to HTML page with a list.
  346. :param url: URL of the directory (file name will be attached)
  347. :param mlist: list only modules in this list
  348. """
  349. file_url = url + "modules.xml"
  350. grass.debug("url=%s" % file_url, 1)
  351. try:
  352. tree = etree_fromurl(file_url, proxies=PROXIES)
  353. except ETREE_EXCEPTIONS:
  354. grass.warning(_("Unable to parse '%s'. Trying to scan"
  355. " SVN repository (may take some time)...") % file_url)
  356. list_available_extensions_svn(url)
  357. return
  358. except (HTTPError, URLError, IOError, OSError):
  359. list_available_extensions_svn(url)
  360. return
  361. for mnode in tree.findall('task'):
  362. name = mnode.get('name').strip()
  363. if mlist and name not in mlist:
  364. continue
  365. if flags['c'] or flags['g']:
  366. desc, keyw = get_optional_params(mnode)
  367. if flags['g']:
  368. print('name=' + name)
  369. print('description=' + desc)
  370. print('keywords=' + keyw)
  371. elif flags['c']:
  372. if mlist:
  373. print('*', end='')
  374. print(name + ' - ' + desc)
  375. else:
  376. print(name)
  377. # TODO: this is now broken/dead code, SVN is basically not used
  378. # fallback for Trac should parse Trac HTML page
  379. # this might be useful for potential SVN repos or anything
  380. # which would list the extensions/addons as list
  381. # TODO: fail when nothing is accessible
  382. def list_available_extensions_svn(url):
  383. """List available extensions from HTML given by URL
  384. Filename is generated based on the module class/family.
  385. This works well for the structure which is in grass-addons repository.
  386. ``<li><a href=...`` is parsed to find module names.
  387. This works well for HTML page generated by Subversion.
  388. :param url: a directory URL (filename will be attached)
  389. """
  390. gscript.debug("list_available_extensions_svn(url=%s)" % url, 2)
  391. grass.message(_('Fetching list of extensions from'
  392. ' GRASS-Addons SVN repository (be patient)...'))
  393. pattern = re.compile(r'(<li><a href=".+">)(.+)(</a></li>)', re.IGNORECASE)
  394. if flags['c']:
  395. grass.warning(
  396. _("Flag 'c' ignored, addons metadata file not available"))
  397. if flags['g']:
  398. grass.warning(
  399. _("Flag 'g' ignored, addons metadata file not available"))
  400. prefixes = ['d', 'db', 'g', 'i', 'm', 'ps',
  401. 'p', 'r', 'r3', 's', 'v']
  402. for prefix in prefixes:
  403. modclass = expand_module_class_name(prefix)
  404. grass.verbose(_("Checking for '%s' modules...") % modclass)
  405. # construct a full URL of a file
  406. file_url = '%s/%s' % (url, modclass)
  407. grass.debug("url = %s" % file_url, debug=2)
  408. try:
  409. file_ = urlopen(file_url, proxies=PROXIES)
  410. except (HTTPError, IOError, OSError):
  411. grass.debug(_("Unable to fetch '%s'") % file_url, debug=1)
  412. continue
  413. for line in file_.readlines():
  414. # list extensions
  415. sline = pattern.search(line)
  416. if not sline:
  417. continue
  418. name = sline.group(2).rstrip('/')
  419. if name.split('.', 1)[0] == prefix:
  420. print(name)
  421. # get_wxgui_extensions(url)
  422. # TODO: this is a dead code, not clear why not used, but seems not needed
  423. def get_wxgui_extensions(url):
  424. """Return list of extensions/addons in wxGUI directory at given URL
  425. :param url: a directory URL (filename will be attached)
  426. """
  427. mlist = list()
  428. grass.debug('Fetching list of wxGUI extensions from '
  429. 'GRASS-Addons SVN repository (be patient)...')
  430. pattern = re.compile(r'(<li><a href=".+">)(.+)(</a></li>)', re.IGNORECASE)
  431. grass.verbose(_("Checking for '%s' modules...") % 'gui/wxpython')
  432. # construct a full URL of a file
  433. url = '%s/%s' % (url, 'gui/wxpython')
  434. grass.debug("url = %s" % url, debug=2)
  435. file_ = urlopen(url, proxies=PROXIES)
  436. if not file_:
  437. grass.warning(_("Unable to fetch '%s'") % url)
  438. return
  439. for line in file.readlines():
  440. # list extensions
  441. sline = pattern.search(line)
  442. if not sline:
  443. continue
  444. name = sline.group(2).rstrip('/')
  445. if name not in ('..', 'Makefile'):
  446. mlist.append(name)
  447. return mlist
  448. def cleanup():
  449. """Cleanup after the downloads and copilation"""
  450. if REMOVE_TMPDIR:
  451. try_rmdir(TMPDIR)
  452. else:
  453. grass.message("\n%s\n" % _("Path to the source code:"))
  454. sys.stderr.write('%s\n' % os.path.join(TMPDIR, options['extension']))
  455. def write_xml_modules(name, tree=None):
  456. """Write element tree as a modules matadata file
  457. If the *tree* is not given, an empty file is created.
  458. :param name: file name
  459. :param tree: XML element tree
  460. """
  461. file_ = open(name, 'w')
  462. file_.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  463. file_.write('<!DOCTYPE task SYSTEM "grass-addons.dtd">\n')
  464. file_.write('<addons version="%s">\n' % version[0])
  465. libgis_revison = grass.version()['libgis_revision']
  466. if tree is not None:
  467. for tnode in tree.findall('task'):
  468. indent = 4
  469. file_.write('%s<task name="%s">\n' %
  470. (' ' * indent, tnode.get('name')))
  471. indent += 4
  472. file_.write('%s<description>%s</description>\n' %
  473. (' ' * indent, tnode.find('description').text))
  474. file_.write('%s<keywords>%s</keywords>\n' %
  475. (' ' * indent, tnode.find('keywords').text))
  476. bnode = tnode.find('binary')
  477. if bnode is not None:
  478. file_.write('%s<binary>\n' % (' ' * indent))
  479. indent += 4
  480. for fnode in bnode.findall('file'):
  481. file_.write('%s<file>%s</file>\n' %
  482. (' ' * indent, os.path.join(options['prefix'],
  483. fnode.text)))
  484. indent -= 4
  485. file_.write('%s</binary>\n' % (' ' * indent))
  486. file_.write('%s<libgis revision="%s" />\n' %
  487. (' ' * indent, libgis_revison))
  488. indent -= 4
  489. file_.write('%s</task>\n' % (' ' * indent))
  490. file_.write('</addons>\n')
  491. file_.close()
  492. def write_xml_toolboxes(name, tree=None):
  493. """Write element tree as a toolboxes matadata file
  494. If the *tree* is not given, an empty file is created.
  495. :param name: file name
  496. :param tree: XML element tree
  497. """
  498. file_ = open(name, 'w')
  499. file_.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  500. file_.write('<!DOCTYPE toolbox SYSTEM "grass-addons.dtd">\n')
  501. file_.write('<addons version="%s">\n' % version[0])
  502. if tree is not None:
  503. for tnode in tree.findall('toolbox'):
  504. indent = 4
  505. file_.write('%s<toolbox name="%s" code="%s">\n' %
  506. (' ' * indent, tnode.get('name'), tnode.get('code')))
  507. indent += 4
  508. for cnode in tnode.findall('correlate'):
  509. file_.write('%s<correlate code="%s" />\n' %
  510. (' ' * indent, tnode.get('code')))
  511. for mnode in tnode.findall('task'):
  512. file_.write('%s<task name="%s" />\n' %
  513. (' ' * indent, mnode.get('name')))
  514. indent -= 4
  515. file_.write('%s</toolbox>\n' % (' ' * indent))
  516. file_.write('</addons>\n')
  517. file_.close()
  518. def install_extension(source, url, xmlurl):
  519. """Install extension (e.g. one module) or a toolbox (list of modules)"""
  520. gisbase = os.getenv('GISBASE')
  521. if not gisbase:
  522. grass.fatal(_('$GISBASE not defined'))
  523. if options['extension'] in get_installed_extensions(force=True):
  524. grass.warning(_("Extension <%s> already installed. Re-installing...") %
  525. options['extension'])
  526. if flags['t']:
  527. grass.message(_("Installing toolbox <%s>...") % options['extension'])
  528. mlist = get_toolbox_modules(xmlurl, options['extension'])
  529. else:
  530. mlist = [options['extension']]
  531. if not mlist:
  532. grass.warning(_("Nothing to install"))
  533. return
  534. ret = 0
  535. for module in mlist:
  536. if sys.platform == "win32":
  537. ret += install_extension_win(module)
  538. else:
  539. ret += install_extension_std_platforms(module,
  540. source=source, url=url)
  541. if len(mlist) > 1:
  542. print('-' * 60)
  543. if flags['d']:
  544. return
  545. if ret != 0:
  546. grass.warning(_('Installation failed, sorry.'
  547. ' Please check above error messages.'))
  548. else:
  549. # for now it is reasonable to assume that only official source
  550. # will provide the metadata file
  551. if source == 'official':
  552. grass.message(_("Updating addons metadata file..."))
  553. blist = install_extension_xml(xmlurl, mlist)
  554. # the blist was used here, but it seems that it is the same as mlist
  555. for module in mlist:
  556. update_manual_page(module)
  557. grass.message(_("Installation of <%s> successfully finished") %
  558. options['extension'])
  559. if not os.getenv('GRASS_ADDON_BASE'):
  560. grass.warning(_('This add-on module will not function until'
  561. ' you set the GRASS_ADDON_BASE environment'
  562. ' variable (see "g.manual variables")'))
  563. def get_toolboxes_metadata(url):
  564. """Return metadata for all toolboxes from given URL
  565. :param url: URL of a modules matadata file
  566. :param mlist: list of modules to get metadata for
  567. :returns: tuple where first item is dictionary with module names as keys
  568. and dictionary with dest, keyw, files keys as value, the second item
  569. is list of 'binary' files (installation files)
  570. """
  571. data = dict()
  572. try:
  573. tree = etree_fromurl(url, proxies=PROXIES)
  574. for tnode in tree.findall('toolbox'):
  575. clist = list()
  576. for cnode in tnode.findall('correlate'):
  577. clist.append(cnode.get('code'))
  578. mlist = list()
  579. for mnode in tnode.findall('task'):
  580. mlist.append(mnode.get('name'))
  581. code = tnode.get('code')
  582. data[code] = {
  583. 'name': tnode.get('name'),
  584. 'correlate': clist,
  585. 'modules': mlist,
  586. }
  587. except (HTTPError, IOError, OSError):
  588. grass.error(_("Unable to read addons metadata file "
  589. "from the remote server"))
  590. return data
  591. def install_toolbox_xml(url, name):
  592. """Update local toolboxes metadata file"""
  593. # read metadata from remote server (toolboxes)
  594. url = url + "toolboxes.xml"
  595. data = get_toolboxes_metadata(url)
  596. if not data:
  597. grass.warning(_("No addons metadata available"))
  598. return
  599. if name not in data:
  600. grass.warning(_("No addons metadata available for <%s>") % name)
  601. return
  602. xml_file = os.path.join(options['prefix'], 'toolboxes.xml')
  603. # create an empty file if not exists
  604. if not os.path.exists(xml_file):
  605. write_xml_modules(xml_file)
  606. # read XML file
  607. with open(xml_file, 'r') as xml:
  608. tree = etree.fromstring(xml.read())
  609. # update tree
  610. tnode = None
  611. for node in tree.findall('toolbox'):
  612. if node.get('code') == name:
  613. tnode = node
  614. break
  615. tdata = data[name]
  616. if tnode is not None:
  617. # update existing node
  618. for cnode in tnode.findall('correlate'):
  619. tnode.remove(cnode)
  620. for mnode in tnode.findall('task'):
  621. tnode.remove(mnode)
  622. else:
  623. # create new node for task
  624. tnode = etree.Element(
  625. 'toolbox', attrib={'name': tdata['name'], 'code': name})
  626. tree.append(tnode)
  627. for cname in tdata['correlate']:
  628. cnode = etree.Element('correlate', attrib={'code': cname})
  629. tnode.append(cnode)
  630. for tname in tdata['modules']:
  631. mnode = etree.Element('task', attrib={'name': tname})
  632. tnode.append(mnode)
  633. write_xml_toolboxes(xml_file, tree)
  634. def get_addons_metadata(url, mlist):
  635. """Return metadata for list of modules from given URL
  636. :param url: URL of a modules matadata file
  637. :param mlist: list of modules to get metadata for
  638. :returns: tuple where first item is dictionary with module names as keys
  639. and dictionary with dest, keyw, files keys as value, the second item
  640. is list of 'binary' files (installation files)
  641. """
  642. data = {}
  643. bin_list = []
  644. try:
  645. tree = etree_fromurl(url, proxies=PROXIES)
  646. except (HTTPError, URLError, IOError, OSError) as error:
  647. grass.error(_("Unable to read addons metadata file"
  648. " from the remote server: {}").format(error))
  649. return data, bin_list
  650. except ETREE_EXCEPTIONS as error:
  651. grass.warning(_("Unable to parse '%s': {}").format(error) % url)
  652. return data, bin_list
  653. for mnode in tree.findall('task'):
  654. name = mnode.get('name')
  655. if name not in mlist:
  656. continue
  657. file_list = list()
  658. bnode = mnode.find('binary')
  659. windows = sys.platform == 'win32'
  660. if bnode is not None:
  661. for fnode in bnode.findall('file'):
  662. path = fnode.text.split('/')
  663. if path[0] == 'bin':
  664. bin_list.append(path[-1])
  665. if windows:
  666. path[-1] += '.exe'
  667. elif path[0] == 'scripts':
  668. bin_list.append(path[-1])
  669. if windows:
  670. path[-1] += '.py'
  671. file_list.append(os.path.sep.join(path))
  672. desc, keyw = get_optional_params(mnode)
  673. data[name] = {
  674. 'desc': desc,
  675. 'keyw': keyw,
  676. 'files': file_list,
  677. }
  678. return data, bin_list
  679. def install_extension_xml(url, mlist):
  680. """Update XML files with metadata about installed modules and toolbox
  681. Uses the remote/repository XML files for modules to obtain the metadata.
  682. :returns: list of executables (useable for ``update_manual_page()``)
  683. """
  684. if len(mlist) > 1:
  685. # read metadata from remote server (toolboxes)
  686. install_toolbox_xml(url, options['extension'])
  687. # read metadata from remote server (modules)
  688. url = url + "modules.xml"
  689. data, bin_list = get_addons_metadata(url, mlist)
  690. if not data:
  691. grass.warning(_("No addons metadata available."
  692. " Addons metadata file not updated."))
  693. return []
  694. xml_file = os.path.join(options['prefix'], 'modules.xml')
  695. # create an empty file if not exists
  696. if not os.path.exists(xml_file):
  697. write_xml_modules(xml_file)
  698. # read XML file
  699. tree = etree_fromfile(xml_file)
  700. # update tree
  701. for name in mlist:
  702. tnode = None
  703. for node in tree.findall('task'):
  704. if node.get('name') == name:
  705. tnode = node
  706. break
  707. if name not in data:
  708. grass.warning(_("No addons metadata found for <%s>") % name)
  709. continue
  710. ndata = data[name]
  711. if tnode is not None:
  712. # update existing node
  713. dnode = tnode.find('description')
  714. if dnode is not None:
  715. dnode.text = ndata['desc']
  716. knode = tnode.find('keywords')
  717. if knode is not None:
  718. knode.text = ndata['keyw']
  719. bnode = tnode.find('binary')
  720. if bnode is not None:
  721. tnode.remove(bnode)
  722. bnode = etree.Element('binary')
  723. for file_name in ndata['files']:
  724. fnode = etree.Element('file')
  725. fnode.text = file_name
  726. bnode.append(fnode)
  727. tnode.append(bnode)
  728. else:
  729. # create new node for task
  730. tnode = etree.Element('task', attrib={'name': name})
  731. dnode = etree.Element('description')
  732. dnode.text = ndata['desc']
  733. tnode.append(dnode)
  734. knode = etree.Element('keywords')
  735. knode.text = ndata['keyw']
  736. tnode.append(knode)
  737. bnode = etree.Element('binary')
  738. for file_name in ndata['files']:
  739. fnode = etree.Element('file')
  740. fnode.text = file_name
  741. bnode.append(fnode)
  742. tnode.append(bnode)
  743. tree.append(tnode)
  744. write_xml_modules(xml_file, tree)
  745. return bin_list
  746. def install_extension_win(name):
  747. """Install extension on MS Windows"""
  748. # do not use hardcoded url -
  749. # http://wingrass.fsv.cvut.cz/grassXX/addonsX.X.X
  750. grass.message(_("Downloading precompiled GRASS Addons <%s>...") %
  751. options['extension'])
  752. url = "http://wingrass.fsv.cvut.cz/" \
  753. "grass%(major)s%(minor)s/addons/" \
  754. "grass-%(major)s.%(minor)s.%(patch)s/" % \
  755. {'major': version[0], 'minor': version[1], 'patch': version[2]}
  756. grass.debug("url=%s" % url, 1)
  757. try:
  758. zfile = url + name + '.zip'
  759. url_file = urlopen(zfile, proxies=PROXIES)
  760. # create addons dir if not exists
  761. if not os.path.exists(options['prefix']):
  762. try:
  763. os.mkdir(options['prefix'])
  764. except OSError as error:
  765. grass.fatal(_("Unable to create <{}>. {}")
  766. .format(options['prefix'], error))
  767. # download data
  768. tmp_file = tempfile.TemporaryFile()
  769. tmp_file.write(url_file.read())
  770. try:
  771. zfobj = zipfile.ZipFile(tmp_file)
  772. except zipfile.BadZipfile as error:
  773. grass.fatal('%s: %s' % (error, zfile))
  774. for name in zfobj.namelist():
  775. if name.endswith('/'):
  776. directory = os.path.join(options['prefix'], name)
  777. if not os.path.exists(directory):
  778. os.mkdir(directory)
  779. else:
  780. outfile = open(os.path.join(options['prefix'], name), 'wb')
  781. outfile.write(zfobj.read(name))
  782. outfile.close()
  783. tmp_file.close()
  784. except HTTPError:
  785. grass.fatal(_("GRASS Addons <%s> not found") % name)
  786. return 0
  787. def download_source_code_svn(url, name, outdev, directory=None):
  788. """Download source code from a Subversion reporsitory
  789. .. note:
  790. Stdout is passed to to *outdev* while stderr is will be just printed.
  791. :param url: URL of the repository
  792. (module class/family and name are attached)
  793. :param name: module name
  794. :param outdev: output devide for the standard output of the svn command
  795. :param directory: directory where the source code will be downloaded
  796. (default is the current directory with name attached)
  797. :returns: full path to the directory with the source code
  798. (useful when you not specify directory, if *directory* is specified
  799. the return value is equal to it)
  800. """
  801. if not directory:
  802. directory = os.path.join(os.getcwd, name)
  803. classchar = name.split('.', 1)[0]
  804. moduleclass = expand_module_class_name(classchar)
  805. url = url + '/' + moduleclass + '/' + name
  806. if grass.call(['svn', 'checkout',
  807. url, directory], stdout=outdev) != 0:
  808. grass.fatal(_("GRASS Addons <%s> not found") % name)
  809. return directory
  810. def move_extracted_files(extract_dir, target_dir, files):
  811. """Fix state of extracted file by moving them to different diretcory
  812. When extracting, it is not clear what will be the root directory
  813. or if there will be one at all. So this function moves the files to
  814. a different directory in the way that if there was one direcory extracted,
  815. the contained files are moved.
  816. """
  817. gscript.debug("move_extracted_files({})".format(locals()))
  818. if len(files) == 1:
  819. shutil.copytree(os.path.join(extract_dir, files[0]), target_dir)
  820. else:
  821. os.mkdir(target_dir)
  822. for file_name in files:
  823. actual_file = os.path.join(extract_dir, file_name)
  824. if os.path.isdir(actual_file):
  825. shutil.copytree(actual_file,
  826. os.path.join(target_dir, file_name))
  827. else:
  828. shutil.copy(actual_file, os.path.join(target_dir, file_name))
  829. # Original copyright and license of the original version of the CRLF function
  830. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
  831. # Python Software Foundation; All Rights Reserved
  832. # Python Software Foundation License Version 2
  833. # http://svn.python.org/projects/python/trunk/Tools/scripts/crlf.py
  834. def fix_newlines(directory):
  835. """Replace CRLF with LF in all files in the directory
  836. Binary files are ignored. Recurses into subdirectories.
  837. """
  838. for root, unused, files in os.walk(directory):
  839. for name in files:
  840. filename = os.path.join(root, name)
  841. data = open(filename, 'rb').read()
  842. if '\0' in data:
  843. continue # ignore binary files
  844. # we don't expect there would be CRLF file by purpose
  845. # if we want to allow CRLF files we would have to whitelite .py etc
  846. newdata = data.replace('\r\n', '\n')
  847. if newdata != data:
  848. newfile = open(filename, 'wb')
  849. newfile.write(newdata)
  850. newfile.close()
  851. def extract_zip(name, directory, tmpdir):
  852. """Extract a ZIP file into a directory"""
  853. gscript.debug("extract_zip(name={name}, directory={directory},"
  854. " tmpdir={tmpdir})".format(name=name, directory=directory,
  855. tmpdir=tmpdir), 3)
  856. try:
  857. zip_file = zipfile.ZipFile(name, mode='r')
  858. file_list = zip_file.namelist()
  859. # we suppose we can write to parent of the given dir
  860. # (supposing a tmp dir)
  861. extract_dir = os.path.join(tmpdir, 'extract_dir')
  862. os.mkdir(extract_dir)
  863. for subfile in file_list:
  864. # this should be safe in Python 2.7.4
  865. zip_file.extract(subfile, extract_dir)
  866. files = os.listdir(extract_dir)
  867. move_extracted_files(extract_dir=extract_dir,
  868. target_dir=directory, files=files)
  869. except zipfile.BadZipfile as error:
  870. gscript.fatal(_("ZIP file is unreadable: {}").format(error))
  871. # TODO: solve the other related formats
  872. def extract_tar(name, directory, tmpdir):
  873. """Extract a TAR or a similar file into a directory"""
  874. gscript.debug("extract_tar(name={name}, directory={directory},"
  875. " tmpdir={tmpdir})".format(name=name, directory=directory,
  876. tmpdir=tmpdir), 3)
  877. try:
  878. import tarfile # we don't need it anywhere else
  879. tar = tarfile.open(name)
  880. extract_dir = os.path.join(tmpdir, 'extract_dir')
  881. os.mkdir(extract_dir)
  882. tar.extractall(path=extract_dir)
  883. files = os.listdir(extract_dir)
  884. move_extracted_files(extract_dir=extract_dir,
  885. target_dir=directory, files=files)
  886. except tarfile.TarError as error:
  887. gscript.fatal(_("Archive file is unreadable: {}").format(error))
  888. extract_tar.supported_formats = ['tar.gz', 'gz', 'bz2', 'tar', 'gzip', 'targz']
  889. def download_source_code(source, url, name, outdev,
  890. directory=None, tmpdir=None):
  891. """Get source code to a local directory for compilation"""
  892. gscript.verbose("Downloading source code for <{name}> from <{url}>"
  893. " which is identified as '{source}' type of source..."
  894. .format(source=source, url=url, name=name))
  895. if source == 'svn':
  896. download_source_code_svn(url, name, outdev, directory)
  897. elif source in ['remote_zip', 'official']:
  898. # we expect that the module.zip file is not by chance in the archive
  899. zip_name = os.path.join(tmpdir, 'extension.zip')
  900. urlretrieve(url, zip_name)
  901. extract_zip(name=zip_name, directory=directory, tmpdir=tmpdir)
  902. fix_newlines(directory)
  903. elif source.startswith('remote_') and \
  904. source.split('_')[1] in extract_tar.supported_formats:
  905. # we expect that the module.tar.gz file is not by chance in the archive
  906. archive_name = os.path.join(tmpdir,
  907. 'extension.' + source.split('_')[1])
  908. urlretrieve(url, archive_name)
  909. extract_tar(name=archive_name, directory=directory, tmpdir=tmpdir)
  910. fix_newlines(directory)
  911. elif source == 'zip':
  912. extract_zip(name=url, directory=directory, tmpdir=tmpdir)
  913. fix_newlines(directory)
  914. elif source in extract_tar.supported_formats:
  915. extract_tar(name=url, directory=directory, tmpdir=tmpdir)
  916. fix_newlines(directory)
  917. elif source == 'dir':
  918. shutil.copytree(url, directory)
  919. fix_newlines(directory)
  920. else:
  921. # probably programmer error
  922. grass.fatal(_("Unknown extension (addon) source type '{}'."
  923. " Please report this to the grass-user mailing list.")
  924. .format(source))
  925. assert os.path.isdir(directory)
  926. def install_extension_std_platforms(name, source, url):
  927. """Install extension on standard plaforms"""
  928. gisbase = os.getenv('GISBASE')
  929. if source == 'official':
  930. gscript.message(_("Fetching <%s> from "
  931. "GRASS GIS Addons repository (be patient)...") % name)
  932. else:
  933. gscript.message(_("Fetching <{name}> from "
  934. "<{url}> (be patient)...").format(name=name, url=url))
  935. # to hide non-error messages from subprocesses
  936. if grass.verbosity() <= 2:
  937. outdev = open(os.devnull, 'w')
  938. else:
  939. outdev = sys.stdout
  940. os.chdir(TMPDIR) # this is just to not leave something behind
  941. srcdir = os.path.join(TMPDIR, name)
  942. download_source_code(source=source, url=url, name=name,
  943. outdev=outdev, directory=srcdir, tmpdir=TMPDIR)
  944. os.chdir(srcdir)
  945. dirs = {
  946. 'bin': os.path.join(TMPDIR, name, 'bin'),
  947. 'docs': os.path.join(TMPDIR, name, 'docs'),
  948. 'html': os.path.join(TMPDIR, name, 'docs', 'html'),
  949. 'rest': os.path.join(TMPDIR, name, 'docs', 'rest'),
  950. 'man': os.path.join(TMPDIR, name, 'docs', 'man'),
  951. 'script': os.path.join(TMPDIR, name, 'scripts'),
  952. # TODO: handle locales also for addons
  953. # 'string' : os.path.join(TMPDIR, name, 'locale'),
  954. 'string': os.path.join(TMPDIR, name),
  955. 'etc': os.path.join(TMPDIR, name, 'etc'),
  956. }
  957. make_cmd = [
  958. 'make',
  959. 'MODULE_TOPDIR=%s' % gisbase.replace(' ', r'\ '),
  960. 'RUN_GISRC=%s' % os.environ['GISRC'],
  961. 'BIN=%s' % dirs['bin'],
  962. 'HTMLDIR=%s' % dirs['html'],
  963. 'RESTDIR=%s' % dirs['rest'],
  964. 'MANBASEDIR=%s' % dirs['man'],
  965. 'SCRIPTDIR=%s' % dirs['script'],
  966. 'STRINGDIR=%s' % dirs['string'],
  967. 'ETC=%s' % os.path.join(dirs['etc'])
  968. ]
  969. install_cmd = [
  970. 'make',
  971. 'MODULE_TOPDIR=%s' % gisbase,
  972. 'ARCH_DISTDIR=%s' % os.path.join(TMPDIR, name),
  973. 'INST_DIR=%s' % options['prefix'],
  974. 'install'
  975. ]
  976. if flags['d']:
  977. grass.message("\n%s\n" % _("To compile run:"))
  978. sys.stderr.write(' '.join(make_cmd) + '\n')
  979. grass.message("\n%s\n" % _("To install run:"))
  980. sys.stderr.write(' '.join(install_cmd) + '\n')
  981. return 0
  982. os.chdir(os.path.join(TMPDIR, name))
  983. grass.message(_("Compiling..."))
  984. if not os.path.exists(os.path.join(gisbase, 'include',
  985. 'Make', 'Module.make')):
  986. grass.fatal(_("Please install GRASS development package"))
  987. if 0 != grass.call(make_cmd,
  988. stdout=outdev):
  989. grass.fatal(_('Compilation failed, sorry.'
  990. ' Please check above error messages.'))
  991. if flags['i']:
  992. return 0
  993. grass.message(_("Installing..."))
  994. return grass.call(install_cmd,
  995. stdout=outdev)
  996. def remove_extension(force=False):
  997. """Remove existing extension (module or toolbox if -t is given)"""
  998. if flags['t']:
  999. mlist = get_toolbox_modules(options['prefix'], options['extension'])
  1000. else:
  1001. mlist = [options['extension']]
  1002. if force:
  1003. grass.verbose(_("List of removed files:"))
  1004. else:
  1005. grass.info(_("Files to be removed:"))
  1006. remove_modules(mlist, force)
  1007. if force:
  1008. grass.message(_("Updating addons metadata file..."))
  1009. remove_extension_xml(mlist)
  1010. grass.message(_("Extension <%s> successfully uninstalled.") %
  1011. options['extension'])
  1012. else:
  1013. grass.warning(_("Extension <%s> not removed. "
  1014. "Re-run '%s' with '-f' flag to force removal")
  1015. % (options['extension'], 'g.extension'))
  1016. # remove existing extension(s) (reading XML file)
  1017. def remove_modules(mlist, force=False):
  1018. """Remove extensions/modules specified in a list
  1019. Collects the file names from the file with metadata and fallbacks
  1020. to standard layout of files on prefix path on error.
  1021. """
  1022. # try to read XML metadata file first
  1023. xml_file = os.path.join(options['prefix'], 'modules.xml')
  1024. installed = get_installed_modules()
  1025. if os.path.exists(xml_file):
  1026. tree = etree_fromfile(xml_file)
  1027. else:
  1028. tree = None
  1029. for name in mlist:
  1030. if name not in installed:
  1031. # try even if module does not seem to be available,
  1032. # as the user may be trying to get rid of left over cruft
  1033. grass.warning(_("Extension <%s> not found") % name)
  1034. if tree is not None:
  1035. flist = []
  1036. for task in tree.findall('task'):
  1037. if name == task.get('name') and \
  1038. task.find('binary') is not None:
  1039. for file_node in task.find('binary').findall('file'):
  1040. flist.append(file_node.text)
  1041. break
  1042. if flist:
  1043. removed = False
  1044. err = list()
  1045. for fpath in flist:
  1046. try:
  1047. if force:
  1048. grass.verbose(fpath)
  1049. removed = True
  1050. os.remove(fpath)
  1051. else:
  1052. print(fpath)
  1053. except OSError:
  1054. err.append((_("Unable to remove file '%s'") % fpath))
  1055. if force and not removed:
  1056. grass.fatal(_("Extension <%s> not found") % name)
  1057. if err:
  1058. for error_line in err:
  1059. grass.error(error_line)
  1060. else:
  1061. remove_extension_std(name, force)
  1062. else:
  1063. remove_extension_std(name, force)
  1064. def remove_extension_std(name, force=False):
  1065. """Remove extension/module expecting the standard layout"""
  1066. for fpath in [os.path.join(options['prefix'], 'bin', name),
  1067. os.path.join(options['prefix'], 'scripts', name),
  1068. os.path.join(
  1069. options['prefix'], 'docs', 'html', name + '.html'),
  1070. os.path.join(
  1071. options['prefix'], 'docs', 'rest', name + '.txt'),
  1072. os.path.join(options['prefix'], 'docs', 'man', 'man1',
  1073. name + '.1')]:
  1074. if os.path.isfile(fpath):
  1075. if force:
  1076. grass.verbose(fpath)
  1077. os.remove(fpath)
  1078. else:
  1079. print(fpath)
  1080. def remove_from_toolbox_xml(name):
  1081. """Update local meta-file when removing existing toolbox"""
  1082. xml_file = os.path.join(options['prefix'], 'toolboxes.xml')
  1083. if not os.path.exists(xml_file):
  1084. return
  1085. # read XML file
  1086. tree = etree_fromfile(xml_file)
  1087. for node in tree.findall('toolbox'):
  1088. if node.get('code') != name:
  1089. continue
  1090. tree.remove(node)
  1091. write_xml_toolboxes(xml_file, tree)
  1092. def remove_extension_xml(modules):
  1093. """Update local meta-file when removing existing extension"""
  1094. if len(modules) > 1:
  1095. # update also toolboxes metadata
  1096. remove_from_toolbox_xml(options['extension'])
  1097. xml_file = os.path.join(options['prefix'], 'modules.xml')
  1098. if not os.path.exists(xml_file):
  1099. return
  1100. # read XML file
  1101. tree = etree_fromfile(xml_file)
  1102. for name in modules:
  1103. for node in tree.findall('task'):
  1104. if node.get('name') != name:
  1105. continue
  1106. tree.remove(node)
  1107. write_xml_modules(xml_file, tree)
  1108. # check links in CSS
  1109. def check_style_files(fil):
  1110. """Ensures that a specified HTML documentation support file exists
  1111. If the file, e.g. a CSS file does not exist, the file is copied from
  1112. the distribution.
  1113. """
  1114. dist_file = os.path.join(os.getenv('GISBASE'), 'docs', 'html', fil)
  1115. addons_file = os.path.join(options['prefix'], 'docs', 'html', fil)
  1116. if os.path.isfile(addons_file):
  1117. return
  1118. try:
  1119. shutil.copyfile(dist_file, addons_file)
  1120. except OSError as error:
  1121. grass.fatal(_("Unable to create '%s': %s") % (addons_file, error))
  1122. def create_dir(path):
  1123. """Creates the specified directory (with all dirs in between)
  1124. NOOP for existing directory.
  1125. """
  1126. if os.path.isdir(path):
  1127. return
  1128. try:
  1129. os.makedirs(path)
  1130. except OSError as error:
  1131. grass.fatal(_("Unable to create '%s': %s") % (path, error))
  1132. grass.debug("'%s' created" % path)
  1133. def check_dirs():
  1134. """Ensure that the necessary directories in prefix path exist"""
  1135. create_dir(os.path.join(options['prefix'], 'bin'))
  1136. create_dir(os.path.join(options['prefix'], 'docs', 'html'))
  1137. create_dir(os.path.join(options['prefix'], 'docs', 'rest'))
  1138. check_style_files('grass_logo.png')
  1139. check_style_files('grassdocs.css')
  1140. create_dir(os.path.join(options['prefix'], 'etc'))
  1141. create_dir(os.path.join(options['prefix'], 'docs', 'man', 'man1'))
  1142. create_dir(os.path.join(options['prefix'], 'scripts'))
  1143. # fix file URI in manual page
  1144. def update_manual_page(module):
  1145. """Fix manual page for addons which are at different directory then rest"""
  1146. if module.split('.', 1)[0] == 'wx':
  1147. return # skip for GUI modules
  1148. grass.verbose(_("Manual page for <%s> updated") % module)
  1149. # read original html file
  1150. htmlfile = os.path.join(
  1151. options['prefix'], 'docs', 'html', module + '.html')
  1152. try:
  1153. oldfile = open(htmlfile)
  1154. shtml = oldfile.read()
  1155. except IOError as error:
  1156. gscript.fatal(_("Unable to read manual page: %s") % error)
  1157. else:
  1158. oldfile.close()
  1159. pos = []
  1160. # fix logo URL
  1161. pattern = r'''<a href="([^"]+)"><img src="grass_logo.png"'''
  1162. for match in re.finditer(pattern, shtml):
  1163. pos.append(match.start(1))
  1164. # find URIs
  1165. pattern = r'''<a href="([^"]+)">([^>]+)</a>'''
  1166. addons = get_installed_extensions(force=True)
  1167. for match in re.finditer(pattern, shtml):
  1168. if match.group(1)[:4] == 'http':
  1169. continue
  1170. if match.group(1).replace('.html', '') in addons:
  1171. continue
  1172. pos.append(match.start(1))
  1173. if not pos:
  1174. return # no match
  1175. # replace file URIs
  1176. prefix = 'file://' + '/'.join([os.getenv('GISBASE'), 'docs', 'html'])
  1177. ohtml = shtml[:pos[0]]
  1178. for i in range(1, len(pos)):
  1179. ohtml += prefix + '/' + shtml[pos[i - 1]:pos[i]]
  1180. ohtml += prefix + '/' + shtml[pos[-1]:]
  1181. # write updated html file
  1182. try:
  1183. newfile = open(htmlfile, 'w')
  1184. newfile.write(ohtml)
  1185. except IOError as error:
  1186. gscript.fatal(_("Unable for write manual page: %s") % error)
  1187. else:
  1188. newfile.close()
  1189. def resolve_install_prefix(path, to_system):
  1190. """Determine and check the path for installation"""
  1191. if to_system:
  1192. path = os.environ['GISBASE']
  1193. if path == '$GRASS_ADDON_BASE':
  1194. if not os.getenv('GRASS_ADDON_BASE'):
  1195. grass.warning(_("GRASS_ADDON_BASE is not defined, "
  1196. "installing to ~/.grass%s/addons") % version[0])
  1197. path = os.path.join(
  1198. os.environ['HOME'], '.grass%s' % version[0], 'addons')
  1199. else:
  1200. path = os.environ['GRASS_ADDON_BASE']
  1201. if os.path.exists(path) and \
  1202. not os.access(path, os.W_OK):
  1203. grass.fatal(_("You don't have permission to install extension to <{}>."
  1204. " Try to run {} with administrator rights"
  1205. " (su or sudo).")
  1206. .format(path, 'g.extension'))
  1207. # ensure dir sep at the end for cases where path is used as URL and pasted
  1208. # together with file names
  1209. if not path.endswith(os.path.sep):
  1210. path = path + os.path.sep
  1211. return os.path.abspath(path) # make likes absolute paths
  1212. def resolve_xmlurl_prefix(url, source=None):
  1213. """Determine and check the URL where the XML metadata files are stored
  1214. It ensures that there is a single slash at the end of URL, so we can attach
  1215. file name easily:
  1216. >>> resolve_xmlurl_prefix('http://grass.osgeo.org/addons')
  1217. 'http://grass.osgeo.org/addons/'
  1218. >>> resolve_xmlurl_prefix('http://grass.osgeo.org/addons/')
  1219. 'http://grass.osgeo.org/addons/'
  1220. """
  1221. gscript.debug("resolve_xmlurl_prefix(url={}, source={})".format(url, source))
  1222. if source == 'official':
  1223. # use pregenerated modules XML file
  1224. url = 'http://grass.osgeo.org/addons/grass%s/' % version[0]
  1225. # else try to get modules XMl from SVN repository (provided URL)
  1226. # the exact action depends on subsequent code (somewhere)
  1227. if not url.endswith('/'):
  1228. url = url + '/'
  1229. return url
  1230. KNOWN_HOST_SERVICES_INFO = {
  1231. 'OSGeo Trac': {
  1232. 'domain': 'trac.osgeo.org',
  1233. 'ignored_suffixes': ['format=zip'],
  1234. 'possible_starts': ['', 'https://', 'http://'],
  1235. 'url_start': 'https://',
  1236. 'url_end': '?format=zip',
  1237. },
  1238. 'GitHub': {
  1239. 'domain': 'github.com',
  1240. 'ignored_suffixes': ['.zip', '.tar.gz'],
  1241. 'possible_starts': ['', 'https://', 'http://'],
  1242. 'url_start': 'https://',
  1243. 'url_end': '/archive/master.zip',
  1244. },
  1245. 'GitLab': {
  1246. 'domain': 'gitlab.com',
  1247. 'ignored_suffixes': ['.zip', '.tar.gz', '.tar.bz2', '.tar'],
  1248. 'possible_starts': ['', 'https://', 'http://'],
  1249. 'url_start': 'https://',
  1250. 'url_end': '/repository/archive.zip',
  1251. },
  1252. 'Bitbucket': {
  1253. 'domain': 'bitbucket.org',
  1254. 'ignored_suffixes': ['.zip', '.tar.gz', '.gz', '.bz2'],
  1255. 'possible_starts': ['', 'https://', 'http://'],
  1256. 'url_start': 'https://',
  1257. 'url_end': '/get/default.zip',
  1258. },
  1259. }
  1260. # TODO: support ZIP URLs which don't end with zip
  1261. # https://gitlab.com/user/reponame/repository/archive.zip?ref=b%C3%A9po
  1262. def resolve_known_host_service(url):
  1263. """Determine source type and full URL for known hosting service
  1264. If the service is not determined from the provided URL, tuple with
  1265. is two ``None`` values is returned.
  1266. """
  1267. match = None
  1268. actual_start = None
  1269. for key, value in KNOWN_HOST_SERVICES_INFO.iteritems():
  1270. for start in value['possible_starts']:
  1271. if url.startswith(start + value['domain']):
  1272. match = value
  1273. actual_start = start
  1274. gscript.verbose(_("Indentified {} as known hosting service")
  1275. .format(key))
  1276. for suffix in value['ignored_suffixes']:
  1277. if url.endswith(suffix):
  1278. gscript.verbose(
  1279. _("Not using {service} as known hosting service"
  1280. " because the URL ends with '{suffix}'")
  1281. .format(service=key, suffix=suffix))
  1282. return None, None
  1283. if match:
  1284. if not actual_start:
  1285. actual_start = match['url_start']
  1286. else:
  1287. actual_start = ''
  1288. url = '{prefix}{base}{suffix}'.format(prefix=actual_start,
  1289. base=url.rstrip('/'),
  1290. suffix=match['url_end'])
  1291. gscript.verbose(_("Will use the following URL for download: {}")
  1292. .format(url))
  1293. return 'remote_zip', url
  1294. else:
  1295. return None, None
  1296. # TODO: add also option to enforce the source type
  1297. def resolve_source_code(url=None, name=None):
  1298. """Return type and URL or path of the source code
  1299. Local paths are not presented as URLs to be usable in standard functions.
  1300. Path is identified as local path if the directory of file exists which
  1301. has the unfortunate consequence that the not existing files are evaluated
  1302. as remote URLs. When path is not evaluated, Subversion is assumed for
  1303. backwards compatibility. When GitHub repository is specified, ZIP file
  1304. link is returned. The ZIP is for master branch, not the default one because
  1305. GitHub does not provide the deafult branch in the URL (July 2015).
  1306. :returns: tuple with type of source and full URL or path
  1307. Official repository:
  1308. >>> resolve_source_code(name='g.example') # doctest: +SKIP
  1309. ('official', 'https://trac.osgeo.org/.../general/g.example')
  1310. Subversion:
  1311. >>> resolve_source_code('http://svn.osgeo.org/grass/grass-addons/grass7')
  1312. ('svn', 'http://svn.osgeo.org/grass/grass-addons/grass7')
  1313. ZIP files online:
  1314. >>> resolve_source_code('https://trac.osgeo.org/.../r.modis?format=zip')
  1315. ('remote_zip', 'https://trac.osgeo.org/.../r.modis?format=zip')
  1316. Local directories and ZIP files:
  1317. >>> resolve_source_code(os.path.expanduser("~")) # doctest: +ELLIPSIS
  1318. ('dir', '...')
  1319. >>> resolve_source_code('/local/directory/downloaded.zip') # doctest: +SKIP
  1320. ('zip', '/local/directory/downloaded.zip')
  1321. OSGeo Trac:
  1322. >>> resolve_source_code('trac.osgeo.org/.../r.agent.aco')
  1323. ('remote_zip', 'https://trac.osgeo.org/.../r.agent.aco?format=zip')
  1324. >>> resolve_source_code('https://trac.osgeo.org/.../r.agent.aco')
  1325. ('remote_zip', 'https://trac.osgeo.org/.../r.agent.aco?format=zip')
  1326. GitHub:
  1327. >>> resolve_source_code('github.com/user/g.example')
  1328. ('remote_zip', 'https://github.com/user/g.example/archive/master.zip')
  1329. >>> resolve_source_code('github.com/user/g.example/')
  1330. ('remote_zip', 'https://github.com/user/g.example/archive/master.zip')
  1331. >>> resolve_source_code('https://github.com/user/g.example')
  1332. ('remote_zip', 'https://github.com/user/g.example/archive/master.zip')
  1333. >>> resolve_source_code('https://github.com/user/g.example/')
  1334. ('remote_zip', 'https://github.com/user/g.example/archive/master.zip')
  1335. GitLab:
  1336. >>> resolve_source_code('gitlab.com/JoeUser/GrassModule')
  1337. ('remote_zip', 'https://gitlab.com/JoeUser/GrassModule/repository/archive.zip')
  1338. >>> resolve_source_code('https://gitlab.com/JoeUser/GrassModule')
  1339. ('remote_zip', 'https://gitlab.com/JoeUser/GrassModule/repository/archive.zip')
  1340. Bitbucket:
  1341. >>> resolve_source_code('bitbucket.org/joe-user/grass-module')
  1342. ('remote_zip', 'https://bitbucket.org/joe-user/grass-module/get/default.zip')
  1343. >>> resolve_source_code('https://bitbucket.org/joe-user/grass-module')
  1344. ('remote_zip', 'https://bitbucket.org/joe-user/grass-module/get/default.zip')
  1345. """
  1346. if not url and name:
  1347. module_class = get_module_class_name(name)
  1348. trac_url = 'https://trac.osgeo.org/grass/browser/grass-addons/' \
  1349. 'grass{version}/{module_class}/{module_name}?format=zip' \
  1350. .format(version=version[0],
  1351. module_class=module_class, module_name=name)
  1352. return 'official', trac_url
  1353. if os.path.isdir(url):
  1354. return 'dir', os.path.abspath(url)
  1355. elif os.path.exists(url):
  1356. if url.endswith('.zip'):
  1357. return 'zip', os.path.abspath(url)
  1358. for suffix in extract_tar.supported_formats:
  1359. if url.endswith('.' + suffix):
  1360. return suffix, os.path.abspath(url)
  1361. else:
  1362. source, resolved_url = resolve_known_host_service(url)
  1363. if source:
  1364. return source, resolved_url
  1365. # we allow URL to end with =zip or ?zip and not only .zip
  1366. # unfortunately format=zip&version=89612 would require something else
  1367. # special option to force the source type would solve it
  1368. if url.endswith('zip'):
  1369. return 'remote_zip', url
  1370. for suffix in extract_tar.supported_formats:
  1371. if url.endswith(suffix):
  1372. return 'remote_' + suffix, url
  1373. # fallback to the classic behavior
  1374. return 'svn', url
  1375. def main():
  1376. # check dependecies
  1377. if sys.platform != "win32":
  1378. check_progs()
  1379. original_url = options['url']
  1380. # manage proxies
  1381. global PROXIES
  1382. if options['proxy']:
  1383. PROXIES = {}
  1384. for ptype, purl in (p.split('=') for p in options['proxy'].split(',')):
  1385. PROXIES[ptype] = purl
  1386. # define path
  1387. options['prefix'] = resolve_install_prefix(path=options['prefix'],
  1388. to_system=flags['s'])
  1389. # list available extensions
  1390. if flags['l'] or flags['c'] or flags['g']:
  1391. # using dummy module, we don't need any module URL now,
  1392. # but will work only as long as the function does not check
  1393. # if the URL is actually valid or something
  1394. source, url = resolve_source_code(name='dummy',
  1395. url=original_url)
  1396. xmlurl = resolve_xmlurl_prefix(original_url, source=source)
  1397. list_available_extensions(xmlurl)
  1398. return 0
  1399. elif flags['a']:
  1400. list_installed_extensions(toolboxes=flags['t'])
  1401. return 0
  1402. if flags['d']:
  1403. if options['operation'] != 'add':
  1404. grass.warning(_("Flag 'd' is relevant only to"
  1405. " 'operation=add'. Ignoring this flag."))
  1406. else:
  1407. global REMOVE_TMPDIR
  1408. REMOVE_TMPDIR = False
  1409. if options['operation'] == 'add':
  1410. check_dirs()
  1411. source, url = resolve_source_code(name=options['extension'],
  1412. url=original_url)
  1413. xmlurl = resolve_xmlurl_prefix(original_url, source=source)
  1414. install_extension(source=source, url=url, xmlurl=xmlurl)
  1415. else: # remove
  1416. remove_extension(force=flags['f'])
  1417. return 0
  1418. if __name__ == "__main__":
  1419. if len(sys.argv) == 2 and sys.argv[1] == '--doctest':
  1420. import doctest
  1421. _ = str # doctest gettext workaround
  1422. sys.exit(doctest.testmod().failed)
  1423. options, flags = grass.parser()
  1424. global TMPDIR
  1425. TMPDIR = tempfile.mkdtemp()
  1426. atexit.register(cleanup)
  1427. version = grass.version()['version'].split('.')
  1428. sys.exit(main())