g.extension.py 67 KB

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