g.extension.py 60 KB

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