g.extension.py 68 KB

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