grass.py 95 KB

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