grass.py 92 KB

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