grass.py 95 KB

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