g.extension.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966
  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. for module in mlist:
  569. if sys.platform == "win32":
  570. ret += install_extension_win(module)
  571. else:
  572. ret1, installed_modules, tmp_dir = install_extension_std_platforms(module,
  573. source=source, url=url)
  574. ret += ret1
  575. if len(mlist) > 1:
  576. print('-' * 60)
  577. if flags['d']:
  578. return
  579. if ret != 0:
  580. grass.warning(_('Installation failed, sorry.'
  581. ' Please check above error messages.'))
  582. else:
  583. # for now it is reasonable to assume that only official source
  584. # will provide the metadata file
  585. if source == 'official' and len(installed_modules) <= len(mlist):
  586. grass.message(_("Updating addons metadata file..."))
  587. blist = install_extension_xml(xmlurl, mlist)
  588. if source == 'official' and len(installed_modules) > len(mlist):
  589. grass.message(_("Updating addons metadata file..."))
  590. blist = install_private_extension_xml(tmp_dir, installed_modules)
  591. else:
  592. grass.message(_("Updating private addons metadata file..."))
  593. if len(installed_modules) > 1:
  594. blist = install_private_extension_xml(tmp_dir, installed_modules)
  595. else:
  596. blist = install_private_extension_xml(tmp_dir, mlist)
  597. # the blist was used here, but it seems that it is the same as mlist
  598. for module in mlist:
  599. update_manual_page(module)
  600. grass.message(_("Installation of <%s> successfully finished") %
  601. options['extension'])
  602. if not os.getenv('GRASS_ADDON_BASE'):
  603. grass.warning(_('This add-on module will not function until'
  604. ' you set the GRASS_ADDON_BASE environment'
  605. ' variable (see "g.manual variables")'))
  606. def get_toolboxes_metadata(url):
  607. """Return metadata for all toolboxes from given URL
  608. :param url: URL of a modules matadata file
  609. :param mlist: list of modules to get metadata for
  610. :returns: tuple where first item is dictionary with module names as keys
  611. and dictionary with dest, keyw, files keys as value, the second item
  612. is list of 'binary' files (installation files)
  613. """
  614. data = dict()
  615. try:
  616. tree = etree_fromurl(url)
  617. for tnode in tree.findall('toolbox'):
  618. clist = list()
  619. for cnode in tnode.findall('correlate'):
  620. clist.append(cnode.get('code'))
  621. mlist = list()
  622. for mnode in tnode.findall('task'):
  623. mlist.append(mnode.get('name'))
  624. code = tnode.get('code')
  625. data[code] = {
  626. 'name': tnode.get('name'),
  627. 'correlate': clist,
  628. 'modules': mlist,
  629. }
  630. except (HTTPError, IOError, OSError):
  631. grass.error(_("Unable to read addons metadata file "
  632. "from the remote server"))
  633. return data
  634. def install_toolbox_xml(url, name):
  635. """Update local toolboxes metadata file"""
  636. # read metadata from remote server (toolboxes)
  637. url = url + "toolboxes.xml"
  638. data = get_toolboxes_metadata(url)
  639. if not data:
  640. grass.warning(_("No addons metadata available"))
  641. return
  642. if name not in data:
  643. grass.warning(_("No addons metadata available for <%s>") % name)
  644. return
  645. xml_file = os.path.join(options['prefix'], 'toolboxes.xml')
  646. # create an empty file if not exists
  647. if not os.path.exists(xml_file):
  648. write_xml_modules(xml_file)
  649. # read XML file
  650. with open(xml_file, 'r') as xml:
  651. tree = etree.fromstring(xml.read())
  652. # update tree
  653. tnode = None
  654. for node in tree.findall('toolbox'):
  655. if node.get('code') == name:
  656. tnode = node
  657. break
  658. tdata = data[name]
  659. if tnode is not None:
  660. # update existing node
  661. for cnode in tnode.findall('correlate'):
  662. tnode.remove(cnode)
  663. for mnode in tnode.findall('task'):
  664. tnode.remove(mnode)
  665. else:
  666. # create new node for task
  667. tnode = etree.Element(
  668. 'toolbox', attrib={'name': tdata['name'], 'code': name})
  669. tree.append(tnode)
  670. for cname in tdata['correlate']:
  671. cnode = etree.Element('correlate', attrib={'code': cname})
  672. tnode.append(cnode)
  673. for tname in tdata['modules']:
  674. mnode = etree.Element('task', attrib={'name': tname})
  675. tnode.append(mnode)
  676. write_xml_toolboxes(xml_file, tree)
  677. def get_addons_metadata(url, mlist):
  678. """Return metadata for list of modules from given URL
  679. :param url: URL of a modules matadata file
  680. :param mlist: list of modules to get metadata for
  681. :returns: tuple where first item is dictionary with module names as keys
  682. and dictionary with dest, keyw, files keys as value, the second item
  683. is list of 'binary' files (installation files)
  684. """
  685. data = {}
  686. bin_list = []
  687. try:
  688. tree = etree_fromurl(url)
  689. except (HTTPError, URLError, IOError, OSError) as error:
  690. grass.error(_("Unable to read addons metadata file"
  691. " from the remote server: {0}").format(error))
  692. return data, bin_list
  693. except ETREE_EXCEPTIONS as error:
  694. grass.warning(_("Unable to parse '%s': {0}").format(error) % url)
  695. return data, bin_list
  696. for mnode in tree.findall('task'):
  697. name = mnode.get('name')
  698. if name not in mlist:
  699. continue
  700. file_list = list()
  701. bnode = mnode.find('binary')
  702. windows = sys.platform == 'win32'
  703. if bnode is not None:
  704. for fnode in bnode.findall('file'):
  705. path = fnode.text.split('/')
  706. if path[0] == 'bin':
  707. bin_list.append(path[-1])
  708. if windows:
  709. path[-1] += '.exe'
  710. elif path[0] == 'scripts':
  711. bin_list.append(path[-1])
  712. if windows:
  713. path[-1] += '.py'
  714. file_list.append(os.path.sep.join(path))
  715. desc, keyw = get_optional_params(mnode)
  716. data[name] = {
  717. 'desc': desc,
  718. 'keyw': keyw,
  719. 'files': file_list,
  720. }
  721. return data, bin_list
  722. def install_extension_xml(url, mlist):
  723. """Update XML files with metadata about installed modules and toolbox
  724. Uses the remote/repository XML files for modules to obtain the metadata.
  725. :returns: list of executables (usable for ``update_manual_page()``)
  726. """
  727. if len(mlist) > 1:
  728. # read metadata from remote server (toolboxes)
  729. install_toolbox_xml(url, options['extension'])
  730. # read metadata from remote server (modules)
  731. url = url + "modules.xml"
  732. data, bin_list = get_addons_metadata(url, mlist)
  733. if not data:
  734. grass.warning(_("No addons metadata available."
  735. " Addons metadata file not updated."))
  736. return []
  737. xml_file = os.path.join(options['prefix'], 'modules.xml')
  738. # create an empty file if not exists
  739. if not os.path.exists(xml_file):
  740. write_xml_modules(xml_file)
  741. # read XML file
  742. tree = etree_fromfile(xml_file)
  743. # update tree
  744. for name in mlist:
  745. tnode = None
  746. for node in tree.findall('task'):
  747. if node.get('name') == name:
  748. tnode = node
  749. break
  750. if name not in data:
  751. grass.warning(_("No addons metadata found for <%s>") % name)
  752. continue
  753. ndata = data[name]
  754. if tnode is not None:
  755. # update existing node
  756. dnode = tnode.find('description')
  757. if dnode is not None:
  758. dnode.text = ndata['desc']
  759. knode = tnode.find('keywords')
  760. if knode is not None:
  761. knode.text = ndata['keyw']
  762. bnode = tnode.find('binary')
  763. if bnode is not None:
  764. tnode.remove(bnode)
  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. else:
  772. # create new node for task
  773. tnode = etree.Element('task', attrib={'name': name})
  774. dnode = etree.Element('description')
  775. dnode.text = ndata['desc']
  776. tnode.append(dnode)
  777. knode = etree.Element('keywords')
  778. knode.text = ndata['keyw']
  779. tnode.append(knode)
  780. bnode = etree.Element('binary')
  781. for file_name in ndata['files']:
  782. fnode = etree.Element('file')
  783. fnode.text = file_name
  784. bnode.append(fnode)
  785. tnode.append(bnode)
  786. tree.append(tnode)
  787. write_xml_modules(xml_file, tree)
  788. return bin_list
  789. def install_private_extension_xml(url, mlist):
  790. """Update XML files with metadata about installed modules and toolbox
  791. of an private addon
  792. """
  793. # TODO toolbox
  794. # if len(mlist) > 1:
  795. # # read metadata from remote server (toolboxes)
  796. # install_toolbox_xml(url, options['extension'])
  797. xml_file = os.path.join(options['prefix'], 'modules.xml')
  798. # create an empty file if not exists
  799. if not os.path.exists(xml_file):
  800. write_xml_modules(xml_file)
  801. # read XML file
  802. tree = etree_fromfile(xml_file)
  803. # update tree
  804. for name in mlist:
  805. try:
  806. desc = gtask.parse_interface(name).description
  807. # mname = gtask.parse_interface(name).name
  808. keywords = gtask.parse_interface(name).keywords
  809. except Exception as e:
  810. grass.warning(_("No addons metadata available."
  811. " Addons metadata file not updated."))
  812. return []
  813. tnode = None
  814. for node in tree.findall('task'):
  815. if node.get('name') == name:
  816. tnode = node
  817. break
  818. # create new node for task
  819. tnode = etree.Element('task', attrib={'name': name})
  820. dnode = etree.Element('description')
  821. dnode.text = desc
  822. tnode.append(dnode)
  823. knode = etree.Element('keywords')
  824. knode.text = (',').join(keywords)
  825. tnode.append(knode)
  826. # create binary
  827. bnode = etree.Element('binary')
  828. list_of_binary_files = []
  829. for file_name in os.listdir(url):
  830. file_type = os.path.splitext(file_name)[-1]
  831. file_n = os.path.splitext(file_name)[0]
  832. html_path = os.path.join(options['prefix'], 'docs', 'html')
  833. c_path = os.path.join(options['prefix'], 'bin')
  834. py_path = os.path.join(options['prefix'], 'scripts')
  835. # html or image file
  836. if file_type in ['.html', '.jpg', '.png'] \
  837. and file_n in os.listdir(html_path):
  838. list_of_binary_files.append(os.path.join(html_path, file_name))
  839. # c file
  840. elif file_type in ['.c'] and file_name in os.listdir(c_path):
  841. list_of_binary_files.append(os.path.join(c_path, file_n))
  842. # python file
  843. elif file_type in ['.py'] and file_name in os.listdir(py_path):
  844. list_of_binary_files.append(os.path.join(py_path, file_n))
  845. # man file
  846. man_path = os.path.join(options['prefix'], 'docs', 'man', 'man1')
  847. if name + '.1' in os.listdir(man_path):
  848. list_of_binary_files.append(os.path.join(man_path, name + '.1'))
  849. # add binaries to xml file
  850. for binary_file_name in list_of_binary_files:
  851. fnode = etree.Element('file')
  852. fnode.text = binary_file_name
  853. bnode.append(fnode)
  854. tnode.append(bnode)
  855. tree.append(tnode)
  856. write_xml_modules(xml_file, tree)
  857. return mlist
  858. def install_extension_win(name):
  859. """Install extension on MS Windows"""
  860. grass.message(_("Downloading precompiled GRASS Addons <%s>...") %
  861. options['extension'])
  862. # build base URL
  863. if build_platform == 'x86_64':
  864. platform = build_platform
  865. else:
  866. platform = 'x86'
  867. base_url = "http://wingrass.fsv.cvut.cz/" \
  868. "grass%(major)s%(minor)s/%(platform)s/addons/" \
  869. "grass-%(major)s.%(minor)s.%(patch)s" % \
  870. {'platform': platform,
  871. 'major': version[0], 'minor': version[1],
  872. 'patch': 'dev'}
  873. # resolve ZIP URL
  874. source, url = resolve_source_code(url='{0}/{1}.zip'.format(base_url, name))
  875. # to hide non-error messages from subprocesses
  876. if grass.verbosity() <= 2:
  877. outdev = open(os.devnull, 'w')
  878. else:
  879. outdev = sys.stdout
  880. # download Addons ZIP file
  881. os.chdir(TMPDIR) # this is just to not leave something behind
  882. srcdir = os.path.join(TMPDIR, name)
  883. download_source_code(source=source, url=url, name=name,
  884. outdev=outdev, directory=srcdir, tmpdir=TMPDIR)
  885. # change shebang from python to python3
  886. pyfiles = []
  887. for r, d, f in os.walk(srcdir):
  888. for file in f:
  889. if file.endswith('.py'):
  890. pyfiles.append(os.path.join(r, file))
  891. for filename in pyfiles:
  892. with fileinput.FileInput(filename, inplace=True) as file:
  893. for line in file:
  894. print(line.replace(
  895. "#!/usr/bin/env python\n",
  896. "#!/usr/bin/env python3\n"
  897. ), end='')
  898. # copy Addons copy tree to destination directory
  899. move_extracted_files(extract_dir=srcdir, target_dir=options['prefix'],
  900. files=os.listdir(srcdir))
  901. return 0
  902. def download_source_code_svn(url, name, outdev, directory=None):
  903. """Download source code from a Subversion reporsitory
  904. .. note:
  905. Stdout is passed to to *outdev* while stderr is will be just printed.
  906. :param url: URL of the repository
  907. (module class/family and name are attached)
  908. :param name: module name
  909. :param outdev: output divide for the standard output of the svn command
  910. :param directory: directory where the source code will be downloaded
  911. (default is the current directory with name attached)
  912. :returns: full path to the directory with the source code
  913. (useful when you not specify directory, if *directory* is specified
  914. the return value is equal to it)
  915. """
  916. if not directory:
  917. directory = os.path.join(os.getcwd, name)
  918. classchar = name.split('.', 1)[0]
  919. moduleclass = expand_module_class_name(classchar)
  920. url = url + '/' + moduleclass + '/' + name
  921. if grass.call(['svn', 'checkout',
  922. url, directory], stdout=outdev) != 0:
  923. grass.fatal(_("GRASS Addons <%s> not found") % name)
  924. return directory
  925. def download_source_code_official_github(url, name, outdev, directory=None):
  926. """Download source code from a official GitHub reporsitory
  927. .. note:
  928. Stdout is passed to to *outdev* while stderr is will be just printed.
  929. :param url: URL of the repository
  930. (module class/family and name are attached)
  931. :param name: module name
  932. :param outdev: output divide for the standard output of the svn command
  933. :param directory: directory where the source code will be downloaded
  934. (default is the current directory with name attached)
  935. :returns: full path to the directory with the source code
  936. (useful when you not specify directory, if *directory* is specified
  937. the return value is equal to it)
  938. """
  939. if not directory:
  940. directory = os.path.join(os.getcwd, name)
  941. classchar = name.split('.', 1)[0]
  942. moduleclass = expand_module_class_name(classchar)
  943. if grass.call(['svn', 'export',
  944. url, directory], stdout=outdev) != 0:
  945. grass.fatal(_("GRASS Addons <%s> not found") % name)
  946. return directory
  947. def move_extracted_files(extract_dir, target_dir, files):
  948. """Fix state of extracted files by moving them to different directory
  949. When extracting, it is not clear what will be the root directory
  950. or if there will be one at all. So this function moves the files to
  951. a different directory in the way that if there was one directory extracted,
  952. the contained files are moved.
  953. """
  954. gscript.debug("move_extracted_files({0})".format(locals()))
  955. if len(files) == 1:
  956. shutil.copytree(os.path.join(extract_dir, files[0]), target_dir)
  957. else:
  958. if not os.path.exists(target_dir):
  959. os.mkdir(target_dir)
  960. for file_name in files:
  961. actual_file = os.path.join(extract_dir, file_name)
  962. if os.path.isdir(actual_file):
  963. # shutil.copytree() replaced by copy_tree() because
  964. # shutil's copytree() fails when subdirectory exists
  965. copy_tree(actual_file,
  966. os.path.join(target_dir, file_name))
  967. else:
  968. shutil.copy(actual_file, os.path.join(target_dir, file_name))
  969. # Original copyright and license of the original version of the CRLF function
  970. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
  971. # Python Software Foundation; All Rights Reserved
  972. # Python Software Foundation License Version 2
  973. # http://svn.python.org/projects/python/trunk/Tools/scripts/crlf.py
  974. def fix_newlines(directory):
  975. """Replace CRLF with LF in all files in the directory
  976. Binary files are ignored. Recurses into subdirectories.
  977. """
  978. # skip binary files
  979. # see https://stackoverflow.com/a/7392391
  980. textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
  981. is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))
  982. for root, unused, files in os.walk(directory):
  983. for name in files:
  984. filename = os.path.join(root, name)
  985. if is_binary_string(open(filename, 'rb').read(1024)):
  986. continue # ignore binary files
  987. # read content of text file
  988. with open(filename, 'rb') as fd:
  989. data = fd.read()
  990. # we don't expect there would be CRLF file by
  991. # purpose if we want to allow CRLF files we would
  992. # have to whitelite .py etc
  993. newdata = data.replace(b'\r\n', b'\n')
  994. if newdata != data:
  995. with open(filename, 'wb') as newfile:
  996. newfile.write(newdata)
  997. def extract_zip(name, directory, tmpdir):
  998. """Extract a ZIP file into a directory"""
  999. gscript.debug("extract_zip(name={name}, directory={directory},"
  1000. " tmpdir={tmpdir})".format(name=name, directory=directory,
  1001. tmpdir=tmpdir), 3)
  1002. try:
  1003. zip_file = zipfile.ZipFile(name, mode='r')
  1004. file_list = zip_file.namelist()
  1005. # we suppose we can write to parent of the given dir
  1006. # (supposing a tmp dir)
  1007. extract_dir = os.path.join(tmpdir, 'extract_dir')
  1008. os.mkdir(extract_dir)
  1009. for subfile in file_list:
  1010. # this should be safe in Python 2.7.4
  1011. zip_file.extract(subfile, extract_dir)
  1012. files = os.listdir(extract_dir)
  1013. move_extracted_files(extract_dir=extract_dir,
  1014. target_dir=directory, files=files)
  1015. except zipfile.BadZipfile as error:
  1016. gscript.fatal(_("ZIP file is unreadable: {0}").format(error))
  1017. # TODO: solve the other related formats
  1018. def extract_tar(name, directory, tmpdir):
  1019. """Extract a TAR or a similar file into a directory"""
  1020. gscript.debug("extract_tar(name={name}, directory={directory},"
  1021. " tmpdir={tmpdir})".format(name=name, directory=directory,
  1022. tmpdir=tmpdir), 3)
  1023. try:
  1024. import tarfile # we don't need it anywhere else
  1025. tar = tarfile.open(name)
  1026. extract_dir = os.path.join(tmpdir, 'extract_dir')
  1027. os.mkdir(extract_dir)
  1028. tar.extractall(path=extract_dir)
  1029. files = os.listdir(extract_dir)
  1030. move_extracted_files(extract_dir=extract_dir,
  1031. target_dir=directory, files=files)
  1032. except tarfile.TarError as error:
  1033. gscript.fatal(_("Archive file is unreadable: {0}").format(error))
  1034. extract_tar.supported_formats = ['tar.gz', 'gz', 'bz2', 'tar', 'gzip', 'targz']
  1035. def download_source_code(source, url, name, outdev,
  1036. directory=None, tmpdir=None):
  1037. """Get source code to a local directory for compilation"""
  1038. gscript.verbose("Downloading source code for <{name}> from <{url}>"
  1039. " which is identified as '{source}' type of source..."
  1040. .format(source=source, url=url, name=name))
  1041. if source == 'official':
  1042. download_source_code_official_github(url, name, outdev, directory)
  1043. elif source == 'svn':
  1044. download_source_code_svn(url, name, outdev, directory)
  1045. elif source in ['remote_zip']: # , 'official'
  1046. # we expect that the module.zip file is not by chance in the archive
  1047. zip_name = os.path.join(tmpdir, 'extension.zip')
  1048. try:
  1049. response = urlopen(url)
  1050. except URLError:
  1051. grass.fatal(_("Extension <%s> not found") % name)
  1052. with open(zip_name, 'wb') as out_file:
  1053. shutil.copyfileobj(response, out_file)
  1054. extract_zip(name=zip_name, directory=directory, tmpdir=tmpdir)
  1055. fix_newlines(directory)
  1056. elif source.startswith('remote_') and \
  1057. source.split('_')[1] in extract_tar.supported_formats:
  1058. # we expect that the module.tar.gz file is not by chance in the archive
  1059. archive_name = os.path.join(tmpdir,
  1060. 'extension.' + source.split('_')[1])
  1061. urlretrieve(url, archive_name)
  1062. extract_tar(name=archive_name, directory=directory, tmpdir=tmpdir)
  1063. fix_newlines(directory)
  1064. elif source == 'zip':
  1065. extract_zip(name=url, directory=directory, tmpdir=tmpdir)
  1066. fix_newlines(directory)
  1067. elif source in extract_tar.supported_formats:
  1068. extract_tar(name=url, directory=directory, tmpdir=tmpdir)
  1069. fix_newlines(directory)
  1070. elif source == 'dir':
  1071. shutil.copytree(url, directory)
  1072. fix_newlines(directory)
  1073. else:
  1074. # probably programmer error
  1075. grass.fatal(_("Unknown extension (addon) source type '{0}'."
  1076. " Please report this to the grass-user mailing list.")
  1077. .format(source))
  1078. assert os.path.isdir(directory)
  1079. def install_extension_std_platforms(name, source, url):
  1080. """Install extension on standard platforms"""
  1081. gisbase = os.getenv('GISBASE')
  1082. source_url = "https://trac.osgeo.org/grass/browser/grass-addons/grass7/"
  1083. if source == 'official':
  1084. gscript.message(_("Fetching <%s> from "
  1085. "GRASS GIS Addons repository (be patient)...") % name)
  1086. else:
  1087. gscript.message(_("Fetching <{name}> from "
  1088. "<{url}> (be patient)...").format(name=name, url=url))
  1089. # to hide non-error messages from subprocesses
  1090. if grass.verbosity() <= 2:
  1091. outdev = open(os.devnull, 'w')
  1092. else:
  1093. outdev = sys.stdout
  1094. os.chdir(TMPDIR) # this is just to not leave something behind
  1095. srcdir = os.path.join(TMPDIR, name)
  1096. download_source_code(source=source, url=url, name=name,
  1097. outdev=outdev, directory=srcdir, tmpdir=TMPDIR)
  1098. os.chdir(srcdir)
  1099. # change shebang from python to python3
  1100. pyfiles = []
  1101. # r=root, d=directories, f = files
  1102. for r, d, f in os.walk(srcdir):
  1103. for file in f:
  1104. if file.endswith('.py'):
  1105. pyfiles.append(os.path.join(r, file))
  1106. for filename in pyfiles:
  1107. with fileinput.FileInput(filename, inplace=True) as file:
  1108. for line in file:
  1109. print(line.replace(
  1110. "#!/usr/bin/env python\n",
  1111. "#!/usr/bin/env python3\n"
  1112. ), end='')
  1113. dirs = {
  1114. 'bin': os.path.join(TMPDIR, name, 'bin'),
  1115. 'docs': os.path.join(TMPDIR, name, 'docs'),
  1116. 'html': os.path.join(TMPDIR, name, 'docs', 'html'),
  1117. 'rest': os.path.join(TMPDIR, name, 'docs', 'rest'),
  1118. 'man': os.path.join(TMPDIR, name, 'docs', 'man'),
  1119. 'script': os.path.join(TMPDIR, name, 'scripts'),
  1120. # TODO: handle locales also for addons
  1121. # 'string' : os.path.join(TMPDIR, name, 'locale'),
  1122. 'string': os.path.join(TMPDIR, name),
  1123. 'etc': os.path.join(TMPDIR, name, 'etc'),
  1124. }
  1125. make_cmd = [
  1126. 'make',
  1127. 'MODULE_TOPDIR=%s' % gisbase.replace(' ', r'\ '),
  1128. 'RUN_GISRC=%s' % os.environ['GISRC'],
  1129. 'BIN=%s' % dirs['bin'],
  1130. 'HTMLDIR=%s' % dirs['html'],
  1131. 'RESTDIR=%s' % dirs['rest'],
  1132. 'MANBASEDIR=%s' % dirs['man'],
  1133. 'SCRIPTDIR=%s' % dirs['script'],
  1134. 'STRINGDIR=%s' % dirs['string'],
  1135. 'ETC=%s' % os.path.join(dirs['etc']),
  1136. 'SOURCE_URL=%s' % source_url
  1137. ]
  1138. install_cmd = [
  1139. 'make',
  1140. 'MODULE_TOPDIR=%s' % gisbase,
  1141. 'ARCH_DISTDIR=%s' % os.path.join(TMPDIR, name),
  1142. 'INST_DIR=%s' % options['prefix'],
  1143. 'install'
  1144. ]
  1145. if flags['d']:
  1146. grass.message("\n%s\n" % _("To compile run:"))
  1147. sys.stderr.write(' '.join(make_cmd) + '\n')
  1148. grass.message("\n%s\n" % _("To install run:"))
  1149. sys.stderr.write(' '.join(install_cmd) + '\n')
  1150. return 0
  1151. os.chdir(os.path.join(TMPDIR, name))
  1152. grass.message(_("Compiling..."))
  1153. if not os.path.exists(os.path.join(gisbase, 'include',
  1154. 'Make', 'Module.make')):
  1155. grass.fatal(_("Please install GRASS development package"))
  1156. if 0 != grass.call(make_cmd,
  1157. stdout=outdev):
  1158. grass.fatal(_('Compilation failed, sorry.'
  1159. ' Please check above error messages.'))
  1160. if flags['i']:
  1161. return 0
  1162. grass.message(_("Installing..."))
  1163. with open(os.path.join(TMPDIR, name, 'Makefile')) as f:
  1164. datafile = f.readlines()
  1165. makefile_part = ""
  1166. next_line = False
  1167. for line in datafile:
  1168. if 'SUBDIRS' in line or next_line:
  1169. makefile_part += line
  1170. if (line.strip()).endswith('\\'):
  1171. next_line = True
  1172. else:
  1173. next_line = False
  1174. modules = makefile_part.replace('SUBDIRS', '').replace('=', '').replace('\\', '').strip().split('\n')
  1175. c_path = os.path.join(options['prefix'], 'bin')
  1176. py_path = os.path.join(options['prefix'], 'scripts')
  1177. all_modules = os.listdir(c_path)
  1178. all_modules.extend(os.listdir(py_path))
  1179. module_list = [x.strip() for x in modules if x.strip() in all_modules]
  1180. return grass.call(install_cmd, stdout=outdev), module_list, os.path.join(TMPDIR, name)
  1181. def remove_extension(force=False):
  1182. """Remove existing extension (module or toolbox if -t is given)"""
  1183. if flags['t']:
  1184. mlist = get_toolbox_modules(options['prefix'], options['extension'])
  1185. else:
  1186. mlist = [options['extension']]
  1187. if force:
  1188. grass.verbose(_("List of removed files:"))
  1189. else:
  1190. grass.info(_("Files to be removed:"))
  1191. remove_modules(mlist, force)
  1192. if force:
  1193. grass.message(_("Updating addons metadata file..."))
  1194. remove_extension_xml(mlist)
  1195. grass.message(_("Extension <%s> successfully uninstalled.") %
  1196. options['extension'])
  1197. else:
  1198. grass.warning(_("Extension <%s> not removed. "
  1199. "Re-run '%s' with '-f' flag to force removal")
  1200. % (options['extension'], 'g.extension'))
  1201. # remove existing extension(s) (reading XML file)
  1202. def remove_modules(mlist, force=False):
  1203. """Remove extensions/modules specified in a list
  1204. Collects the file names from the file with metadata and fallbacks
  1205. to standard layout of files on prefix path on error.
  1206. """
  1207. # try to read XML metadata file first
  1208. xml_file = os.path.join(options['prefix'], 'modules.xml')
  1209. installed = get_installed_modules()
  1210. if os.path.exists(xml_file):
  1211. tree = etree_fromfile(xml_file)
  1212. else:
  1213. tree = None
  1214. for name in mlist:
  1215. if name not in installed:
  1216. # try even if module does not seem to be available,
  1217. # as the user may be trying to get rid of left over cruft
  1218. grass.warning(_("Extension <%s> not found") % name)
  1219. if tree is not None:
  1220. flist = []
  1221. for task in tree.findall('task'):
  1222. if name == task.get('name') and \
  1223. task.find('binary') is not None:
  1224. flist = get_module_files(task)
  1225. break
  1226. if flist:
  1227. removed = False
  1228. err = list()
  1229. for fpath in flist:
  1230. grass.verbose(fpath)
  1231. if force:
  1232. try:
  1233. os.remove(fpath)
  1234. removed = True
  1235. except OSError:
  1236. msg = "Unable to remove file '%s'"
  1237. err.append((_(msg) % fpath))
  1238. if force and not removed:
  1239. grass.fatal(_("Extension <%s> not found") % name)
  1240. if err:
  1241. for error_line in err:
  1242. grass.error(error_line)
  1243. else:
  1244. remove_extension_std(name, force)
  1245. else:
  1246. remove_extension_std(name, force)
  1247. # remove module libraries directories under GRASS_ADDONS/etc/{name}/*
  1248. libpath = os.path.join(options['prefix'], 'etc', name)
  1249. if os.path.isdir(libpath):
  1250. grass.verbose(libpath)
  1251. if force:
  1252. shutil.rmtree(libpath)
  1253. def remove_extension_std(name, force=False):
  1254. """Remove extension/module expecting the standard layout"""
  1255. for fpath in [os.path.join(options['prefix'], 'bin', name),
  1256. os.path.join(options['prefix'], 'scripts', name),
  1257. os.path.join(
  1258. options['prefix'], 'docs', 'html', name + '.html'),
  1259. os.path.join(
  1260. options['prefix'], 'docs', 'rest', name + '.txt'),
  1261. os.path.join(options['prefix'], 'docs', 'man', 'man1',
  1262. name + '.1')]:
  1263. if os.path.isfile(fpath):
  1264. grass.verbose(fpath)
  1265. if force:
  1266. os.remove(fpath)
  1267. # remove module libraries under GRASS_ADDONS/etc/{name}/*
  1268. libpath = os.path.join(options['prefix'], 'etc', name)
  1269. if os.path.isdir(libpath):
  1270. grass.verbose(libpath)
  1271. if force:
  1272. shutil.rmtree(libpath)
  1273. def remove_from_toolbox_xml(name):
  1274. """Update local meta-file when removing existing toolbox"""
  1275. xml_file = os.path.join(options['prefix'], 'toolboxes.xml')
  1276. if not os.path.exists(xml_file):
  1277. return
  1278. # read XML file
  1279. tree = etree_fromfile(xml_file)
  1280. for node in tree.findall('toolbox'):
  1281. if node.get('code') != name:
  1282. continue
  1283. tree.remove(node)
  1284. write_xml_toolboxes(xml_file, tree)
  1285. def remove_extension_xml(modules):
  1286. """Update local meta-file when removing existing extension"""
  1287. if len(modules) > 1:
  1288. # update also toolboxes metadata
  1289. remove_from_toolbox_xml(options['extension'])
  1290. xml_file = os.path.join(options['prefix'], 'modules.xml')
  1291. if not os.path.exists(xml_file):
  1292. return
  1293. # read XML file
  1294. tree = etree_fromfile(xml_file)
  1295. for name in modules:
  1296. for node in tree.findall('task'):
  1297. if node.get('name') != name:
  1298. continue
  1299. tree.remove(node)
  1300. write_xml_modules(xml_file, tree)
  1301. # check links in CSS
  1302. def check_style_files(fil):
  1303. """Ensures that a specified HTML documentation support file exists
  1304. If the file, e.g. a CSS file does not exist, the file is copied from
  1305. the distribution.
  1306. """
  1307. dist_file = os.path.join(os.getenv('GISBASE'), 'docs', 'html', fil)
  1308. addons_file = os.path.join(options['prefix'], 'docs', 'html', fil)
  1309. if os.path.isfile(addons_file):
  1310. return
  1311. try:
  1312. shutil.copyfile(dist_file, addons_file)
  1313. except OSError as error:
  1314. grass.fatal(_("Unable to create '%s': %s") % (addons_file, error))
  1315. def create_dir(path):
  1316. """Creates the specified directory (with all dirs in between)
  1317. NOOP for existing directory.
  1318. """
  1319. if os.path.isdir(path):
  1320. return
  1321. try:
  1322. os.makedirs(path)
  1323. except OSError as error:
  1324. grass.fatal(_("Unable to create '%s': %s") % (path, error))
  1325. grass.debug("'%s' created" % path)
  1326. def check_dirs():
  1327. """Ensure that the necessary directories in prefix path exist"""
  1328. create_dir(os.path.join(options['prefix'], 'bin'))
  1329. create_dir(os.path.join(options['prefix'], 'docs', 'html'))
  1330. create_dir(os.path.join(options['prefix'], 'docs', 'rest'))
  1331. check_style_files('grass_logo.png')
  1332. check_style_files('grassdocs.css')
  1333. create_dir(os.path.join(options['prefix'], 'etc'))
  1334. create_dir(os.path.join(options['prefix'], 'docs', 'man', 'man1'))
  1335. create_dir(os.path.join(options['prefix'], 'scripts'))
  1336. # fix file URI in manual page
  1337. def update_manual_page(module):
  1338. """Fix manual page for addons which are at different directory then rest"""
  1339. if module.split('.', 1)[0] == 'wx':
  1340. return # skip for GUI modules
  1341. grass.verbose(_("Manual page for <%s> updated") % module)
  1342. # read original html file
  1343. htmlfile = os.path.join(
  1344. options['prefix'], 'docs', 'html', module + '.html')
  1345. try:
  1346. oldfile = open(htmlfile)
  1347. shtml = oldfile.read()
  1348. except IOError as error:
  1349. gscript.fatal(_("Unable to read manual page: %s") % error)
  1350. else:
  1351. oldfile.close()
  1352. pos = []
  1353. # fix logo URL
  1354. pattern = r'''<a href="([^"]+)"><img src="grass_logo.png"'''
  1355. for match in re.finditer(pattern, shtml):
  1356. pos.append(match.start(1))
  1357. # find URIs
  1358. pattern = r'''<a href="([^"]+)">([^>]+)</a>'''
  1359. addons = get_installed_extensions(force=True)
  1360. for match in re.finditer(pattern, shtml):
  1361. if match.group(1)[:4] == 'http':
  1362. continue
  1363. if match.group(1).replace('.html', '') in addons:
  1364. continue
  1365. pos.append(match.start(1))
  1366. if not pos:
  1367. return # no match
  1368. # replace file URIs
  1369. prefix = 'file://' + '/'.join([os.getenv('GISBASE'), 'docs', 'html'])
  1370. ohtml = shtml[:pos[0]]
  1371. for i in range(1, len(pos)):
  1372. ohtml += prefix + '/' + shtml[pos[i - 1]:pos[i]]
  1373. ohtml += prefix + '/' + shtml[pos[-1]:]
  1374. # write updated html file
  1375. try:
  1376. newfile = open(htmlfile, 'w')
  1377. newfile.write(ohtml)
  1378. except IOError as error:
  1379. gscript.fatal(_("Unable for write manual page: %s") % error)
  1380. else:
  1381. newfile.close()
  1382. def resolve_install_prefix(path, to_system):
  1383. """Determine and check the path for installation"""
  1384. if to_system:
  1385. path = os.environ['GISBASE']
  1386. if path == '$GRASS_ADDON_BASE':
  1387. if not os.getenv('GRASS_ADDON_BASE'):
  1388. grass.warning(_("GRASS_ADDON_BASE is not defined, "
  1389. "installing to ~/.grass%s/addons") % version[0])
  1390. path = os.path.join(
  1391. os.environ['HOME'], '.grass%s' % version[0], 'addons')
  1392. else:
  1393. path = os.environ['GRASS_ADDON_BASE']
  1394. if os.path.exists(path) and \
  1395. not os.access(path, os.W_OK):
  1396. grass.fatal(_("You don't have permission to install extension to <{0}>."
  1397. " Try to run {1} with administrator rights"
  1398. " (su or sudo).")
  1399. .format(path, 'g.extension'))
  1400. # ensure dir sep at the end for cases where path is used as URL and pasted
  1401. # together with file names
  1402. if not path.endswith(os.path.sep):
  1403. path = path + os.path.sep
  1404. return os.path.abspath(path) # make likes absolute paths
  1405. def resolve_xmlurl_prefix(url, source=None):
  1406. """Determine and check the URL where the XML metadata files are stored
  1407. It ensures that there is a single slash at the end of URL, so we can attach
  1408. file name easily:
  1409. >>> resolve_xmlurl_prefix('https://grass.osgeo.org/addons')
  1410. 'https://grass.osgeo.org/addons/'
  1411. >>> resolve_xmlurl_prefix('https://grass.osgeo.org/addons/')
  1412. 'https://grass.osgeo.org/addons/'
  1413. """
  1414. gscript.debug("resolve_xmlurl_prefix(url={0}, source={1})".format(url, source))
  1415. if source == 'official':
  1416. # use pregenerated modules XML file
  1417. url = 'https://grass.osgeo.org/addons/grass%s/' % version[0]
  1418. # else try to get modules XMl from SVN repository (provided URL)
  1419. # the exact action depends on subsequent code (somewhere)
  1420. if not url.endswith('/'):
  1421. url = url + '/'
  1422. return url
  1423. KNOWN_HOST_SERVICES_INFO = {
  1424. 'OSGeo Trac': {
  1425. 'domain': 'trac.osgeo.org',
  1426. 'ignored_suffixes': ['format=zip'],
  1427. 'possible_starts': ['', 'https://', 'http://'],
  1428. 'url_start': 'https://',
  1429. 'url_end': '?format=zip',
  1430. },
  1431. 'GitHub': {
  1432. 'domain': 'github.com',
  1433. 'ignored_suffixes': ['.zip', '.tar.gz'],
  1434. 'possible_starts': ['', 'https://', 'http://'],
  1435. 'url_start': 'https://',
  1436. 'url_end': '/archive/master.zip',
  1437. },
  1438. 'GitLab': {
  1439. 'domain': 'gitlab.com',
  1440. 'ignored_suffixes': ['.zip', '.tar.gz', '.tar.bz2', '.tar'],
  1441. 'possible_starts': ['', 'https://', 'http://'],
  1442. 'url_start': 'https://',
  1443. 'url_end': '/repository/archive.zip',
  1444. },
  1445. 'Bitbucket': {
  1446. 'domain': 'bitbucket.org',
  1447. 'ignored_suffixes': ['.zip', '.tar.gz', '.gz', '.bz2'],
  1448. 'possible_starts': ['', 'https://', 'http://'],
  1449. 'url_start': 'https://',
  1450. 'url_end': '/get/master.zip',
  1451. },
  1452. }
  1453. # TODO: support ZIP URLs which don't end with zip
  1454. # https://gitlab.com/user/reponame/repository/archive.zip?ref=b%C3%A9po
  1455. def resolve_known_host_service(url):
  1456. """Determine source type and full URL for known hosting service
  1457. If the service is not determined from the provided URL, tuple with
  1458. is two ``None`` values is returned.
  1459. """
  1460. match = None
  1461. actual_start = None
  1462. for key, value in KNOWN_HOST_SERVICES_INFO.items():
  1463. for start in value['possible_starts']:
  1464. if url.startswith(start + value['domain']):
  1465. match = value
  1466. actual_start = start
  1467. gscript.verbose(_("Identified {0} as known hosting service")
  1468. .format(key))
  1469. for suffix in value['ignored_suffixes']:
  1470. if url.endswith(suffix):
  1471. gscript.verbose(
  1472. _("Not using {service} as known hosting service"
  1473. " because the URL ends with '{suffix}'")
  1474. .format(service=key, suffix=suffix))
  1475. return None, None
  1476. if match:
  1477. if not actual_start:
  1478. actual_start = match['url_start']
  1479. else:
  1480. actual_start = ''
  1481. url = '{prefix}{base}{suffix}'.format(prefix=actual_start,
  1482. base=url.rstrip('/'),
  1483. suffix=match['url_end'])
  1484. gscript.verbose(_("Will use the following URL for download: {0}")
  1485. .format(url))
  1486. return 'remote_zip', url
  1487. else:
  1488. return None, None
  1489. # TODO: add also option to enforce the source type
  1490. def resolve_source_code(url=None, name=None):
  1491. """Return type and URL or path of the source code
  1492. Local paths are not presented as URLs to be usable in standard functions.
  1493. Path is identified as local path if the directory of file exists which
  1494. has the unfortunate consequence that the not existing files are evaluated
  1495. as remote URLs. When path is not evaluated, Subversion is assumed for
  1496. backwards compatibility. When GitHub repository is specified, ZIP file
  1497. link is returned. The ZIP is for master branch, not the default one because
  1498. GitHub does not provide the default branch in the URL (July 2015).
  1499. :returns: tuple with type of source and full URL or path
  1500. Official repository:
  1501. >>> resolve_source_code(name='g.example') # doctest: +SKIP
  1502. ('official', 'https://trac.osgeo.org/.../general/g.example')
  1503. Subversion:
  1504. >>> resolve_source_code('https://svn.osgeo.org/grass/grass-addons/grass7')
  1505. ('svn', 'https://svn.osgeo.org/grass/grass-addons/grass7')
  1506. ZIP files online:
  1507. >>> resolve_source_code('https://trac.osgeo.org/.../r.modis?format=zip') # doctest: +SKIP
  1508. ('remote_zip', 'https://trac.osgeo.org/.../r.modis?format=zip')
  1509. Local directories and ZIP files:
  1510. >>> resolve_source_code(os.path.expanduser("~")) # doctest: +ELLIPSIS
  1511. ('dir', '...')
  1512. >>> resolve_source_code('/local/directory/downloaded.zip') # doctest: +SKIP
  1513. ('zip', '/local/directory/downloaded.zip')
  1514. OSGeo Trac:
  1515. >>> resolve_source_code('trac.osgeo.org/.../r.agent.aco') # doctest: +SKIP
  1516. ('remote_zip', 'https://trac.osgeo.org/.../r.agent.aco?format=zip')
  1517. >>> resolve_source_code('https://trac.osgeo.org/.../r.agent.aco') # doctest: +SKIP
  1518. ('remote_zip', 'https://trac.osgeo.org/.../r.agent.aco?format=zip')
  1519. GitHub:
  1520. >>> resolve_source_code('github.com/user/g.example') # doctest: +SKIP
  1521. ('remote_zip', 'https://github.com/user/g.example/archive/master.zip')
  1522. >>> resolve_source_code('github.com/user/g.example/') # doctest: +SKIP
  1523. ('remote_zip', 'https://github.com/user/g.example/archive/master.zip')
  1524. >>> resolve_source_code('https://github.com/user/g.example') # doctest: +SKIP
  1525. ('remote_zip', 'https://github.com/user/g.example/archive/master.zip')
  1526. >>> resolve_source_code('https://github.com/user/g.example/') # doctest: +SKIP
  1527. ('remote_zip', 'https://github.com/user/g.example/archive/master.zip')
  1528. GitLab:
  1529. >>> resolve_source_code('gitlab.com/JoeUser/GrassModule') # doctest: +SKIP
  1530. ('remote_zip', 'https://gitlab.com/JoeUser/GrassModule/repository/archive.zip')
  1531. >>> resolve_source_code('https://gitlab.com/JoeUser/GrassModule') # doctest: +SKIP
  1532. ('remote_zip', 'https://gitlab.com/JoeUser/GrassModule/repository/archive.zip')
  1533. Bitbucket:
  1534. >>> resolve_source_code('bitbucket.org/joe-user/grass-module') # doctest: +SKIP
  1535. ('remote_zip', 'https://bitbucket.org/joe-user/grass-module/get/default.zip')
  1536. >>> resolve_source_code('https://bitbucket.org/joe-user/grass-module') # doctest: +SKIP
  1537. ('remote_zip', 'https://bitbucket.org/joe-user/grass-module/get/default.zip')
  1538. """
  1539. if not url and name:
  1540. module_class = get_module_class_name(name)
  1541. # note: 'trunk' is required to make URL usable for 'svn export' call
  1542. git_url = 'https://github.com/OSGeo/grass-addons/trunk/' \
  1543. 'grass{version}/{module_class}/{module_name}' \
  1544. .format(version=version[0],
  1545. module_class=module_class, module_name=name)
  1546. # trac_url = 'https://trac.osgeo.org/grass/browser/grass-addons/' \
  1547. # 'grass{version}/{module_class}/{module_name}?format=zip' \
  1548. # .format(version=version[0],
  1549. # module_class=module_class, module_name=name)
  1550. # return 'official', trac_url
  1551. return 'official', git_url
  1552. # Check if URL can be found
  1553. # Catch corner case if local URL is given starting with file://
  1554. url = url[6:] if url.startswith('file://') else url
  1555. if not os.path.exists(url):
  1556. url_validated = False
  1557. if url.startswith('http'):
  1558. try:
  1559. open_url = urlopen(url)
  1560. open_url.close()
  1561. url_validated = True
  1562. except:
  1563. pass
  1564. else:
  1565. try:
  1566. open_url = urlopen('http://' + url)
  1567. open_url.close()
  1568. url_validated = True
  1569. except:
  1570. pass
  1571. try:
  1572. open_url = urlopen('https://' + url)
  1573. open_url.close()
  1574. url_validated = True
  1575. except:
  1576. pass
  1577. if not url_validated:
  1578. grass.fatal(_('Cannot open URL: {}'.format(url)))
  1579. # Handle local URLs
  1580. if os.path.isdir(url):
  1581. return 'dir', os.path.abspath(url)
  1582. elif os.path.exists(url):
  1583. if url.endswith('.zip'):
  1584. return 'zip', os.path.abspath(url)
  1585. for suffix in extract_tar.supported_formats:
  1586. if url.endswith('.' + suffix):
  1587. return suffix, os.path.abspath(url)
  1588. # Handle remote URLs
  1589. else:
  1590. source, resolved_url = resolve_known_host_service(url)
  1591. if source:
  1592. return source, resolved_url
  1593. # we allow URL to end with =zip or ?zip and not only .zip
  1594. # unfortunately format=zip&version=89612 would require something else
  1595. # special option to force the source type would solve it
  1596. if url.endswith('zip'):
  1597. return 'remote_zip', url
  1598. for suffix in extract_tar.supported_formats:
  1599. if url.endswith(suffix):
  1600. return 'remote_' + suffix, url
  1601. # fallback to the classic behavior
  1602. return 'svn', url
  1603. def main():
  1604. # check dependencies
  1605. if not flags['a'] and sys.platform != "win32":
  1606. check_progs()
  1607. original_url = options['url']
  1608. # manage proxies
  1609. global PROXIES
  1610. if options['proxy']:
  1611. PROXIES = {}
  1612. for ptype, purl in (p.split('=') for p in options['proxy'].split(',')):
  1613. PROXIES[ptype] = purl
  1614. proxy = ProxyHandler(PROXIES)
  1615. opener = build_opener(proxy)
  1616. install_opener(opener)
  1617. # define path
  1618. options['prefix'] = resolve_install_prefix(path=options['prefix'],
  1619. to_system=flags['s'])
  1620. # list available extensions
  1621. if flags['l'] or flags['c'] or (flags['g'] and not flags['a']):
  1622. # using dummy module, we don't need any module URL now,
  1623. # but will work only as long as the function does not check
  1624. # if the URL is actually valid or something
  1625. source, url = resolve_source_code(name='dummy',
  1626. url=original_url)
  1627. xmlurl = resolve_xmlurl_prefix(original_url, source=source)
  1628. list_available_extensions(xmlurl)
  1629. return 0
  1630. elif flags['a']:
  1631. list_installed_extensions(toolboxes=flags['t'])
  1632. return 0
  1633. if flags['d']:
  1634. if options['operation'] != 'add':
  1635. grass.warning(_("Flag 'd' is relevant only to"
  1636. " 'operation=add'. Ignoring this flag."))
  1637. else:
  1638. global REMOVE_TMPDIR
  1639. REMOVE_TMPDIR = False
  1640. if options['operation'] == 'add':
  1641. check_dirs()
  1642. source, url = resolve_source_code(name=options['extension'],
  1643. url=original_url)
  1644. xmlurl = resolve_xmlurl_prefix(original_url, source=source)
  1645. install_extension(source=source, url=url, xmlurl=xmlurl)
  1646. else: # remove
  1647. remove_extension(force=flags['f'])
  1648. return 0
  1649. if __name__ == "__main__":
  1650. if len(sys.argv) == 2 and sys.argv[1] == '--doctest':
  1651. import doctest
  1652. sys.exit(doctest.testmod().failed)
  1653. options, flags = grass.parser()
  1654. global TMPDIR
  1655. TMPDIR = tempfile.mkdtemp()
  1656. atexit.register(cleanup)
  1657. grass_version = grass.version()
  1658. version = grass_version['version'].split('.')
  1659. build_platform = grass_version['build_platform'].split('-', 1)[0]
  1660. sys.exit(main())