g.extension.py 89 KB

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