grass.py 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744
  1. #!/usr/bin/env python3
  2. #############################################################################
  3. #
  4. # MODULE: GRASS initialization script
  5. # AUTHOR(S): Original author unknown - probably CERL
  6. # Andreas Lange <andreas.lange rhein-main.de>
  7. # Huidae Cho <grass4u gmail.com>
  8. # Justin Hickey <jhickey hpcc.nectec.or.th>
  9. # Markus Neteler <neteler osgeo.org>
  10. # Hamish Bowman <hamish_b yahoo.com>
  11. #
  12. # GRASS 7: converted to Python (based on init.sh shell
  13. # script from GRASS 6) by Glynn Clements
  14. # Martin Landa <landa.martin gmail.com>
  15. # Luca Delucchi <lucadeluge gmail.com>
  16. # Vaclav Petras <wenzeslaus gmail.com> (refactoring and exec)
  17. # PURPOSE: Sets up environment variables, parses any remaining
  18. # command line options for setting the GISDBASE, LOCATION,
  19. # and/or MAPSET. Finally it starts GRASS with the appropriate
  20. # user interface and cleans up after it is finished.
  21. # COPYRIGHT: (C) 2000-2022 by the GRASS Development Team
  22. #
  23. # This program is free software under the GNU General
  24. # Public License (>=v2). Read the file COPYING that
  25. # comes with GRASS for details.
  26. #
  27. #############################################################################
  28. """
  29. Script to run GRASS session.
  30. Some of the functions could be used separately but import from this module
  31. is not safe, i.e. it has side effects (this should be changed in the future).
  32. """
  33. # we allow for long file because we want to avoid imports if possible
  34. # (this makes it more stable since we have to set up paths first)
  35. # pylint: disable=too-many-lines
  36. from __future__ import print_function
  37. import sys
  38. import os
  39. import errno
  40. import atexit
  41. import gettext
  42. import shutil
  43. import signal
  44. import string
  45. import subprocess
  46. import re
  47. import six
  48. import platform
  49. import tempfile
  50. import locale
  51. import uuid
  52. import unicodedata
  53. import argparse
  54. import json
  55. # mechanism meant for debugging this script (only)
  56. # private global to store if we are debugging
  57. _DEBUG = None
  58. # for wxpath
  59. _WXPYTHON_BASE = None
  60. ENCODING = locale.getdefaultlocale()[1]
  61. if ENCODING is None:
  62. ENCODING = "UTF-8"
  63. print("Default locale not found, using UTF-8") # intentionally not translatable
  64. # The "@...@" variables are being substituted during build process
  65. #
  66. # TODO: should GISBASE be renamed to something like GRASS_PATH?
  67. # GISBASE marks complete runtime, so no need to get it here when
  68. # setting it up, possible scenario: existing runtime and starting
  69. # GRASS in that, we want to overwrite the settings, not to take it
  70. # possibly same for GRASS_PROJSHARE and others but maybe not
  71. #
  72. # We need to simultaneously make sure that:
  73. # - we get GISBASE from os.environ if it is defined (doesn't this mean that we are
  74. # already inside a GRASS session? If we are, why do we need to run this script
  75. # again???).
  76. # - GISBASE exists as an ENV variable
  77. #
  78. # pmav99: Ugly as hell, but that's what the code before the refactoring was doing.
  79. if "GISBASE" in os.environ and len(os.getenv("GISBASE")) > 0:
  80. GISBASE = os.path.normpath(os.environ["GISBASE"])
  81. else:
  82. GISBASE = os.path.normpath("@GISBASE@")
  83. os.environ["GISBASE"] = GISBASE
  84. CMD_NAME = "@START_UP@"
  85. GRASS_VERSION = "@GRASS_VERSION_NUMBER@"
  86. GRASS_VERSION_MAJOR = "@GRASS_VERSION_MAJOR@"
  87. GRASS_VERSION_MINOR = "@GRASS_VERSION_MINOR@"
  88. LD_LIBRARY_PATH_VAR = "@LD_LIBRARY_PATH_VAR@"
  89. CONFIG_PROJSHARE = os.environ.get("GRASS_PROJSHARE", "@CONFIG_PROJSHARE@")
  90. # Get the system name
  91. WINDOWS = sys.platform.startswith("win")
  92. CYGWIN = sys.platform.startswith("cygwin")
  93. MACOS = sys.platform.startswith("darwin")
  94. def decode(bytes_, encoding=ENCODING):
  95. """Decode bytes with default locale and return (unicode) string
  96. Adapted from grass.script.core.utils.
  97. No-op if parameter is not bytes (assumed unicode string).
  98. :param bytes bytes_: the bytes to decode
  99. :param encoding: encoding to be used, default value is the system's default
  100. encoding or, if that cannot be determined, 'UTF-8'.
  101. """
  102. if sys.version_info.major >= 3:
  103. unicode = str
  104. if isinstance(bytes_, unicode):
  105. return bytes_
  106. elif isinstance(bytes_, bytes):
  107. return bytes_.decode(encoding)
  108. else:
  109. # if something else than text
  110. raise TypeError("can only accept types str and bytes")
  111. def encode(string, encoding=ENCODING):
  112. """Encode string with default locale and return bytes with that encoding
  113. Adapted from grass.script.core.utils.
  114. No-op if parameter is bytes (assumed already encoded).
  115. This ensures garbage in, garbage out.
  116. :param str string: the string to encode
  117. :param encoding: encoding to be used, default value is the system's default
  118. encoding or, if that cannot be determined, 'UTF-8'.
  119. """
  120. if sys.version_info.major >= 3:
  121. unicode = str
  122. if isinstance(string, bytes):
  123. return string
  124. # this also tests str in Py3:
  125. elif isinstance(string, unicode):
  126. return string.encode(encoding)
  127. else:
  128. # if something else than text
  129. raise TypeError("can only accept types str and bytes")
  130. # see https://trac.osgeo.org/grass/ticket/3508
  131. def to_text_string(obj, encoding=ENCODING):
  132. """Convert `obj` to (unicode) text string"""
  133. if six.PY2:
  134. # Python 2
  135. return encode(obj, encoding=encoding)
  136. else:
  137. # Python 3
  138. return decode(obj, encoding=encoding)
  139. def try_remove(path):
  140. try:
  141. os.remove(path)
  142. except: # noqa: E722
  143. pass
  144. def clean_env():
  145. gisrc = os.environ["GISRC"]
  146. env_curr = read_gisrc(gisrc)
  147. env_new = {}
  148. for k, v in env_curr.items():
  149. if k.endswith("PID") or k.startswith("MONITOR"):
  150. continue
  151. env_new[k] = v
  152. write_gisrc(env_new, gisrc)
  153. def is_debug():
  154. """Returns True if we are in debug mode
  155. For debug messages use ``debug()``.
  156. """
  157. global _DEBUG
  158. if _DEBUG is not None:
  159. return _DEBUG
  160. _DEBUG = os.getenv("GRASS_DEBUG")
  161. # translate to bool (no or empty variable means false)
  162. if _DEBUG:
  163. _DEBUG = True
  164. else:
  165. _DEBUG = False
  166. return _DEBUG
  167. def debug(msg):
  168. """Print a debug message if in debug mode
  169. Do not use translatable strings for debug messages.
  170. """
  171. if is_debug():
  172. sys.stderr.write("DEBUG: %s\n" % msg)
  173. sys.stderr.flush()
  174. def message(msg):
  175. sys.stderr.write(msg + "\n")
  176. sys.stderr.flush()
  177. def warning(text):
  178. sys.stderr.write(_("WARNING") + ": " + text + os.linesep)
  179. def fatal(msg):
  180. sys.stderr.write("%s: " % _("ERROR") + msg + os.linesep)
  181. sys.exit(_("Exiting..."))
  182. def readfile(path):
  183. debug("Reading %s" % path)
  184. f = open(path, "r")
  185. s = f.read()
  186. f.close()
  187. return s
  188. def writefile(path, s):
  189. debug("Writing %s" % path)
  190. f = open(path, "w")
  191. f.write(s)
  192. f.close()
  193. def call(cmd, **kwargs):
  194. """Wrapper for subprocess.call to deal with platform-specific issues"""
  195. if WINDOWS:
  196. kwargs["shell"] = True
  197. return subprocess.call(cmd, **kwargs)
  198. def Popen(cmd, **kwargs): # pylint: disable=C0103
  199. """Wrapper for subprocess.Popen to deal with platform-specific issues"""
  200. if WINDOWS:
  201. kwargs["shell"] = True
  202. return subprocess.Popen(cmd, **kwargs)
  203. def gpath(*args):
  204. """Costruct path to file or directory in GRASS GIS installation
  205. Can be called only after GISBASE was set.
  206. """
  207. return os.path.join(GISBASE, *args)
  208. def wxpath(*args):
  209. """Costruct path to file or directory in GRASS wxGUI
  210. Can be called only after GISBASE was set.
  211. This function does not check if the directories exist or if GUI works
  212. this must be done by the caller if needed.
  213. """
  214. global _WXPYTHON_BASE
  215. if not _WXPYTHON_BASE:
  216. # this can be called only after GISBASE was set
  217. _WXPYTHON_BASE = gpath("gui", "wxpython")
  218. return os.path.join(_WXPYTHON_BASE, *args)
  219. def count_wide_chars(s):
  220. """Returns the number of wide CJK characters in a string.
  221. :param str s: string
  222. """
  223. return sum(
  224. unicodedata.east_asian_width(c) in "WF"
  225. for c in (s if sys.version_info.major >= 3 else unicode(s))
  226. )
  227. def f(fmt, *args):
  228. """Adjusts fixed-width string specifiers for wide CJK characters and
  229. returns a formatted string. Does not support named arguments yet.
  230. :param str fmt: format string
  231. :param *args: arguments for the format string
  232. """
  233. matches = []
  234. # https://docs.python.org/3/library/stdtypes.html#old-string-formatting
  235. for m in re.finditer(
  236. "%([#0 +-]*)([0-9]*)(\.[0-9]*)?([hlL]?[diouxXeEfFgGcrsa%])", fmt
  237. ):
  238. matches.append(m)
  239. if len(matches) != len(args):
  240. raise Exception("The numbers of format specifiers and arguments do not match")
  241. i = len(args) - 1
  242. for m in reversed(matches):
  243. f = m.group(1)
  244. w = m.group(2)
  245. p = m.group(3) or ""
  246. c = m.group(4)
  247. if c == "s" and w:
  248. w = str(int(w) - count_wide_chars(args[i]))
  249. fmt = "".join((fmt[: m.start()], "%", f, w, p, c, fmt[m.end() :]))
  250. i -= 1
  251. return fmt % args
  252. # using format for most but leaving usage of template for the dynamic ones
  253. # two different methods are easy way to implement two phase construction
  254. HELP_TEXT = r"""GRASS GIS $VERSION_NUMBER
  255. Geographic Resources Analysis Support System (GRASS GIS).
  256. {usage}:
  257. $CMD_NAME [-h | --help] [-v | --version]
  258. [-c | -c geofile | -c EPSG:code[:datum_trans] | -c XY]
  259. [-e] [-f] [--text | --gtext | --gui] [--config param]
  260. [[[GISDBASE/]LOCATION/]MAPSET]
  261. $CMD_NAME [FLAG]... GISDBASE/LOCATION/MAPSET --exec EXECUTABLE [EPARAM]...
  262. $CMD_NAME --tmp-location [geofile | EPSG | XY] --exec EXECUTABLE [EPARAM]...
  263. $CMD_NAME --tmp-mapset GISDBASE/LOCATION/ --exec EXECUTABLE [EPARAM]...
  264. {flags}:
  265. -h or --help {help_flag}
  266. -v or --version {version_flag}
  267. -c {create}
  268. -e {exit_after}
  269. -f {force_removal}
  270. --text {text}
  271. {text_detail}
  272. --gtext {gtext}
  273. {gtext_detail}
  274. --gui {gui}
  275. {gui_detail}
  276. --config {config}
  277. {config_detail}
  278. --exec EXECUTABLE {exec_}
  279. {exec_detail}
  280. --tmp-location {tmp_location}
  281. {tmp_location_detail}
  282. --tmp-mapset {tmp_mapset}
  283. {tmp_mapset_detail}
  284. {params}:
  285. GISDBASE {gisdbase}
  286. {gisdbase_detail}
  287. LOCATION {location}
  288. {location_detail}
  289. MAPSET {mapset}
  290. GISDBASE/LOCATION/MAPSET {full_mapset}
  291. EXECUTABLE {executable}
  292. EPARAM {executable_params}
  293. FLAG {standard_flags}
  294. {env_vars}:
  295. GRASS_GUI {gui_var}
  296. GRASS_HTML_BROWSER {html_var}
  297. GRASS_ADDON_PATH {addon_path_var}
  298. GRASS_ADDON_BASE {addon_base_var}
  299. GRASS_PYTHON {python_var}
  300. """
  301. def help_message(default_gui):
  302. t = string.Template(
  303. HELP_TEXT.format(
  304. usage=_("Usage"),
  305. flags=_("Flags"),
  306. help_flag=_("print this help message"),
  307. version_flag=_("show version information and exit"),
  308. create=_("create given database, location or mapset if it doesn't exist"),
  309. exit_after=_(
  310. "exit after creation of location or mapset. Only with -c flag"
  311. ),
  312. force_removal=_(
  313. "force removal of .gislock if exists (use with care!)."
  314. " Only with --text flag"
  315. ),
  316. text=_("use text based interface (skip graphical welcome screen)"),
  317. text_detail=_("and set as default"),
  318. gtext=_("use text based interface (show graphical welcome screen)"),
  319. gtext_detail=_("and set as default"),
  320. gui=_("use $DEFAULT_GUI graphical user interface"),
  321. gui_detail=_("and set as default"),
  322. config=_("print GRASS configuration parameters"),
  323. config_detail=_(
  324. "options: arch,build,compiler,date,path,python_path,revision,svn_revision,version"
  325. ),
  326. params=_("Parameters"),
  327. gisdbase=_("initial GRASS database directory"),
  328. gisdbase_detail=_("directory containing Locations"),
  329. location=_("initial GRASS Location"),
  330. location_detail=_(
  331. "directory containing Mapsets with one common"
  332. " coordinate system (projection)"
  333. ),
  334. mapset=_("initial GRASS Mapset"),
  335. full_mapset=_("fully qualified initial Mapset directory"),
  336. env_vars=_("Environment variables relevant for startup"),
  337. gui_var=_("select GUI (text, gui, gtext)"),
  338. html_var=_("set html web browser for help pages"),
  339. addon_path_var=_(
  340. "set additional path(s) to local GRASS modules or user scripts"
  341. ),
  342. addon_base_var=_(
  343. "set additional GISBASE for locally installed GRASS Addons"
  344. ),
  345. python_var=_("set Python interpreter name to override 'python'"),
  346. exec_=_("execute GRASS module or script"),
  347. exec_detail=_("provided executable will be executed in GRASS session"),
  348. executable=_("GRASS module, script or any other executable"),
  349. executable_params=_("parameters of the executable"),
  350. standard_flags=_("standard flags"),
  351. tmp_location=_("create temporary location (use with the --exec flag)"),
  352. tmp_location_detail=_(
  353. "created in a temporary directory and deleted at exit"
  354. ),
  355. tmp_mapset=_("create temporary mapset (use with the --exec flag)"),
  356. tmp_mapset_detail=_(
  357. "created in the specified location and deleted at exit"
  358. ),
  359. )
  360. )
  361. s = t.substitute(
  362. CMD_NAME=CMD_NAME, DEFAULT_GUI=default_gui, VERSION_NUMBER=GRASS_VERSION
  363. )
  364. sys.stderr.write(s)
  365. def get_grass_config_dir():
  366. """Get configuration directory
  367. Determines path of GRASS GIS user configuration directory and creates
  368. it if it does not exist.
  369. Configuration directory is for example used for grass env file
  370. (the one which caries mapset settings from session to session).
  371. """
  372. if WINDOWS:
  373. grass_config_dirname = f"GRASS{GRASS_VERSION_MAJOR}"
  374. win_conf_path = os.getenv("APPDATA")
  375. # this can happen with some strange settings
  376. if not win_conf_path:
  377. fatal(
  378. _(
  379. "The APPDATA variable is not set, ask your operating"
  380. " system support"
  381. )
  382. )
  383. if not os.path.exists(win_conf_path):
  384. fatal(
  385. _(
  386. "The APPDATA variable points to directory which does"
  387. " not exist, ask your operating system support"
  388. )
  389. )
  390. directory = os.path.join(win_conf_path, grass_config_dirname)
  391. else:
  392. grass_config_dirname = f".grass{GRASS_VERSION_MAJOR}"
  393. directory = os.path.join(os.getenv("HOME"), grass_config_dirname)
  394. if not os.path.isdir(directory):
  395. try:
  396. os.mkdir(directory)
  397. except OSError as e:
  398. # Can happen as a race condition
  399. if not e.errno == errno.EEXIST or not os.path.isdir(directory):
  400. fatal(
  401. _("Failed to create configuration directory '%s' with error: %s")
  402. % (directory, e.strerror)
  403. )
  404. return directory
  405. def create_tmp(user, gis_lock):
  406. """Create temporary directory
  407. :param user: user name to be used in the directory name
  408. :param gis_lock: session lock filename to be used in the directory name
  409. """
  410. # use $TMPDIR if it exists, then $TEMP, otherwise /tmp
  411. tmp = os.getenv("TMPDIR")
  412. if not tmp:
  413. tmp = os.getenv("TEMP")
  414. if not tmp:
  415. tmp = os.getenv("TMP")
  416. if not tmp:
  417. tmp = tempfile.gettempdir()
  418. tmpdir_name = f"grass{GRASS_VERSION_MAJOR}-{user}-{gis_lock}"
  419. if tmp:
  420. tmpdir = os.path.join(tmp, tmpdir_name)
  421. try:
  422. os.mkdir(tmpdir, 0o700)
  423. except: # noqa: E722
  424. tmp = None
  425. if not tmp:
  426. for ttmp in ("/tmp", "/var/tmp", "/usr/tmp"):
  427. tmp = ttmp
  428. tmpdir = os.path.join(tmp, tmpdir_name)
  429. try:
  430. os.mkdir(tmpdir, 0o700)
  431. except: # noqa: E722
  432. tmp = None
  433. if tmp:
  434. break
  435. if not tmp:
  436. fatal(
  437. _("Unable to create temporary directory <{tmpdir_name}>! Exiting.").format(
  438. tmpdir_name=tmpdir_name
  439. )
  440. )
  441. # promoting the variable even if it was not defined before
  442. os.environ["TMPDIR"] = tmpdir
  443. debug(
  444. "Tmp directory '{tmpdir}' created for user '{user}'".format(
  445. tmpdir=tmpdir, user=user
  446. )
  447. )
  448. return tmpdir
  449. def get_gisrc_from_config_dir(grass_config_dir, batch_job):
  450. """Set the global grassrc file (aka grassrcrc)"""
  451. if batch_job:
  452. # TODO: This is probably not needed since batch job does write to config.
  453. # use individual GISRCRC files when in batch mode (r33174)
  454. filename = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  455. if os.access(filename, os.R_OK):
  456. return filename
  457. # use standard file if in normal mode or the special file is not available
  458. return os.path.join(grass_config_dir, "rc")
  459. def create_gisrc(tmpdir, gisrcrc):
  460. # Set the session grassrc file
  461. gisrc = os.path.join(tmpdir, "gisrc")
  462. os.environ["GISRC"] = gisrc
  463. # remove invalid GISRC file to avoid disturbing error messages:
  464. try:
  465. s = readfile(gisrcrc)
  466. if "UNKNOWN" in s:
  467. try_remove(gisrcrc)
  468. s = None
  469. except:
  470. s = None
  471. # Copy the global grassrc file to the session grassrc file
  472. if s:
  473. writefile(gisrc, s)
  474. return gisrc
  475. def read_gisrc(filename):
  476. kv = {}
  477. try:
  478. f = open(filename, "r")
  479. except IOError:
  480. return kv
  481. for line in f:
  482. try:
  483. k, v = line.split(":", 1)
  484. except ValueError as e:
  485. warning(
  486. _("Invalid line in RC file ({file}):" " '{line}' ({error})\n").format(
  487. line=line, error=e, file=filename
  488. )
  489. )
  490. continue
  491. kv[k.strip()] = v.strip()
  492. if not kv:
  493. warning(_("Empty RC file ({file})").format(file=filename))
  494. f.close()
  495. return kv
  496. def write_gisrcrc(gisrcrc, gisrc, skip_variable=None):
  497. """Reads gisrc file and write to gisrcrc"""
  498. debug("Reading %s" % gisrc)
  499. number = 0
  500. with open(gisrc, "r") as f:
  501. lines = f.readlines()
  502. for line in lines:
  503. if skip_variable in line:
  504. del lines[number]
  505. number += 1
  506. with open(gisrcrc, "w") as f:
  507. for line in lines:
  508. f.write(line)
  509. def read_env_file(path):
  510. kv = {}
  511. f = open(path, "r")
  512. for line in f:
  513. k, v = line.split(":", 1)
  514. kv[k.strip()] = v.strip()
  515. f.close()
  516. return kv
  517. def write_gisrc(kv, filename, append=False):
  518. # use append=True to avoid a race condition between write_gisrc() and
  519. # grass_prompt() on startup (PR #548)
  520. f = open(filename, "a" if append else "w")
  521. for k, v in kv.items():
  522. f.write("%s: %s\n" % (k, v))
  523. f.close()
  524. def add_mapset_to_gisrc(gisrc, grassdb, location, mapset):
  525. if os.access(gisrc, os.R_OK):
  526. kv = read_gisrc(gisrc)
  527. else:
  528. kv = {}
  529. kv["GISDBASE"] = grassdb
  530. kv["LOCATION_NAME"] = location
  531. kv["MAPSET"] = mapset
  532. write_gisrc(kv, gisrc)
  533. def add_last_mapset_to_gisrc(gisrc, last_mapset_path):
  534. if os.access(gisrc, os.R_OK):
  535. kv = read_gisrc(gisrc)
  536. else:
  537. kv = {}
  538. kv["LAST_MAPSET_PATH"] = last_mapset_path
  539. write_gisrc(kv, gisrc)
  540. def create_fallback_session(gisrc, tmpdir):
  541. """Creates fallback temporary session"""
  542. # Create temporary location
  543. set_mapset(
  544. gisrc=gisrc,
  545. geofile="XY",
  546. create_new=True,
  547. tmp_location=True,
  548. tmpdir=tmpdir,
  549. )
  550. def read_gui(gisrc, default_gui):
  551. grass_gui = None
  552. # At this point the GRASS user interface variable has been set from the
  553. # command line, been set from an external environment variable,
  554. # or is not set. So we check if it is not set
  555. # Check for a reference to the GRASS user interface in the grassrc file
  556. if os.access(gisrc, os.R_OK):
  557. kv = read_gisrc(gisrc)
  558. if "GRASS_GUI" in os.environ:
  559. grass_gui = os.environ["GRASS_GUI"]
  560. elif "GUI" in kv:
  561. grass_gui = kv["GUI"]
  562. elif "GRASS_GUI" in kv:
  563. # For backward compatibility (GRASS_GUI renamed to GUI)
  564. grass_gui = kv["GRASS_GUI"]
  565. else:
  566. # Set the GRASS user interface to the default if needed
  567. grass_gui = default_gui
  568. if not grass_gui:
  569. grass_gui = default_gui
  570. if grass_gui == "gui":
  571. grass_gui = default_gui
  572. # FIXME oldtcltk, gis.m, d.m no longer exist (remove this around 7.2)
  573. if grass_gui in ["d.m", "gis.m", "oldtcltk", "tcltk"]:
  574. warning(_("GUI <%s> not supported in this version") % grass_gui)
  575. grass_gui = default_gui
  576. return grass_gui
  577. def path_prepend(directory, var):
  578. path = os.getenv(var)
  579. if path:
  580. path = directory + os.pathsep + path
  581. else:
  582. path = directory
  583. os.environ[var] = path
  584. def path_append(directory, var):
  585. path = os.getenv(var)
  586. if path:
  587. path = path + os.pathsep + directory
  588. else:
  589. path = directory
  590. os.environ[var] = path
  591. def set_paths(grass_config_dir):
  592. # addons (path)
  593. addon_path = os.getenv("GRASS_ADDON_PATH")
  594. if addon_path:
  595. for path in addon_path.split(os.pathsep):
  596. path_prepend(addon_path, "PATH")
  597. # addons (base)
  598. addon_base = os.getenv("GRASS_ADDON_BASE")
  599. if not addon_base:
  600. if MACOS:
  601. version = f"{GRASS_VERSION_MAJOR}.{GRASS_VERSION_MINOR}"
  602. addon_base = os.path.join(
  603. os.getenv("HOME"), "Library", "GRASS", version, "Addons"
  604. )
  605. else:
  606. addon_base = os.path.join(grass_config_dir, "addons")
  607. os.environ["GRASS_ADDON_BASE"] = addon_base
  608. if not WINDOWS:
  609. path_prepend(os.path.join(addon_base, "scripts"), "PATH")
  610. path_prepend(os.path.join(addon_base, "bin"), "PATH")
  611. # standard installation
  612. if not WINDOWS:
  613. path_prepend(gpath("scripts"), "PATH")
  614. path_prepend(gpath("bin"), "PATH")
  615. # Set PYTHONPATH to find GRASS Python modules
  616. if os.path.exists(gpath("etc", "python")):
  617. pythonpath = gpath("etc", "python")
  618. path_prepend(pythonpath, "PYTHONPATH")
  619. # the env var PYTHONPATH is only evaluated when python is started,
  620. # thus:
  621. sys.path.append(pythonpath)
  622. # now we can import stuff from grass package
  623. # set path for the GRASS man pages
  624. grass_man_path = gpath("docs", "man")
  625. addons_man_path = os.path.join(addon_base, "docs", "man")
  626. man_path = os.getenv("MANPATH")
  627. sys_man_path = None
  628. if man_path:
  629. path_prepend(addons_man_path, "MANPATH")
  630. path_prepend(grass_man_path, "MANPATH")
  631. else:
  632. try:
  633. nul = open(os.devnull, "w")
  634. p = Popen(["manpath"], stdout=subprocess.PIPE, stderr=nul)
  635. nul.close()
  636. s = p.stdout.read()
  637. p.wait()
  638. sys_man_path = s.strip()
  639. except:
  640. pass
  641. if sys_man_path:
  642. os.environ["MANPATH"] = to_text_string(sys_man_path)
  643. path_prepend(addons_man_path, "MANPATH")
  644. path_prepend(grass_man_path, "MANPATH")
  645. else:
  646. os.environ["MANPATH"] = to_text_string(addons_man_path)
  647. path_prepend(grass_man_path, "MANPATH")
  648. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  649. # this works for subprocesses but won't affect the current process
  650. path_prepend(gpath("lib"), LD_LIBRARY_PATH_VAR)
  651. def find_exe(pgm):
  652. for directory in os.getenv("PATH").split(os.pathsep):
  653. path = os.path.join(directory, pgm)
  654. if os.access(path, os.X_OK):
  655. return path
  656. return None
  657. def set_defaults():
  658. # GRASS_PAGER
  659. if not os.getenv("GRASS_PAGER"):
  660. if find_exe("more"):
  661. pager = "more"
  662. elif find_exe("less"):
  663. pager = "less"
  664. elif WINDOWS:
  665. pager = "more"
  666. else:
  667. pager = "cat"
  668. os.environ["GRASS_PAGER"] = pager
  669. # GRASS_PYTHON
  670. if not os.getenv("GRASS_PYTHON"):
  671. if WINDOWS:
  672. os.environ["GRASS_PYTHON"] = "python3.exe"
  673. else:
  674. os.environ["GRASS_PYTHON"] = "python3"
  675. # GRASS_GNUPLOT
  676. if not os.getenv("GRASS_GNUPLOT"):
  677. os.environ["GRASS_GNUPLOT"] = "gnuplot -persist"
  678. # GRASS_PROJSHARE
  679. if not os.getenv("GRASS_PROJSHARE"):
  680. os.environ["GRASS_PROJSHARE"] = CONFIG_PROJSHARE
  681. def set_display_defaults():
  682. """Predefine monitor size for certain architectures"""
  683. if os.getenv("HOSTTYPE") == "arm":
  684. # small monitor on ARM (iPAQ, zaurus... etc)
  685. os.environ["GRASS_RENDER_HEIGHT"] = "320"
  686. os.environ["GRASS_RENDER_WIDTH"] = "240"
  687. def set_browser():
  688. # GRASS_HTML_BROWSER
  689. browser = os.getenv("GRASS_HTML_BROWSER")
  690. if not browser:
  691. if MACOS:
  692. # OSX doesn't execute browsers from the shell PATH - route through a
  693. # script
  694. browser = gpath("etc", "html_browser_mac.sh")
  695. os.environ["GRASS_HTML_BROWSER_MACOSX"] = "-b com.apple.helpviewer"
  696. if WINDOWS:
  697. browser = "start"
  698. elif CYGWIN:
  699. browser = "explorer"
  700. else:
  701. # the usual suspects
  702. browsers = [
  703. "xdg-open",
  704. "x-www-browser",
  705. "htmlview",
  706. "konqueror",
  707. "mozilla",
  708. "mozilla-firefox",
  709. "firefox",
  710. "iceweasel",
  711. "opera",
  712. "google-chrome",
  713. "chromium",
  714. "netscape",
  715. "dillo",
  716. "lynx",
  717. "links",
  718. "w3c",
  719. ]
  720. for b in browsers:
  721. if find_exe(b):
  722. browser = b
  723. break
  724. elif MACOS:
  725. # OSX doesn't execute browsers from the shell PATH - route through a
  726. # script
  727. os.environ["GRASS_HTML_BROWSER_MACOSX"] = "-b %s" % browser
  728. browser = gpath("etc", "html_browser_mac.sh")
  729. if not browser:
  730. # even so we set to 'xdg-open' as a generic fallback
  731. browser = "xdg-open"
  732. os.environ["GRASS_HTML_BROWSER"] = browser
  733. def ensure_home():
  734. """Set HOME if not set on MS Windows"""
  735. if WINDOWS and not os.getenv("HOME"):
  736. os.environ["HOME"] = os.path.join(os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH"))
  737. def create_initial_gisrc(filename):
  738. # for convenience, define GISDBASE as pwd:
  739. s = (
  740. r"""GISDBASE: %s
  741. LOCATION_NAME: <UNKNOWN>
  742. MAPSET: <UNKNOWN>
  743. """
  744. % os.getcwd()
  745. )
  746. writefile(filename, s)
  747. def check_gui(expected_gui):
  748. grass_gui = expected_gui
  749. # Check if we are running X windows by checking the DISPLAY variable
  750. if os.getenv("DISPLAY") or WINDOWS or MACOS:
  751. # Check if python is working properly
  752. if expected_gui in ("wxpython", "gtext"):
  753. nul = open(os.devnull, "w")
  754. p = Popen(
  755. [os.environ["GRASS_PYTHON"]],
  756. stdin=subprocess.PIPE,
  757. stdout=nul,
  758. stderr=nul,
  759. )
  760. nul.close()
  761. p.stdin.write("variable=True".encode(ENCODING))
  762. p.stdin.close()
  763. p.wait()
  764. msg = None
  765. if p.returncode != 0:
  766. # Python was not found - switch to text interface mode
  767. msg = _(
  768. "The python command does not work as expected.\n"
  769. "Please check your installation or set the GRASS_PYTHON"
  770. " environment variable."
  771. )
  772. if not os.path.exists(wxpath("wxgui.py")):
  773. msg = _("GRASS GUI not found. Please check your installation.")
  774. if msg:
  775. warning(_("{}\nSwitching to text based interface mode.").format(msg))
  776. grass_gui = "text"
  777. else:
  778. # Display a message if a graphical interface was expected
  779. if expected_gui != "text":
  780. # Set the interface mode to text
  781. warning(
  782. _(
  783. "It appears that the X Windows system is not active.\n"
  784. "A graphical based user interface is not supported.\n"
  785. "(DISPLAY variable is not set.)\n"
  786. "Switching to text based interface mode."
  787. )
  788. )
  789. grass_gui = "text"
  790. return grass_gui
  791. def save_gui(gisrc, grass_gui):
  792. """Save the user interface variable in the grassrc file"""
  793. if os.access(gisrc, os.F_OK):
  794. kv = read_gisrc(gisrc)
  795. kv["GUI"] = grass_gui
  796. write_gisrc(kv, gisrc)
  797. def create_location(gisdbase, location, geostring):
  798. """Create GRASS Location using georeferenced file or EPSG
  799. EPSG code format is ``EPSG:code`` or ``EPSG:code:datum_trans``.
  800. :param gisdbase: Path to GRASS GIS database directory
  801. :param location: name of new Location
  802. :param geostring: path to a georeferenced file or EPSG code
  803. """
  804. if gpath("etc", "python") not in sys.path:
  805. sys.path.append(gpath("etc", "python"))
  806. from grass.script import core as gcore # pylint: disable=E0611
  807. try:
  808. if geostring and geostring.upper().find("EPSG:") > -1:
  809. # create location using EPSG code
  810. epsg = geostring.split(":", 1)[1]
  811. if ":" in epsg:
  812. epsg, datum_trans = epsg.split(":", 1)
  813. else:
  814. datum_trans = None
  815. gcore.create_location(
  816. gisdbase, location, epsg=epsg, datum_trans=datum_trans
  817. )
  818. elif geostring == "XY":
  819. # create an XY location
  820. gcore.create_location(gisdbase, location)
  821. else:
  822. # create location using georeferenced file
  823. gcore.create_location(gisdbase, location, filename=geostring)
  824. except gcore.ScriptError as err:
  825. fatal(err.value.strip('"').strip("'").replace("\\n", os.linesep))
  826. def can_create_location(gisdbase, location):
  827. """Checks if location can be created"""
  828. path = os.path.join(gisdbase, location)
  829. if os.path.exists(path):
  830. return False
  831. return True
  832. def cannot_create_location_reason(gisdbase, location):
  833. """Returns a message describing why location cannot be created
  834. The goal is to provide the most suitable error message
  835. (rather than to do a quick check).
  836. :param gisdbase: Path to GRASS GIS database directory
  837. :param location: name of a Location
  838. :returns: translated message
  839. """
  840. from grass.grassdb.checks import is_location_valid
  841. path = os.path.join(gisdbase, location)
  842. if is_location_valid(gisdbase, location):
  843. return _(
  844. "Unable to create new location because"
  845. " the location <{location}>"
  846. " already exists."
  847. ).format(**locals())
  848. elif os.path.isfile(path):
  849. return _(
  850. "Unable to create new location <{location}> because" " <{path}> is a file."
  851. ).format(**locals())
  852. elif os.path.isdir(path):
  853. return _(
  854. "Unable to create new location <{location}> because"
  855. " the directory <{path}>"
  856. " already exists."
  857. ).format(**locals())
  858. else:
  859. return _(
  860. "Unable to create new location in"
  861. " the directory <{path}>"
  862. " for an unknown reason."
  863. ).format(**locals())
  864. def set_mapset(
  865. gisrc,
  866. arg=None,
  867. geofile=None,
  868. create_new=False,
  869. tmp_location=False,
  870. tmp_mapset=False,
  871. tmpdir=None,
  872. ):
  873. """Selected Location and Mapset are checked and created if requested
  874. The gisrc (GRASS environment file) is written at the end
  875. (nothing is returned).
  876. tmp_location requires tmpdir (which is used as gisdbase)
  877. """
  878. from grass.grassdb.checks import (
  879. is_mapset_valid,
  880. is_location_valid,
  881. get_mapset_invalid_reason,
  882. get_location_invalid_reason,
  883. get_location_invalid_suggestion,
  884. mapset_exists,
  885. )
  886. # TODO: arg param seems to be always the mapset parameter (or a dash
  887. # in a distant past), refactor
  888. if arg:
  889. # TODO: the block below could be just one line: os.path.abspath(l)
  890. # abspath both resolves relative paths and normalizes the path
  891. # so that trailing / is stripped away and split then always returns
  892. # non-empty element as the last element (which is good for both mapset
  893. # and location split)
  894. if arg == ".":
  895. arg = os.getcwd()
  896. elif not os.path.isabs(arg):
  897. arg = os.path.abspath(arg)
  898. if arg.endswith(os.path.sep):
  899. arg = arg.rstrip(os.path.sep)
  900. # now we can get the last element by split on the first go
  901. # and it works for the last element being mapset or location
  902. if tmp_mapset:
  903. # We generate a random name and then create the mapset as usual.
  904. mapset = "tmp_" + uuid.uuid4().hex
  905. create_new = True
  906. else:
  907. arg, mapset = os.path.split(arg)
  908. arg, location_name = os.path.split(arg)
  909. gisdbase = arg
  910. # all was None for tmp loc so that case goes here quickly
  911. # TODO: but the above code needs review anyway
  912. if tmp_location:
  913. # set gisdbase to temporary directory
  914. gisdbase = tmpdir
  915. # we are already in a unique directory, so we can use fixed name
  916. location_name = "tmploc"
  917. # we need only one mapset
  918. mapset = "PERMANENT"
  919. debug(
  920. "Using temporary location <{gdb}{sep}{lc}>".format(
  921. gdb=gisdbase, lc=location_name, sep=os.path.sep
  922. )
  923. )
  924. if gisdbase and location_name and mapset:
  925. path = os.path.join(gisdbase, location_name, mapset)
  926. # check if 'path' is a valid GRASS location/mapset
  927. path_is_valid_mapset = is_mapset_valid(path)
  928. if path_is_valid_mapset and tmp_mapset:
  929. # If we would be creating the mapset directory at the same time as
  930. # generating the name, we could just try another name in case of
  931. # conflict. Conflict is unlikely, but it would be worth considering
  932. # it during refactoring of this code.
  933. fatal(
  934. _(
  935. "Mapset <{}> already exists."
  936. " Unable to create a new temporary mapset of that name."
  937. ).format(path)
  938. )
  939. elif path_is_valid_mapset and create_new:
  940. fatal(_("Mapset <{}> already exists.").format(path))
  941. if not path_is_valid_mapset:
  942. if not create_new:
  943. # 'path' is not a valid mapset and user does not
  944. # want to create anything new
  945. reason = get_mapset_invalid_reason(gisdbase, location_name, mapset)
  946. if not mapset_exists(gisdbase, location_name, mapset):
  947. suggestion = _("A new mapset can be created using '-c' flag.")
  948. else:
  949. suggestion = _("Maybe you meant a different directory.")
  950. fatal("{reason}\n{suggestion}".format(**locals()))
  951. else:
  952. # 'path' is not valid and the user wants to create
  953. # mapset on the fly
  954. # check if 'location_name' is a valid GRASS location
  955. if not is_location_valid(gisdbase, location_name):
  956. if not (tmp_location or tmp_mapset):
  957. # 'location_name' is not a valid GRASS location
  958. # and user requested its creation, so we parsed
  959. # the path wrong and need to move one level
  960. # and use 'PERMANENT' mapset
  961. # (we already got that right in case of tmploc)
  962. gisdbase = os.path.join(gisdbase, location_name)
  963. location_name = mapset
  964. mapset = "PERMANENT"
  965. if tmp_mapset:
  966. suggestion = get_location_invalid_suggestion(
  967. gisdbase, location_name
  968. )
  969. reason = get_location_invalid_reason(gisdbase, location_name)
  970. if suggestion:
  971. fatal("{reason}\n{suggestion}".format(**locals()))
  972. else:
  973. fatal(reason)
  974. if not can_create_location(gisdbase, location_name):
  975. fatal(cannot_create_location_reason(gisdbase, location_name))
  976. # create new location based on the provided EPSG/...
  977. if not geofile:
  978. fatal(_("Provide CRS to create a location"))
  979. message(
  980. _("Creating new GRASS GIS location <{}>...").format(
  981. location_name
  982. )
  983. )
  984. create_location(gisdbase, location_name, geofile)
  985. else:
  986. # 'location_name' is a valid GRASS location,
  987. # create new mapset
  988. if os.path.isfile(path):
  989. # not a valid mapset, but dir exists, assuming
  990. # broken/incomplete mapset
  991. fatal(
  992. _(
  993. "Unable to create new mapset <{mapset}>"
  994. " because <{path}> is a file."
  995. ).format(mapset=mapset, path=path)
  996. )
  997. elif os.path.isdir(path):
  998. # not a valid mapset, but dir exists, assuming
  999. # broken/incomplete mapset
  1000. warning(
  1001. _(
  1002. "The mapset <{}> is missing the WIND file"
  1003. " (computational region). It will be"
  1004. " fixed now. Note that this warning"
  1005. " may become an error in future versions."
  1006. ).format(mapset)
  1007. )
  1008. else:
  1009. if geofile:
  1010. fatal(
  1011. _(
  1012. "No CRS is needed for creating mapset."
  1013. " Did you mean to create a new location?"
  1014. )
  1015. )
  1016. message(
  1017. _("Creating new GRASS GIS mapset <{}>...").format(mapset)
  1018. )
  1019. # create mapset directory
  1020. os.mkdir(path)
  1021. if tmp_mapset:
  1022. # The tmp location is handled by (re-)using the
  1023. # tmpdir, but we need to take care of the tmp
  1024. # mapset which is only a subtree in an existing
  1025. # location. We simply remove the tree at exit.
  1026. # All mapset cleaning functions should succeed
  1027. # because they are called before exit or registered
  1028. # only later (and thus called before this one).
  1029. # (Theoretically, they could be disabled if that's
  1030. # just cleaning a files in the mapset directory.)
  1031. atexit.register(
  1032. lambda: shutil.rmtree(path, ignore_errors=True)
  1033. )
  1034. # make directory a mapset, add the region
  1035. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  1036. s = readfile(
  1037. os.path.join(
  1038. gisdbase, location_name, "PERMANENT", "DEFAULT_WIND"
  1039. )
  1040. )
  1041. writefile(os.path.join(path, "WIND"), s)
  1042. add_mapset_to_gisrc(gisrc, gisdbase, location_name, mapset)
  1043. else:
  1044. fatal(
  1045. _(
  1046. "GRASS GIS database directory, location and mapset"
  1047. " not set properly."
  1048. " Use GUI or command line to set them."
  1049. )
  1050. )
  1051. # we don't follow the LOCATION_NAME legacy naming here but we have to still
  1052. # translate to it, so always double check
  1053. class MapsetSettings(object):
  1054. """Holds GRASS GIS database directory, Location and Mapset
  1055. Provides few convenient functions.
  1056. """
  1057. def __init__(self):
  1058. self.gisdbase = None
  1059. self.location = None
  1060. self.mapset = None
  1061. self._full_mapset = None
  1062. # TODO: perhaps full_mapset would be better as mapset_path
  1063. # TODO: works only when set for the first time
  1064. # this follows the current usage but we must invalidate when
  1065. # the others are changed (use properties for that)
  1066. @property
  1067. def full_mapset(self):
  1068. if self._full_mapset is None:
  1069. self._full_mapset = os.path.join(self.gisdbase, self.location, self.mapset)
  1070. return self._full_mapset
  1071. # TODO: perhaps conversion to bool would be nicer
  1072. def is_valid(self):
  1073. return self.gisdbase and self.location and self.mapset
  1074. def get_mapset_settings(gisrc):
  1075. """Get the settings of Location and Mapset from the gisrc file"""
  1076. mapset_settings = MapsetSettings()
  1077. kv = read_gisrc(gisrc)
  1078. mapset_settings.gisdbase = kv.get("GISDBASE")
  1079. mapset_settings.location = kv.get("LOCATION_NAME")
  1080. mapset_settings.mapset = kv.get("MAPSET")
  1081. if not mapset_settings.is_valid():
  1082. return None
  1083. return mapset_settings
  1084. # TODO: does it really makes sense to tell user about gisrcrc?
  1085. # anything could have happened in between loading from gisrcrc and now
  1086. # (we do e.g. GUI or creating loctation)
  1087. def load_gisrc(gisrc, gisrcrc):
  1088. """Get the settings of Location and Mapset from the gisrc file
  1089. :returns: MapsetSettings object
  1090. """
  1091. mapset_settings = get_mapset_settings(gisrc)
  1092. if not mapset_settings:
  1093. fatal(
  1094. _(
  1095. "Error reading data path information from g.gisenv.\n"
  1096. "GISDBASE={gisdbase}\n"
  1097. "LOCATION_NAME={location}\n"
  1098. "MAPSET={mapset}\n\n"
  1099. "Check the <{file}> file."
  1100. ).format(
  1101. gisdbase=mapset_settings.gisdbase,
  1102. location=mapset_settings.location,
  1103. mapset=mapset_settings.mapset,
  1104. file=gisrcrc,
  1105. )
  1106. )
  1107. return mapset_settings
  1108. # load environmental variables from grass_env_file
  1109. def load_env(grass_env_file):
  1110. if not os.access(grass_env_file, os.R_OK):
  1111. return
  1112. # Regular expression for lines starting with "export var=val" (^export
  1113. # lines below). Environment variables should start with a-zA-Z or _.
  1114. # \1 and \2 are a variable name and its value, respectively.
  1115. export_re = re.compile("^export[ \t]+([a-zA-Z_]+[a-zA-Z0-9_]*)=(.*?)[ \t]*$")
  1116. for line in readfile(grass_env_file).splitlines():
  1117. # match ^export lines
  1118. m = export_re.match(line)
  1119. # if not ^export lines, skip
  1120. if not m:
  1121. continue
  1122. # k is the variable name and v is its value
  1123. k = m.group(1)
  1124. v = m.group(2)
  1125. # let's try to expand any $var's in v
  1126. expand = True
  1127. if v.startswith("'") and v.endswith("'"):
  1128. # we're parsing
  1129. # export var='value'
  1130. # and need to strip out starting and ending quotes from the value
  1131. v = v.strip("'")
  1132. # we don't want to expand any $var's inside 'value' because they
  1133. # are within single quotes
  1134. expand = False
  1135. elif v.startswith('"') and v.endswith('"'):
  1136. # in this case, we're parsing
  1137. # export var="value"
  1138. # and again need to strip out starting and ending quotes from the
  1139. # value
  1140. v = v.strip('"')
  1141. # we'll keep expand=True to expand $var's inside "value" because
  1142. # they are within double quotes
  1143. elif (
  1144. v.startswith("'") or v.endswith("'") or v.startswith('"') or v.endswith('"')
  1145. ):
  1146. # here, let's try to ignore unmatching single/double quotes, which
  1147. # might be a multi-line variable or just a user error
  1148. debug("Ignoring multi-line environmental variable {0}".format(k))
  1149. continue
  1150. if expand:
  1151. # finally, expand $var's within a non-single quoted value
  1152. v = os.path.expanduser(
  1153. os.path.expandvars(v.replace("\\$", "\0")).replace("\0", "$")
  1154. )
  1155. debug("Environmental variable set {0}={1}".format(k, v))
  1156. # create a new environment variable
  1157. os.environ[k] = v
  1158. # Allow for mixed ISIS-GRASS Environment
  1159. if os.getenv("ISISROOT"):
  1160. isis = os.getenv("ISISROOT")
  1161. os.environ["ISIS_LIB"] = isis + os.sep + "lib"
  1162. os.environ["ISIS_3RDPARTY"] = isis + os.sep + "3rdParty" + os.sep + "lib"
  1163. os.environ["QT_PLUGIN_PATH"] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  1164. # os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  1165. libpath = os.getenv("LD_LIBRARY_PATH", "")
  1166. isislibpath = os.getenv("ISIS_LIB")
  1167. isis3rdparty = os.getenv("ISIS_3RDPARTY")
  1168. os.environ["LD_LIBRARY_PATH"] = (
  1169. libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  1170. )
  1171. def install_notranslation():
  1172. # If locale is not supported, _ function might be missing
  1173. # This function just installs _ as a pass-through function
  1174. # See trac #3875 for details
  1175. import builtins
  1176. builtins.__dict__["_"] = lambda x: x
  1177. def set_language(grass_config_dir):
  1178. # This function is used to override system default language and locale
  1179. # Such override can be requested only from wxGUI
  1180. # An override if user has provided correct environmental variables as
  1181. # LC_MESSAGES or LANG is not necessary.
  1182. # Unfortunately currently a working solution for Windows is lacking
  1183. # thus it always on Vista and XP will print an error.
  1184. # See discussion for Windows not following its own documentation and
  1185. # not accepting ISO codes as valid locale identifiers
  1186. # http://bugs.python.org/issue10466
  1187. # As this code relies heavily on various locale calls, it is necessary
  1188. # to track related python changes:
  1189. # https://bugs.python.org/issue43557
  1190. encoding = None
  1191. # Override value is stored in wxGUI preferences file.
  1192. try:
  1193. with open(os.path.join(grass_config_dir, "wx.json"), "r") as json_file:
  1194. try:
  1195. language = json.load(json_file)["language"]["locale"]["lc_all"]
  1196. except KeyError:
  1197. language = None
  1198. except FileNotFoundError:
  1199. language = None
  1200. # Backwards compatibility with old wx preferences files
  1201. if language == "C":
  1202. language = "en"
  1203. if not language:
  1204. # Language override is disabled (system language specified)
  1205. # As by default program runs with C locale, but users expect to
  1206. # have their default locale, we'll just set default locale
  1207. try:
  1208. locale.setlocale(locale.LC_ALL, "")
  1209. except locale.Error as e:
  1210. # If we get here, system locale settings are terribly wrong
  1211. # There is no point to continue as GRASS/Python will fail
  1212. # in some other unpredictable way.
  1213. sys.stderr.write(
  1214. "System locale is not usable (LC_ALL variable not defined)."
  1215. " Most likely it indicates misconfigured environment.\n"
  1216. )
  1217. sys.stderr.write("Reported error message: %s\n" % e)
  1218. # it would be too drastic to exit
  1219. # sys.exit("Fix system locale settings and then try again.")
  1220. locale.setlocale(locale.LC_ALL, "C")
  1221. sys.stderr.write(
  1222. "Default locale settings are missing. GRASS running with C locale.\n"
  1223. )
  1224. language, encoding = locale.getdefaultlocale()
  1225. if not language:
  1226. sys.stderr.write(
  1227. "Default locale settings are missing. GRASS running with C locale.\n"
  1228. )
  1229. install_notranslation()
  1230. return
  1231. else:
  1232. debug(
  1233. "A language override has been requested."
  1234. " Trying to switch GRASS into '%s'..." % language
  1235. )
  1236. try:
  1237. locale.setlocale(locale.LC_ALL, language)
  1238. except locale.Error:
  1239. try:
  1240. # Locale lang.encoding might be missing. Let's try
  1241. # UTF-8 encoding before giving up as on Linux systems
  1242. # lang.UTF-8 locales are more common than legacy
  1243. # ISO-8859 ones.
  1244. encoding = "UTF-8"
  1245. normalized = locale.normalize("%s.%s" % (language, encoding))
  1246. locale.setlocale(locale.LC_ALL, normalized)
  1247. except locale.Error as e:
  1248. if language == "en":
  1249. # A workaround for Python Issue30755
  1250. # https://bugs.python.org/issue30755
  1251. if locale.normalize("C.UTF-8") == "en_US.UTF-8":
  1252. locale.setlocale(locale.LC_ALL, "C")
  1253. os.environ["LANGUAGE"] = "C"
  1254. os.environ["LANG"] = "C"
  1255. os.environ["LC_MESSAGES"] = "C"
  1256. os.environ["LC_NUMERIC"] = "C"
  1257. os.environ["LC_TIME"] = "C"
  1258. sys.stderr.write(
  1259. "To avoid Unicode errors in GUI, install"
  1260. " en_US.UTF-8 locale and restart GRASS.\n"
  1261. "Also consider upgrading your Python version"
  1262. " to one containing fix for Python Issue 30755.\n"
  1263. )
  1264. install_notranslation()
  1265. return
  1266. # en_US locale might be missing, still all messages in
  1267. # GRASS are already in en_US language.
  1268. # Using plain C as locale forces encodings to ascii
  1269. # thus lets try our luck with C.UTF-8 first.
  1270. # See bugs #3441 and #3423
  1271. try:
  1272. locale.setlocale(locale.LC_ALL, "C.UTF-8")
  1273. except locale.Error as e:
  1274. # All lost. Setting to C as much as possible.
  1275. # We can not call locale.normalize on C as it
  1276. # will transform it to en_US and we already know
  1277. # it doesn't work.
  1278. locale.setlocale(locale.LC_ALL, "C")
  1279. os.environ["LANGUAGE"] = "C"
  1280. os.environ["LANG"] = "C"
  1281. os.environ["LC_MESSAGES"] = "C"
  1282. os.environ["LC_NUMERIC"] = "C"
  1283. os.environ["LC_TIME"] = "C"
  1284. gettext.install("grasslibs", gpath("locale"))
  1285. sys.stderr.write(
  1286. "All attempts to enable English language have"
  1287. " failed. GRASS running with C locale.\n"
  1288. "If you observe UnicodeError in Python,"
  1289. " install en_US.UTF-8"
  1290. " locale and restart GRASS.\n"
  1291. )
  1292. install_notranslation()
  1293. return
  1294. else:
  1295. # The last attempt...
  1296. try:
  1297. encoding = locale.getpreferredencoding()
  1298. normalized = locale.normalize("%s.%s" % (language, encoding))
  1299. locale.setlocale(locale.LC_ALL, normalized)
  1300. except locale.Error as e:
  1301. # If we got so far, attempts to set up language and locale have
  1302. # failed on this system.
  1303. sys.stderr.write(
  1304. "Failed to enforce user specified language '%s' with error: '%s'\n"
  1305. % (language, e)
  1306. )
  1307. sys.stderr.write(
  1308. "A LANGUAGE environmental variable has been set.\n"
  1309. "Part of messages will be displayed in"
  1310. " the requested language.\n"
  1311. )
  1312. # Even if setting locale will fail, let's set LANG in a hope,
  1313. # that UI will use it GRASS texts will be in selected language,
  1314. # system messages (i.e. OK, Cancel etc.) - in system default
  1315. # language
  1316. os.environ["LANGUAGE"] = language
  1317. os.environ["LANG"] = language
  1318. install_notranslation()
  1319. return
  1320. # Set up environment for subprocesses
  1321. os.environ["LANGUAGE"] = language
  1322. os.environ["LANG"] = language
  1323. if WINDOWS and (language == "ko" or (language == "ko_KR" and encoding == "cp949")):
  1324. # The default encoding for the Korean language in Windows is cp949,
  1325. # Microsoft's proprietary extension to euc-kr, but gettext prints no
  1326. # translated messages at all in the Command Prompt window if LC_CTYPE
  1327. # is set to ko_KR.cp949. Here, force LC_CTYPE to be euc-kr.
  1328. normalized = "euc-kr"
  1329. encoding = None
  1330. # XXX: In UN*X, LC_CTYPE needs to be set to *any* value before GRASS
  1331. # starts when the language setting is overriden by the user. For
  1332. # example, 'LC_CTYPE= grass' will break the welcome message.
  1333. # Interestingly, modules' help messages look fine.
  1334. elif encoding:
  1335. normalized = locale.normalize("%s.%s" % (language, encoding))
  1336. else:
  1337. normalized = language
  1338. for lc in (
  1339. "LC_CTYPE",
  1340. "LC_MESSAGES",
  1341. "LC_TIME",
  1342. "LC_COLLATE",
  1343. "LC_MONETARY",
  1344. "LC_PAPER",
  1345. "LC_NAME",
  1346. "LC_ADDRESS",
  1347. "LC_TELEPHONE",
  1348. "LC_MEASUREMENT",
  1349. "LC_IDENTIFICATION",
  1350. ):
  1351. os.environ[lc] = normalized
  1352. # Some code in GRASS might not like other decimal separators than .
  1353. # Other potential sources for problems are: LC_TIME LC_CTYPE
  1354. locale.setlocale(locale.LC_NUMERIC, "C")
  1355. os.environ["LC_NUMERIC"] = "C"
  1356. if os.getenv("LC_ALL"):
  1357. del os.environ["LC_ALL"] # Remove LC_ALL to not override LC_NUMERIC
  1358. # From now on enforce the new language
  1359. if encoding:
  1360. gettext.install("grasslibs", gpath("locale"), codeset=encoding)
  1361. else:
  1362. gettext.install("grasslibs", gpath("locale"))
  1363. def lock_mapset(mapset_path, force_gislock_removal, user):
  1364. """Lock the mapset and return name of the lock file
  1365. Behavior on error must be changed somehow; now it fatals but GUI case is
  1366. unresolved.
  1367. """
  1368. if not os.path.exists(mapset_path):
  1369. fatal(_("Path '%s' doesn't exist") % mapset_path)
  1370. if not os.access(mapset_path, os.W_OK):
  1371. error = _("Path '%s' not accessible.") % mapset_path
  1372. stat_info = os.stat(mapset_path)
  1373. mapset_uid = stat_info.st_uid
  1374. if mapset_uid != os.getuid():
  1375. # GTC %s is mapset's folder path
  1376. error = "%s\n%s" % (
  1377. error,
  1378. _("You are not the owner of '%s'.") % mapset_path,
  1379. )
  1380. fatal(error)
  1381. # Check for concurrent use
  1382. lockfile = os.path.join(mapset_path, ".gislock")
  1383. ret = call([gpath("etc", "lock"), lockfile, "%d" % os.getpid()])
  1384. msg = None
  1385. if ret == 2:
  1386. if not force_gislock_removal:
  1387. msg = _(
  1388. "%(user)s is currently running GRASS in selected mapset"
  1389. " (file %(file)s found). Concurrent use not allowed.\n"
  1390. "You can force launching GRASS using -f flag"
  1391. " (note that you need permission for this operation)."
  1392. " Have another look in the processor "
  1393. "manager just to be sure..." % {"user": user, "file": lockfile}
  1394. )
  1395. else:
  1396. try_remove(lockfile)
  1397. message(
  1398. _(
  1399. "%(user)s is currently running GRASS in selected mapset"
  1400. " (file %(file)s found). Forcing to launch GRASS..."
  1401. % {"user": user, "file": lockfile}
  1402. )
  1403. )
  1404. elif ret != 0:
  1405. msg = (
  1406. _("Unable to properly access '%s'.\n" "Please notify system personnel.")
  1407. % lockfile
  1408. )
  1409. if msg:
  1410. raise Exception(msg)
  1411. debug(
  1412. "Mapset <{mapset}> locked using '{lockfile}'".format(
  1413. mapset=mapset_path, lockfile=lockfile
  1414. )
  1415. )
  1416. return lockfile
  1417. # TODO: the gisrcrc here does not make sense, remove it from load_gisrc
  1418. def unlock_gisrc_mapset(gisrc, gisrcrc):
  1419. """Unlock mapset from the gisrc file"""
  1420. settings = load_gisrc(gisrc, gisrcrc)
  1421. lockfile = os.path.join(settings.full_mapset, ".gislock")
  1422. # this fails silently, perhaps a warning would be helpful to
  1423. # catch cases when removal was not possible due to e.g. another
  1424. # session force-removing the file (unlocking the mapset)
  1425. try_remove(lockfile)
  1426. def make_fontcap():
  1427. # TODO: is GRASS_FONT_CAP ever defined? It seems it must be defined in system
  1428. fc = os.getenv("GRASS_FONT_CAP")
  1429. if fc and not os.access(fc, os.R_OK):
  1430. message(_("Building user fontcap..."))
  1431. call(["g.mkfontcap"])
  1432. def ensure_db_connected(mapset):
  1433. """Predefine default driver if DB connection not defined
  1434. :param mapset: full path to the mapset
  1435. """
  1436. if not os.access(os.path.join(mapset, "VAR"), os.F_OK):
  1437. call(["db.connect", "-c", "--quiet"])
  1438. def get_shell():
  1439. # set SHELL on ms windowns
  1440. # this was at the very beginning of the script but it can be anywhere
  1441. if WINDOWS:
  1442. if os.getenv("GRASS_SH"):
  1443. os.environ["SHELL"] = os.getenv("GRASS_SH")
  1444. if not os.getenv("SHELL"):
  1445. os.environ["SHELL"] = os.getenv("COMSPEC", "cmd.exe")
  1446. # cygwin has many problems with the shell setup
  1447. # below, so i hardcoded everything here.
  1448. if CYGWIN:
  1449. sh = "CYGWIN"
  1450. shellname = "GNU Bash (Cygwin)"
  1451. os.environ["SHELL"] = "/usr/bin/bash.exe"
  1452. os.environ["OSTYPE"] = "cygwin"
  1453. else:
  1454. # In a Docker container the 'SHELL' variable may not be set
  1455. # unless 'ENV SHELL /bin/bash' is set in Dockerfile. However, often Bash
  1456. # is available, so we try Bash first and fall back to sh if needed.
  1457. sh = os.getenv("SHELL")
  1458. if sh:
  1459. sh = os.path.basename(sh)
  1460. else:
  1461. # If SHELL is not set, see if there is Bash and use it.
  1462. if shutil.which("bash"):
  1463. sh = "bash"
  1464. else:
  1465. # Fallback to sh if there is no Bash on path.
  1466. sh = "sh"
  1467. # Ensure the variable is set.
  1468. os.environ["SHELL"] = sh
  1469. if WINDOWS and sh:
  1470. sh = os.path.splitext(sh)[0]
  1471. if sh == "ksh":
  1472. shellname = "Korn Shell"
  1473. elif sh == "csh":
  1474. shellname = "C Shell"
  1475. elif sh == "tcsh":
  1476. shellname = "TC Shell"
  1477. elif sh == "bash":
  1478. shellname = "Bash Shell"
  1479. elif sh == "sh":
  1480. shellname = "Bourne Shell"
  1481. elif sh == "zsh":
  1482. shellname = "Z Shell"
  1483. elif sh == "cmd":
  1484. shellname = "Command Prompt"
  1485. elif sh == "powershell":
  1486. shellname = "Windows PowerShell"
  1487. else:
  1488. shellname = "shell"
  1489. # check for SHELL
  1490. if not os.getenv("SHELL"):
  1491. fatal(_("The SHELL variable is not set"))
  1492. return sh, shellname
  1493. def get_grass_env_file(sh, grass_config_dir):
  1494. """Get name of the shell-specific GRASS environment (rc) file"""
  1495. if sh in ["csh", "tcsh"]:
  1496. grass_env_file = os.path.join(grass_config_dir, "cshrc")
  1497. elif sh in ["bash", "msh", "cygwin", "sh"]:
  1498. grass_env_file = os.path.join(grass_config_dir, "bashrc")
  1499. elif sh == "zsh":
  1500. grass_env_file = os.path.join(grass_config_dir, "zshrc")
  1501. elif sh in ["cmd", "powershell"]:
  1502. grass_env_file = os.path.join(grass_config_dir, "env.bat")
  1503. else:
  1504. grass_env_file = os.path.join(grass_config_dir, "bashrc")
  1505. warning(
  1506. _("Unsupported shell <{sh}>: {env_file}").format(
  1507. sh=sh, env_file=grass_env_file
  1508. )
  1509. )
  1510. return grass_env_file
  1511. def run_batch_job(batch_job):
  1512. """Runs script, module or any command
  1513. If *batch_job* is a string (insecure) shell=True is used for execution.
  1514. :param batch_job: executable and parameters in a list or a string
  1515. """
  1516. batch_job_string = batch_job
  1517. if not isinstance(batch_job, six.string_types):
  1518. # for messages only
  1519. batch_job_string = " ".join(batch_job)
  1520. message(_("Executing <%s> ...") % batch_job_string)
  1521. def script_path(batch_job):
  1522. """Adjust script path
  1523. :param batch_job list: index 0, script path
  1524. :return str or None: script path or None
  1525. """
  1526. script_in_addon_path = None
  1527. if "GRASS_ADDON_BASE" in os.environ:
  1528. script_in_addon_path = os.path.join(
  1529. os.environ["GRASS_ADDON_BASE"],
  1530. "scripts",
  1531. batch_job[0],
  1532. )
  1533. if script_in_addon_path and os.path.exists(script_in_addon_path):
  1534. batch_job[0] = script_in_addon_path
  1535. return script_in_addon_path
  1536. elif os.path.exists(batch_job[0]):
  1537. return batch_job[0]
  1538. try:
  1539. script = script_path(batch_job)
  1540. proc = Popen(batch_job, shell=False, env=os.environ)
  1541. except OSError as error:
  1542. error_message = _("Execution of <{cmd}> failed:\n" "{error}").format(
  1543. cmd=batch_job_string,
  1544. error=error,
  1545. )
  1546. # No such file or directory
  1547. if error.errno == errno.ENOENT:
  1548. if script and os.access(batch_job[0], os.X_OK):
  1549. # Allow run py script with CRLF line terminators
  1550. proc = Popen([sys.executable] + batch_job, shell=False)
  1551. else:
  1552. fatal(error_message)
  1553. else:
  1554. fatal(error_message)
  1555. returncode = proc.wait()
  1556. message(_("Execution of <%s> finished.") % batch_job_string)
  1557. return returncode
  1558. def start_gui(grass_gui):
  1559. """Start specified GUI
  1560. :param grass_gui: GUI name (supported values: 'wxpython')
  1561. Returns the process for a supported GUI, None otherwise.
  1562. """
  1563. # Start the chosen GUI but ignore text
  1564. debug("GRASS GUI should be <%s>" % grass_gui)
  1565. # Check for gui interface
  1566. if grass_gui == "wxpython":
  1567. # TODO: report failures
  1568. return Popen([os.getenv("GRASS_PYTHON"), wxpath("wxgui.py")])
  1569. return None
  1570. def close_gui():
  1571. """Close GUI if running"""
  1572. if gpath("etc", "python") not in sys.path:
  1573. sys.path.append(gpath("etc", "python"))
  1574. from grass.script import core as gcore # pylint: disable=E0611
  1575. env = gcore.gisenv()
  1576. if "GUI_PID" not in env:
  1577. return
  1578. for pid in env["GUI_PID"].split(","):
  1579. debug("Exiting GUI with pid={0}".format(pid))
  1580. try:
  1581. os.kill(int(pid), signal.SIGTERM)
  1582. except OSError as e:
  1583. message(_("Unable to close GUI. {0}").format(e))
  1584. def show_banner():
  1585. """Write GRASS GIS ASCII name to stderr"""
  1586. sys.stderr.write(
  1587. r"""
  1588. __________ ___ __________ _______________
  1589. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  1590. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  1591. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  1592. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  1593. """
  1594. )
  1595. def say_hello():
  1596. """Write welcome to stderr including code revision if in git copy"""
  1597. sys.stderr.write(_("Welcome to GRASS GIS %s") % GRASS_VERSION)
  1598. if GRASS_VERSION.endswith("dev"):
  1599. try:
  1600. filerev = open(gpath("etc", "VERSIONNUMBER"))
  1601. linerev = filerev.readline().rstrip("\n")
  1602. filerev.close()
  1603. revision = linerev.split(" ")[1]
  1604. sys.stderr.write(" (" + revision + ")")
  1605. except:
  1606. pass
  1607. INFO_TEXT = r"""
  1608. %-41shttps://grass.osgeo.org
  1609. %-41s%s (%s)
  1610. %-41sg.manual -i
  1611. %-41sg.version -c
  1612. %-41sg.version -x
  1613. """
  1614. def show_info(shellname, grass_gui, default_gui):
  1615. """Write basic info about GRASS GIS and GRASS session to stderr"""
  1616. sys.stderr.write(
  1617. f(
  1618. INFO_TEXT,
  1619. _("GRASS GIS homepage:"),
  1620. # GTC Running through: SHELL NAME
  1621. _("This version running through:"),
  1622. shellname,
  1623. os.getenv("SHELL"),
  1624. _("Help is available with the command:"),
  1625. _("See the licence terms with:"),
  1626. _("See citation options with:"),
  1627. )
  1628. )
  1629. if grass_gui == "wxpython":
  1630. message(f("%-41sg.gui wxpython", _("If required, restart the GUI with:")))
  1631. else:
  1632. message(f("%-41sg.gui %s", _("Start the GUI with:"), default_gui))
  1633. message(f("%-41sexit", _("When ready to quit enter:")))
  1634. message("")
  1635. def start_shell():
  1636. if WINDOWS:
  1637. # "$ETC/run" doesn't work at all???
  1638. process = subprocess.Popen([os.getenv("SHELL")])
  1639. else:
  1640. process = Popen([gpath("etc", "run"), os.getenv("SHELL")])
  1641. return process
  1642. def csh_startup(location, grass_env_file):
  1643. userhome = os.getenv("HOME") # save original home
  1644. home = location
  1645. os.environ["HOME"] = home
  1646. cshrc = os.path.join(home, ".cshrc")
  1647. tcshrc = os.path.join(home, ".tcshrc")
  1648. try_remove(cshrc)
  1649. try_remove(tcshrc)
  1650. f = open(cshrc, "w")
  1651. f.write("set home = %s\n" % userhome)
  1652. f.write("set history = 10000000 savehist = (10000000 merge) noclobber ignoreeof\n")
  1653. f.write("set histfile = %s\n" % os.path.join(os.getenv("HOME"), ".history"))
  1654. f.write("alias _location g.gisenv get=LOCATION_NAME\n")
  1655. f.write("alias _mapset g.gisenv get=MAPSET\n")
  1656. f.write("alias precmd 'echo \"Mapset <`_mapset`> in Location <`_location`>\"'\n")
  1657. f.write('set prompt="GRASS > "\n')
  1658. # csh shell rc file left for backward compatibility
  1659. path = os.path.join(userhome, ".grass.cshrc")
  1660. if os.access(path, os.R_OK):
  1661. f.write(readfile(path) + "\n")
  1662. if os.access(grass_env_file, os.R_OK):
  1663. f.write(readfile(grass_env_file) + "\n")
  1664. mail_re = re.compile(r"^ *set *mail *= *")
  1665. for filename in [".cshrc", ".tcshrc", ".login"]:
  1666. path = os.path.join(userhome, filename)
  1667. if os.access(path, os.R_OK):
  1668. s = readfile(path)
  1669. lines = s.splitlines()
  1670. for line in lines:
  1671. if mail_re.match(line):
  1672. f.write(line)
  1673. path = os.getenv("PATH").split(":")
  1674. f.write("set path = ( %s ) \n" % " ".join(path))
  1675. f.close()
  1676. writefile(tcshrc, readfile(cshrc))
  1677. process = start_shell()
  1678. os.environ["HOME"] = userhome
  1679. return process
  1680. def sh_like_startup(location, location_name, grass_env_file, sh):
  1681. """Start Bash or Z shell (but not sh (Bourne Shell))"""
  1682. if sh == "bash":
  1683. # set bash history to record an unlimited command history
  1684. sh_history_limit = "" # unlimited
  1685. os.environ["HISTSIZE"] = sh_history_limit
  1686. os.environ["HISTFILESIZE"] = sh_history_limit
  1687. sh_history = ".bash_history"
  1688. shrc = ".bashrc"
  1689. grass_shrc = ".grass.bashrc"
  1690. elif sh == "zsh":
  1691. # zsh does not have an unlimited history setting, so 1e8 is set as a proxy
  1692. sh_history_limit = "100000000" # proxy for unlimited
  1693. os.environ["SAVEHIST"] = sh_history_limit
  1694. os.environ["HISTSIZE"] = sh_history_limit
  1695. sh_history = ".zsh_history"
  1696. shrc = ".zshrc"
  1697. grass_shrc = ".grass.zshrc"
  1698. else:
  1699. raise ValueError(
  1700. "Only bash-like and zsh shells are supported by sh_like_startup()"
  1701. )
  1702. # save command history in mapset dir and remember more
  1703. # bash histroy file handled in specific_addition
  1704. if not sh == "bash":
  1705. os.environ["HISTFILE"] = os.path.join(location, sh_history)
  1706. # instead of changing $HOME, start bash with:
  1707. # --rcfile "$LOCATION/.bashrc" ?
  1708. # if so, must care be taken to explicitly call .grass.bashrc et al
  1709. # for non-interactive bash batch jobs?
  1710. userhome = os.getenv("HOME") # save original home
  1711. home = location # save .bashrc in $LOCATION
  1712. os.environ["HOME"] = home
  1713. shell_rc_file = os.path.join(home, shrc)
  1714. try_remove(shell_rc_file)
  1715. f = open(shell_rc_file, "w")
  1716. if sh == "zsh":
  1717. f.write("test -r {home}/.alias && source {home}/.alias\n".format(home=userhome))
  1718. else:
  1719. f.write("test -r ~/.alias && . ~/.alias\n")
  1720. if os.getenv("ISISROOT"):
  1721. # GRASS GIS and ISIS blend
  1722. grass_name = "ISIS-GRASS"
  1723. else:
  1724. grass_name = "GRASS"
  1725. if sh == "zsh":
  1726. f.write("setopt PROMPT_SUBST\n")
  1727. f.write("PS1='{name} : %1~ > '\n".format(name=grass_name))
  1728. else:
  1729. f.write(
  1730. "PS1='{name} {db_place}:\\W > '\n".format(
  1731. name=grass_name, db_place="$_GRASS_DB_PLACE"
  1732. )
  1733. )
  1734. # TODO: have a function and/or module to test this
  1735. mask2d_test = 'test -f "$MAPSET_PATH/cell/MASK"'
  1736. mask3d_test = 'test -d "$MAPSET_PATH/grid3/RASTER3D_MASK"'
  1737. specific_addition = ""
  1738. if sh == "zsh":
  1739. specific_addition = """
  1740. local z_lo=`g.gisenv get=LOCATION_NAME`
  1741. local z_ms=`g.gisenv get=MAPSET`
  1742. ZLOC="Mapset <$z_ms> in <$z_lo>"
  1743. if [ "$_grass_old_mapset" != "$MAPSET_PATH" ] ; then
  1744. fc -A -I
  1745. HISTFILE="$MAPSET_PATH/{sh_history}"
  1746. fc -R
  1747. _grass_old_mapset="$MAPSET_PATH"
  1748. fi
  1749. """.format(
  1750. sh_history=sh_history
  1751. )
  1752. elif sh == "bash":
  1753. # Append existing history to file ("flush").
  1754. # Clear the (in-memory) history.
  1755. # Change the file.
  1756. # Read history from that file.
  1757. specific_addition = """
  1758. if [ "$_grass_old_mapset" != "$MAPSET_PATH" ] ; then
  1759. history -a
  1760. history -c
  1761. HISTFILE="$MAPSET_PATH/{sh_history}"
  1762. history -r
  1763. _grass_old_mapset="$MAPSET_PATH"
  1764. fi
  1765. """.format(
  1766. sh_history=sh_history
  1767. )
  1768. # double curly brackets means single one for format function
  1769. # setting LOCATION for backwards compatibility
  1770. f.write(
  1771. """grass_prompt() {{
  1772. MAPSET_PATH="`g.gisenv get=GISDBASE,LOCATION_NAME,MAPSET separator='/'`"
  1773. _GRASS_DB_PLACE="`g.gisenv get=LOCATION_NAME,MAPSET separator='/'`"
  1774. {specific_addition}
  1775. if {mask2d_test} && {mask3d_test} ; then
  1776. echo "[{both_masks}]"
  1777. elif {mask2d_test} ; then
  1778. echo "[{mask2d}]"
  1779. elif {mask3d_test} ; then
  1780. echo "[{mask3d}]"
  1781. fi
  1782. }}
  1783. PROMPT_COMMAND=grass_prompt\n""".format(
  1784. both_masks=_("2D and 3D raster MASKs present"),
  1785. mask2d=_("Raster MASK present"),
  1786. mask3d=_("3D raster MASK present"),
  1787. mask2d_test=mask2d_test,
  1788. mask3d_test=mask3d_test,
  1789. specific_addition=specific_addition,
  1790. )
  1791. )
  1792. if sh == "zsh":
  1793. f.write('precmd() { eval "$PROMPT_COMMAND" }\n')
  1794. f.write("RPROMPT='${ZLOC}'\n")
  1795. # this line was moved here from below .grass.bashrc to allow ~ and $HOME in
  1796. # .grass.bashrc
  1797. f.write('export HOME="%s"\n' % userhome) # restore user home path
  1798. # read other settings (aliases, ...) since environmental variables
  1799. # have been already set by load_env(), see #3462
  1800. for env_file in [os.path.join(userhome, grass_shrc), grass_env_file]:
  1801. if not os.access(env_file, os.R_OK):
  1802. continue
  1803. for line in readfile(env_file).splitlines():
  1804. # Bug related to OS X "SIP", see
  1805. # https://trac.osgeo.org/grass/ticket/3462#comment:13
  1806. if MACOS or not line.startswith("export"):
  1807. f.write(line + "\n")
  1808. f.write('export PATH="%s"\n' % os.getenv("PATH"))
  1809. # fix trac issue #3009 https://trac.osgeo.org/grass/ticket/3009
  1810. # re: failure to "Quit GRASS" from GUI
  1811. f.write('trap "exit" TERM\n')
  1812. f.close()
  1813. process = start_shell()
  1814. os.environ["HOME"] = userhome
  1815. return process
  1816. def default_startup(location, location_name):
  1817. """Start shell making no assumptions about what is supported in PS1"""
  1818. os.environ["PS1"] = "GRASS > "
  1819. return start_shell()
  1820. def done_message():
  1821. # here was something for batch job but it was never called
  1822. message(_("Done."))
  1823. message("")
  1824. message(_("Goodbye from GRASS GIS"))
  1825. message("")
  1826. def clean_temp():
  1827. message(_("Cleaning up temporary files..."))
  1828. nul = open(os.devnull, "w")
  1829. call([gpath("etc", "clean_temp")], stdout=nul)
  1830. nul.close()
  1831. def clean_all():
  1832. from grass.script import setup as gsetup
  1833. # clean default sqlite db
  1834. gsetup.clean_default_db()
  1835. # remove leftover temp files
  1836. clean_temp()
  1837. # save 'last used' GISRC after removing variables which shouldn't
  1838. # be saved, e.g. d.mon related
  1839. clean_env()
  1840. def grep(pattern, lines):
  1841. """Search lines (list of strings) and return them when beginning matches.
  1842. >>> grep("a", ['abc', 'cab', 'sdr', 'aaa', 'sss'])
  1843. ['abc', 'aaa']
  1844. """
  1845. expr = re.compile(pattern)
  1846. return [elem for elem in lines if expr.match(elem)]
  1847. def io_is_interactive():
  1848. """Return True if running in an interactive terminal (TTY), False otherwise"""
  1849. return sys.stdin.isatty() and sys.stdout.isatty()
  1850. def print_params(params):
  1851. """Write compile flags and other configuration to stdout"""
  1852. if not params:
  1853. params = [
  1854. "arch",
  1855. "build",
  1856. "compiler",
  1857. "path",
  1858. "python_path",
  1859. "revision",
  1860. "version",
  1861. "date",
  1862. ]
  1863. # check if we are dealing with parameters which require dev files
  1864. dev_params = ["arch", "compiler", "build", "date"]
  1865. if any([param in dev_params for param in params]):
  1866. plat = gpath("include", "Make", "Platform.make")
  1867. if not os.path.exists(plat):
  1868. fatal(_("Please install the GRASS GIS development package"))
  1869. fileplat = open(plat)
  1870. # this is in fact require only for some, but prepare it anyway
  1871. linesplat = fileplat.readlines()
  1872. fileplat.close()
  1873. for arg in params:
  1874. if arg == "path":
  1875. sys.stdout.write("%s\n" % GISBASE)
  1876. elif arg in ["python_path", "python-path"]:
  1877. sys.stdout.write("%s\n" % gpath("etc", "python"))
  1878. elif arg == "arch":
  1879. val = grep("ARCH", linesplat)
  1880. sys.stdout.write("%s\n" % val[0].split("=")[1].strip())
  1881. elif arg == "build":
  1882. build = gpath("include", "grass", "confparms.h")
  1883. filebuild = open(build)
  1884. val = filebuild.readline()
  1885. filebuild.close()
  1886. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  1887. elif arg == "compiler":
  1888. val = grep("CC", linesplat)
  1889. sys.stdout.write("%s\n" % val[0].split("=")[1].strip())
  1890. elif arg == "revision":
  1891. sys.stdout.write("@GRASS_VERSION_GIT@\n")
  1892. elif arg == "svn_revision":
  1893. filerev = open(gpath("etc", "VERSIONNUMBER"))
  1894. linerev = filerev.readline().rstrip("\n")
  1895. filerev.close()
  1896. try:
  1897. revision = linerev.split(" ")[1]
  1898. sys.stdout.write("%s\n" % revision[1:])
  1899. except:
  1900. sys.stdout.write("No SVN revision defined\n")
  1901. elif arg == "version":
  1902. sys.stdout.write("%s\n" % GRASS_VERSION)
  1903. elif arg == "date":
  1904. date_str = "#define GRASS_HEADERS_DATE "
  1905. gdate = gpath("include", "grass", "version.h")
  1906. with open(gdate) as filegdate:
  1907. for line in filegdate.readlines():
  1908. if line.startswith(date_str):
  1909. sys.stdout.write(
  1910. "{}\n".format(
  1911. line.replace(date_str, "").lstrip()[1:-2]
  1912. ) # remove quotes
  1913. )
  1914. break
  1915. else:
  1916. message(_("Parameter <%s> not supported") % arg)
  1917. def get_username():
  1918. """Get name of the current user"""
  1919. if WINDOWS:
  1920. user = os.getenv("USERNAME")
  1921. if not user:
  1922. user = "user_name"
  1923. else:
  1924. user = os.getenv("USER")
  1925. if not user:
  1926. user = os.getenv("LOGNAME")
  1927. if not user:
  1928. try:
  1929. p = Popen(["whoami"], stdout=subprocess.PIPE)
  1930. s = p.stdout.read()
  1931. p.wait()
  1932. user = s.strip()
  1933. if type(user) is bytes:
  1934. user = decode(user)
  1935. except:
  1936. pass
  1937. if not user:
  1938. user = "user_%d" % os.getuid()
  1939. return user
  1940. class Parameters(object):
  1941. """Structure to hold standard part of command line parameters"""
  1942. # we don't need to define any methods
  1943. # pylint: disable=R0903
  1944. def __init__(self):
  1945. self.grass_gui = None
  1946. self.create_new = None
  1947. self.exit_grass = None
  1948. self.force_gislock_removal = None
  1949. self.mapset = None
  1950. self.geofile = None
  1951. self.tmp_location = False
  1952. self.tmp_mapset = False
  1953. self.batch_job = None
  1954. def add_mapset_arguments(parser, mapset_as_option):
  1955. if mapset_as_option:
  1956. parser.add_argument(
  1957. "-m", "--mapset", metavar="PATH", type=str, help=_("use mapset %(metavar)s")
  1958. )
  1959. parser.add_argument(
  1960. "--tmp-mapset",
  1961. metavar="PATH",
  1962. type=str,
  1963. help=_("use temporary mapset in location %(metavar)s"),
  1964. )
  1965. else:
  1966. parser.add_argument(
  1967. "mapset",
  1968. metavar="PATH",
  1969. type=str,
  1970. nargs="?",
  1971. help=_("path to mapset (or location if creating one)"),
  1972. )
  1973. parser.add_argument(
  1974. "--tmp-mapset", action="store_true", help=_("use temporary mapset")
  1975. )
  1976. parser.add_argument(
  1977. "--tmp-location",
  1978. metavar="CRS",
  1979. type=str,
  1980. help=_(
  1981. "use temporary location with %(metavar)s (EPSG, georeferenced file, ...)"
  1982. ),
  1983. )
  1984. parser.add_argument(
  1985. "-f",
  1986. "--force-remove-lock",
  1987. action="store_true",
  1988. help=_("remove lock if present"),
  1989. )
  1990. def update_params_with_mapset_arguments(params, args):
  1991. """Update location and mapset related parameters"""
  1992. if args.force_remove_lock:
  1993. params.force_gislock_removal = True
  1994. if args.tmp_location:
  1995. params.tmp_location = True
  1996. params.geofile = args.tmp_location
  1997. if args.tmp_mapset:
  1998. params.tmp_mapset = True
  1999. if args.mapset:
  2000. params.mapset = args.mapset
  2001. def classic_parser(argv, default_gui):
  2002. """Parse CLI similar to v7 but with argparse
  2003. --exec is handled before argparse is used.
  2004. Help requests are also handled separately.
  2005. Not only help but also version and config are handled in this function.
  2006. """
  2007. # Check if the user asked for help
  2008. # Checking also the less standard -help and help.
  2009. help_requests = ["help", "-h", "-help", "--help", "--h"]
  2010. if len(argv) == 2 and argv[1] in help_requests:
  2011. help_message(default_gui=default_gui)
  2012. sys.exit()
  2013. parser = argparse.ArgumentParser()
  2014. parser.add_argument("-v", "--version", action="store_true")
  2015. parser.add_argument("--text", action="store_true")
  2016. parser.add_argument("--gtext", action="store_true")
  2017. parser.add_argument("--gui", action="store_true")
  2018. # -c works as plain True when only mapset is being created.
  2019. # However, option with a value is hungry, so it eats the mapset path.
  2020. mapset_tag = "__create_mapset_placeholder__"
  2021. parser.add_argument(
  2022. "-c", metavar="CRS", nargs="?", type=str, dest="create", const=mapset_tag
  2023. )
  2024. parser.add_argument("-e", action="store_true", dest="exit")
  2025. parser.add_argument("--config", nargs="*")
  2026. add_mapset_arguments(parser, mapset_as_option=False)
  2027. parser.add_argument(
  2028. "--exec",
  2029. nargs=argparse.REMAINDER,
  2030. help=_("execute module or script (followed by executable with arguments)"),
  2031. )
  2032. parsed_args = parser.parse_args(args=argv[1:])
  2033. params = Parameters()
  2034. # Check if the --text flag was given
  2035. if parsed_args.text:
  2036. params.grass_gui = "text"
  2037. # Check if the --gtext flag was given
  2038. if parsed_args.gtext:
  2039. params.grass_gui = "gtext"
  2040. # Check if the --gui flag was given
  2041. if parsed_args.gui:
  2042. params.grass_gui = default_gui
  2043. # Check if the user wants to create a new mapset
  2044. if parsed_args.create:
  2045. params.create_new = True
  2046. if parsed_args.create != mapset_tag:
  2047. if parsed_args.mapset:
  2048. # A value here is request to create a location.
  2049. params.geofile = parsed_args.create
  2050. else:
  2051. # The loc/mapset path argument is optional, so it can get
  2052. # eaten by the option. So here we got it mixed up and the
  2053. # option value is actually the path, not CRS.
  2054. params.mapset = parsed_args.create
  2055. if parsed_args.exit:
  2056. params.exit_grass = True
  2057. if parsed_args.exec:
  2058. params.batch_job = parsed_args.exec
  2059. # Cases to execute immediatelly
  2060. if parsed_args.version:
  2061. message("GRASS GIS %s" % GRASS_VERSION)
  2062. message("\n" + readfile(gpath("etc", "license")))
  2063. sys.exit()
  2064. if parsed_args.config is not None:
  2065. # None if not provided, empty list if present without values.
  2066. print_params(parsed_args.config)
  2067. sys.exit()
  2068. update_params_with_mapset_arguments(params, parsed_args)
  2069. return params
  2070. def parse_cmdline(argv, default_gui):
  2071. """Parse command line parameters
  2072. Returns Parameters object used throughout the script.
  2073. """
  2074. params = classic_parser(argv, default_gui)
  2075. validate_cmdline(params)
  2076. return params
  2077. def validate_cmdline(params):
  2078. """Validate the cmdline params and exit if necessary."""
  2079. if params.exit_grass and not params.create_new:
  2080. fatal(_("Flag -e requires also flag -c"))
  2081. if params.create_new and not params.mapset:
  2082. fatal(_("Flag -c requires name of location or mapset"))
  2083. if params.tmp_location and params.tmp_mapset:
  2084. fatal(
  2085. _("Either --tmp-location or --tmp-mapset can be used, not both").format(
  2086. params.mapset
  2087. )
  2088. )
  2089. if params.tmp_location and not params.geofile:
  2090. fatal(
  2091. _(
  2092. "Coordinate reference system argument (e.g. EPSG)"
  2093. " is needed for --tmp-location"
  2094. )
  2095. )
  2096. if params.tmp_location and params.mapset:
  2097. fatal(
  2098. _(
  2099. "Only one argument (e.g. EPSG) is needed for"
  2100. " --tmp-location, mapset name <{}> provided"
  2101. ).format(params.mapset)
  2102. )
  2103. # For now, we allow, but not advertise/document, --tmp-location
  2104. # without --exec (usefulness to be evaluated).
  2105. def main():
  2106. """The main function which does the whole setup and run procedure
  2107. Only few things are set on the module level.
  2108. """
  2109. # Set language
  2110. # This has to be called before any _() function call!
  2111. # Subsequent functions are using _() calls and
  2112. # thus must be called only after Language has been set.
  2113. grass_config_dir = get_grass_config_dir()
  2114. set_language(grass_config_dir)
  2115. # Set default GUI
  2116. default_gui = "wxpython"
  2117. # explain what is happening in debug mode (visible only in debug mode)
  2118. debug(
  2119. "GRASS_DEBUG environmental variable is set. It is meant to be"
  2120. " an internal variable for debugging only this script.\n"
  2121. " Use 'g.gisenv set=\"DEBUG=[0-5]\"'"
  2122. " to turn GRASS GIS debug mode on if you wish to do so."
  2123. )
  2124. # Set GRASS version number for R interface etc
  2125. # (must be an env var for MS Windows)
  2126. os.environ["GRASS_VERSION"] = GRASS_VERSION
  2127. # Set the GIS_LOCK variable to current process id
  2128. gis_lock = str(os.getpid())
  2129. os.environ["GIS_LOCK"] = gis_lock
  2130. params = parse_cmdline(sys.argv, default_gui=default_gui)
  2131. grass_gui = params.grass_gui # put it to variable, it is used a lot
  2132. # A shell is activated when using TTY.
  2133. # Explicit --[g]text in command line, forces a shell to be activated.
  2134. force_shell = grass_gui in ["text", "gtext"]
  2135. use_shell = io_is_interactive() or force_shell
  2136. if not use_shell:
  2137. # If no shell is used, always use actual GUI as GUI, even when "text" is set as
  2138. # a GUI in the gisrcrc becasue otherwise there would be nothing for the user
  2139. # unless running in the batch mode. (The gisrcrc file is loaded later on in case
  2140. # nothing was provided in the command line).
  2141. grass_gui = default_gui
  2142. # TODO: with --tmp-location there is no point in loading settings
  2143. # i.e. rc file from home dir, but the code is too spread out
  2144. # to disable it at this point
  2145. gisrcrc = get_gisrc_from_config_dir(grass_config_dir, params.batch_job)
  2146. # Set the username
  2147. user = get_username()
  2148. # Set shell (needs to be called before load_env())
  2149. sh, shellname = get_shell()
  2150. grass_env_file = get_grass_env_file(sh, grass_config_dir)
  2151. # Load environmental variables from the file (needs to be called
  2152. # before create_tmp())
  2153. load_env(grass_env_file)
  2154. # Create the temporary directory and session grassrc file
  2155. tmpdir = create_tmp(user, gis_lock)
  2156. # Remove the tmpdir
  2157. # The removal will be executed when the python process terminates.
  2158. atexit.register(lambda: shutil.rmtree(tmpdir, ignore_errors=True))
  2159. # Create the session grassrc file
  2160. gisrc = create_gisrc(tmpdir, gisrcrc)
  2161. ensure_home()
  2162. # Set PATH, PYTHONPATH, ...
  2163. set_paths(grass_config_dir=grass_config_dir)
  2164. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  2165. set_defaults()
  2166. set_display_defaults()
  2167. # Set GRASS_HTML_BROWSER
  2168. set_browser()
  2169. # First time user - GISRC is defined in the GRASS script
  2170. if not os.access(gisrc, os.F_OK):
  2171. if grass_gui == "text" and not params.mapset:
  2172. fatal(
  2173. _(
  2174. "Unable to start GRASS GIS. You have the choice to:\n"
  2175. " - Launch the graphical user interface with"
  2176. " the '--gui' switch\n"
  2177. " {cmd_name} --gui\n"
  2178. " - Launch with path to "
  2179. "the location/mapset as an argument\n"
  2180. " {cmd_name} /path/to/location/mapset`\n"
  2181. " - Create a location with '-c' and launch in its"
  2182. " PERMANENT mapset\n"
  2183. " {cmd_name} -c EPSG:number /path/to/location\n"
  2184. " {cmd_name} -c geofile /path/to/location\n"
  2185. " - Create manually the GISRC file ({gisrcrc})\n"
  2186. " - Use '--help' for further options\n"
  2187. " {cmd_name} --help\n"
  2188. "See also: https://grass.osgeo.org/{cmd_name}/manuals/helptext.html"
  2189. ).format(cmd_name=CMD_NAME, gisrcrc=gisrcrc)
  2190. )
  2191. create_initial_gisrc(gisrc)
  2192. message(_("Starting GRASS GIS..."))
  2193. # Ensure GUI is set
  2194. if params.batch_job or params.exit_grass:
  2195. grass_gui = "text"
  2196. else:
  2197. if not grass_gui:
  2198. # if GUI was not set previously (e.g. command line),
  2199. # get it from rc file or env variable
  2200. grass_gui = read_gui(gisrc, default_gui)
  2201. # check that the GUI works but only if not doing a batch job
  2202. grass_gui = check_gui(expected_gui=grass_gui)
  2203. # save GUI only if we are not doibg batch job
  2204. save_gui(gisrc, grass_gui)
  2205. # Parsing argument to get LOCATION
  2206. # Mapset is not specified in command line arguments
  2207. if not params.mapset and not params.tmp_location:
  2208. # Get mapset parameters from gisrc file
  2209. mapset_settings = get_mapset_settings(gisrc)
  2210. last_mapset_path = mapset_settings.full_mapset
  2211. # Check if mapset from gisrc is usable
  2212. from grass.grassdb.checks import can_start_in_mapset
  2213. last_mapset_usable = can_start_in_mapset(
  2214. mapset_path=last_mapset_path,
  2215. ignore_lock=params.force_gislock_removal,
  2216. )
  2217. debug(f"last_mapset_usable: {last_mapset_usable}")
  2218. if not last_mapset_usable:
  2219. from grass.app import ensure_default_data_hierarchy
  2220. from grass.grassdb.checks import is_first_time_user
  2221. fallback_session = False
  2222. # Add last used mapset to gisrc
  2223. add_last_mapset_to_gisrc(gisrc, last_mapset_path)
  2224. if is_first_time_user():
  2225. # Ensure default data hierarchy
  2226. (
  2227. default_gisdbase,
  2228. default_location,
  2229. unused_default_mapset,
  2230. default_mapset_path,
  2231. ) = ensure_default_data_hierarchy()
  2232. if not default_gisdbase:
  2233. fatal(
  2234. _(
  2235. "Failed to start GRASS GIS, grassdata directory cannot"
  2236. " be found or created."
  2237. )
  2238. )
  2239. elif not default_location:
  2240. fatal(
  2241. _(
  2242. "Failed to start GRASS GIS, no default location to copy in"
  2243. " the installation or copying failed."
  2244. )
  2245. )
  2246. if can_start_in_mapset(
  2247. mapset_path=default_mapset_path, ignore_lock=False
  2248. ):
  2249. # Use the default location/mapset.
  2250. set_mapset(gisrc=gisrc, arg=default_mapset_path)
  2251. else:
  2252. fallback_session = True
  2253. add_last_mapset_to_gisrc(gisrc, default_mapset_path)
  2254. else:
  2255. fallback_session = True
  2256. if fallback_session:
  2257. if grass_gui == "text":
  2258. # Fallback in command line is just failing in a standard way.
  2259. set_mapset(gisrc=gisrc, arg=last_mapset_path)
  2260. else:
  2261. # Create fallback temporary session
  2262. create_fallback_session(gisrc, tmpdir)
  2263. params.tmp_location = True
  2264. else:
  2265. # Use the last used mapset.
  2266. set_mapset(gisrc=gisrc, arg=last_mapset_path)
  2267. else:
  2268. # Mapset was specified in command line parameters.
  2269. if params.tmp_location:
  2270. # tmp loc requires other things to be set as well
  2271. set_mapset(
  2272. gisrc=gisrc,
  2273. geofile=params.geofile,
  2274. create_new=True,
  2275. tmp_location=params.tmp_location,
  2276. tmpdir=tmpdir,
  2277. )
  2278. elif params.create_new and params.geofile:
  2279. set_mapset(
  2280. gisrc=gisrc, arg=params.mapset, geofile=params.geofile, create_new=True
  2281. )
  2282. elif params.tmp_mapset:
  2283. set_mapset(gisrc=gisrc, arg=params.mapset, tmp_mapset=params.tmp_mapset)
  2284. else:
  2285. set_mapset(gisrc=gisrc, arg=params.mapset, create_new=params.create_new)
  2286. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  2287. # e.g. wxGUI startup screen writes to the gisrc file,
  2288. # so loading it is the only universal way to obtain the values
  2289. # this suppose that both programs share the right path to gisrc file
  2290. # TODO: perhaps gisrcrc should be removed from here
  2291. # alternatively, we can check validity here with all the info we have
  2292. # about what was used to create gisrc
  2293. mapset_settings = load_gisrc(gisrc, gisrcrc=gisrcrc)
  2294. location = mapset_settings.full_mapset
  2295. try:
  2296. # check and create .gislock file
  2297. lock_mapset(
  2298. mapset_settings.full_mapset,
  2299. user=user,
  2300. force_gislock_removal=params.force_gislock_removal,
  2301. )
  2302. except Exception as e:
  2303. fatal(e.args[0])
  2304. sys.exit(_("Exiting..."))
  2305. # unlock the mapset which is current at the time of turning off
  2306. # in case mapset was changed
  2307. atexit.register(lambda: unlock_gisrc_mapset(gisrc, gisrcrc))
  2308. # We now own the mapset (set and lock), so we can clean temporary
  2309. # files which previous session may have left behind. We do it even
  2310. # for first time user because the cost is low and first time user
  2311. # doesn't necessarily mean that the mapset is used for the first time.
  2312. clean_temp()
  2313. # build user fontcap if specified but not present
  2314. make_fontcap()
  2315. # TODO: is this really needed? Modules should call this when/if required.
  2316. ensure_db_connected(location)
  2317. # Display the version and license info
  2318. # only non-error, interactive version continues from here
  2319. if params.batch_job:
  2320. returncode = run_batch_job(params.batch_job)
  2321. clean_all()
  2322. sys.exit(returncode)
  2323. elif params.exit_grass:
  2324. # clean always at exit, cleans whatever is current mapset based on
  2325. # the GISRC env variable
  2326. clean_all()
  2327. sys.exit(0)
  2328. else:
  2329. if use_shell:
  2330. show_banner()
  2331. say_hello()
  2332. show_info(shellname=shellname, grass_gui=grass_gui, default_gui=default_gui)
  2333. if grass_gui == "wxpython":
  2334. message(
  2335. _("Launching <%s> GUI in the background, please wait...")
  2336. % grass_gui
  2337. )
  2338. if sh in ["csh", "tcsh"]:
  2339. shell_process = csh_startup(mapset_settings.full_mapset, grass_env_file)
  2340. elif sh in ["zsh"]:
  2341. shell_process = sh_like_startup(
  2342. mapset_settings.full_mapset,
  2343. mapset_settings.location,
  2344. grass_env_file,
  2345. "zsh",
  2346. )
  2347. elif sh in ["bash", "msh", "cygwin"]:
  2348. shell_process = sh_like_startup(
  2349. mapset_settings.full_mapset,
  2350. mapset_settings.location,
  2351. grass_env_file,
  2352. "bash",
  2353. )
  2354. else:
  2355. shell_process = default_startup(
  2356. mapset_settings.full_mapset, mapset_settings.location
  2357. )
  2358. else:
  2359. shell_process = None
  2360. # start GUI and register shell PID in rc file
  2361. gui_process = start_gui(grass_gui)
  2362. if shell_process:
  2363. kv = {}
  2364. kv["PID"] = str(shell_process.pid)
  2365. # grass_prompt() tries to read gisrc while write_gisrc() is adding PID
  2366. # to this file, so don't rewrite it; just append PID to make it
  2367. # available to grass_prompt() at all times (PR #548)
  2368. write_gisrc(kv, gisrc, append=True)
  2369. exit_val = shell_process.wait()
  2370. if exit_val != 0:
  2371. warning(_("Failed to start shell '%s'") % os.getenv("SHELL"))
  2372. else:
  2373. gui_process.wait()
  2374. # close GUI if running
  2375. close_gui()
  2376. # here we are at the end of grass session
  2377. clean_all()
  2378. mapset_settings = load_gisrc(gisrc, gisrcrc=gisrcrc)
  2379. if not params.tmp_location or (
  2380. params.tmp_location and mapset_settings.gisdbase != os.environ["TMPDIR"]
  2381. ):
  2382. write_gisrcrc(gisrcrc, gisrc, skip_variable="LAST_MAPSET_PATH")
  2383. # After this point no more grass modules may be called
  2384. # done message at last: no atexit.register()
  2385. # or register done_message()
  2386. if use_shell:
  2387. done_message()
  2388. if __name__ == "__main__":
  2389. main()