grass.py 93 KB

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