g.extension.py 84 KB

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