grass.py 95 KB

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