g.extension.py 59 KB

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