g.extension.py 75 KB

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