g.extension.py 60 KB

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