g.extension.py 59 KB

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