g.extension.py 60 KB

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