__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python2.7
  3. from __future__ import (nested_scopes, generators, division, absolute_import,
  4. with_statement, print_function, unicode_literals)
  5. from os import listdir
  6. from os.path import join, isdir
  7. import shutil
  8. import ctypes as ct
  9. import fnmatch
  10. import grass.lib.gis as libgis
  11. libgis.G_gisinit('')
  12. from grass.pygrass.errors import GrassError
  13. ETYPE = {'raster': libgis.G_ELEMENT_RASTER,
  14. 'raster_3d': libgis.G_ELEMENT_RASTER3D,
  15. 'vector': libgis.G_ELEMENT_VECTOR,
  16. 'label': libgis.G_ELEMENT_LABEL,
  17. 'region': libgis.G_ELEMENT_REGION,
  18. 'group': libgis.G_ELEMENT_GROUP}
  19. CHECK_IS = {"GISBASE": libgis.G_is_gisbase,
  20. "GISDBASE": lambda x: True,
  21. "LOCATION_NAME": libgis.G_is_location,
  22. "MAPSET": libgis.G_is_mapset}
  23. def _check(value, path, type):
  24. """Private function to check the correctness of a value.
  25. :param value: Name of the directory
  26. :type value: str
  27. :param path: Path where the directory is located
  28. :type path: path
  29. :param type: it is a string defining the type that will e checked,
  30. valid types are: GISBASE, GISDBASE, LOCATION_NAME, MAPSET
  31. :type type: str
  32. :return: the value if verify else None and
  33. if value is empty return environmental variable
  34. :rtype: str
  35. """
  36. if value and CHECK_IS[type](join(path, value)):
  37. return value
  38. elif value is '':
  39. from grass.pygrass.utils import getenv
  40. return getenv(type)
  41. else:
  42. raise GrassError("%s <%s> not found" % (type.title(),
  43. join(path, value)))
  44. def set_current_mapset(mapset, location=None, gisdbase=None):
  45. """Set the current mapset as working area
  46. :param mapset: Name of the mapset
  47. :type value: str
  48. :param location: Name of the location
  49. :type location: str
  50. :param gisdbase: Name of the gisdbase
  51. :type gisdbase: str
  52. """
  53. libgis.G_setenv('MAPSET', mapset)
  54. if location:
  55. libgis.G_setenv('LOCATION_NAME', location)
  56. if gisdbase:
  57. libgis.G_setenv('GISDBASE', gisdbase)
  58. def make_mapset(mapset, location=None, gisdbase=None):
  59. """Create a new mapset
  60. :param mapset: Name of the mapset
  61. :type value: str
  62. :param location: Name of the location
  63. :type location: str
  64. :param gisdbase: Name of the gisdbase
  65. :type gisdbase: str"""
  66. res = libgis.G_make_mapset(gisdbase, location, mapset)
  67. if res == -1:
  68. raise GrassError("Cannot create new mapset")
  69. elif res == -2:
  70. raise GrassError("Illegal name")
  71. class Gisdbase(object):
  72. """Return Gisdbase object. ::
  73. >>> from grass.script.core import gisenv
  74. >>> gisdbase = Gisdbase()
  75. >>> gisdbase.name == gisenv()['GISDBASE']
  76. True
  77. ..
  78. """
  79. def __init__(self, gisdbase=''):
  80. self.name = gisdbase
  81. def _get_name(self):
  82. return self._name
  83. def _set_name(self, name):
  84. self._name = _check(name, '', "GISDBASE")
  85. name = property(fget=_get_name, fset=_set_name,
  86. doc="Set or obtain the name of GISDBASE")
  87. def __str__(self):
  88. return self.name
  89. def __repr__(self):
  90. return 'Gisdbase(%s)' % self.name
  91. def __getitem__(self, location):
  92. """Return a Location object. ::
  93. >>> from grass.script.core import gisenv
  94. >>> loc_env = gisenv()['LOCATION_NAME']
  95. >>> gisdbase = Gisdbase()
  96. >>> loc_py = gisdbase[loc_env]
  97. >>> loc_env == loc_py.name
  98. True
  99. ..
  100. """
  101. if location in self.locations():
  102. return Location(location, self.name)
  103. else:
  104. raise KeyError('Location: %s does not exist' % location)
  105. def __iter__(self):
  106. for loc in self.locations():
  107. yield Location(loc, self.name)
  108. # TODO remove or complete this function
  109. def new_location(self):
  110. if libgis.G_make_location() != 0:
  111. raise GrassError("Cannot create new location")
  112. def locations(self):
  113. """Return a list of locations that are available in the gisdbase: ::
  114. >>> gisdbase = Gisdbase()
  115. >>> gisdbase.locations() # doctest: +ELLIPSIS
  116. [...]
  117. ..
  118. """
  119. return sorted([loc for loc in listdir(self.name)
  120. if libgis.G_is_location(join(self.name, loc))])
  121. class Location(object):
  122. """Location object ::
  123. >>> from grass.script.core import gisenv
  124. >>> location = Location()
  125. >>> location # doctest: +ELLIPSIS
  126. Location(...)
  127. >>> location.gisdbase == gisenv()['GISDBASE']
  128. True
  129. >>> location.name == gisenv()['LOCATION_NAME']
  130. True
  131. ..
  132. """
  133. def __init__(self, location='', gisdbase=''):
  134. self.gisdbase = gisdbase
  135. self.name = location
  136. def _get_gisdb(self):
  137. return self._gisdb
  138. def _set_gisdb(self, gisdb):
  139. self._gisdb = _check(gisdb, '', "GISDBASE")
  140. gisdbase = property(fget=_get_gisdb, fset=_set_gisdb,
  141. doc="Set or obtain the name of GISDBASE")
  142. def _get_name(self):
  143. return self._name
  144. def _set_name(self, name):
  145. self._name = _check(name, self._gisdb, "LOCATION_NAME")
  146. name = property(fget=_get_name, fset=_set_name,
  147. doc="Set or obtain the name of LOCATION")
  148. def __getitem__(self, mapset):
  149. if mapset in self.mapsets():
  150. return Mapset(mapset)
  151. else:
  152. raise KeyError('Mapset: %s does not exist' % mapset)
  153. def __iter__(self):
  154. lpath = self.path()
  155. return (m for m in listdir(lpath)
  156. if (isdir(join(lpath, m)) and _check(m, lpath, "MAPSET")))
  157. def __len__(self):
  158. return len(self.mapsets())
  159. def __str__(self):
  160. return self.name
  161. def __repr__(self):
  162. return 'Location(%r)' % self.name
  163. def mapsets(self, pattern=None, permissions=True):
  164. """Return a list of the available mapsets.
  165. :param pattern: the pattern to filter the result
  166. :type pattern: str
  167. :param permissions: check the permission of mapset
  168. :type permissions: bool
  169. :return: a list of mapset's names
  170. :rtype: list of strings
  171. ::
  172. >>> location = Location()
  173. >>> sorted(location.mapsets())
  174. ['PERMANENT', 'user1']
  175. """
  176. mapsets = [mapset for mapset in self]
  177. if permissions:
  178. mapsets = [mapset for mapset in mapsets
  179. if libgis.G_mapset_permissions(mapset)]
  180. if pattern:
  181. return fnmatch.filter(mapsets, pattern)
  182. return mapsets
  183. def path(self):
  184. """Return the complete path of the location"""
  185. return join(self.gisdbase, self.name)
  186. class Mapset(object):
  187. """Mapset ::
  188. >>> mapset = Mapset()
  189. >>> mapset
  190. Mapset('user1')
  191. >>> mapset.gisdbase # doctest: +ELLIPSIS
  192. '/home/...'
  193. >>> mapset.location
  194. 'nc_basic_spm_grass7'
  195. >>> mapset.name
  196. 'user1'
  197. ..
  198. """
  199. def __init__(self, mapset='', location='', gisdbase=''):
  200. self.gisdbase = gisdbase
  201. self.location = location
  202. self.name = mapset
  203. self.visible = VisibleMapset(self.name, self.location, self.gisdbase)
  204. def _get_gisdb(self):
  205. return self._gisdb
  206. def _set_gisdb(self, gisdb):
  207. self._gisdb = _check(gisdb, '', "GISDBASE")
  208. gisdbase = property(fget=_get_gisdb, fset=_set_gisdb,
  209. doc="Set or obtain the name of GISDBASE")
  210. def _get_loc(self):
  211. return self._loc
  212. def _set_loc(self, loc):
  213. self._loc = _check(loc, self._gisdb, "LOCATION_NAME")
  214. location = property(fget=_get_loc, fset=_set_loc,
  215. doc="Set or obtain the name of LOCATION")
  216. def _get_name(self):
  217. return self._name
  218. def _set_name(self, name):
  219. self._name = _check(name, join(self._gisdb, self._loc), "MAPSET")
  220. name = property(fget=_get_name, fset=_set_name,
  221. doc="Set or obtain the name of MAPSET")
  222. def __str__(self):
  223. return self.name
  224. def __repr__(self):
  225. return 'Mapset(%r)' % self.name
  226. def glist(self, type, pattern=None):
  227. """Return a list of grass types like:
  228. * 'group',
  229. * 'label',
  230. * 'raster',
  231. * 'raster_3d',
  232. * 'region',
  233. * 'vector',
  234. :param type: the type of element to query
  235. :type type: str
  236. :param pattern: the pattern to filter the result
  237. :type pattern: str
  238. ::
  239. >>> mapset = Mapset('PERMANENT')
  240. >>> rast = mapset.glist('rast')
  241. >>> rast.sort()
  242. >>> rast # doctest: +ELLIPSIS
  243. ['basins', 'elevation', ...]
  244. >>> sorted(mapset.glist('rast', pattern='el*'))
  245. ['elevation', 'elevation_shade']
  246. ..
  247. """
  248. if type not in ETYPE:
  249. str_err = "Type %s is not valid, valid types are: %s."
  250. raise TypeError(str_err % (type, ', '.join(ETYPE.keys())))
  251. clist = libgis.G_list(ETYPE[type], self.gisdbase,
  252. self.location, self.name)
  253. elist = []
  254. for el in clist:
  255. el_name = ct.cast(el, ct.c_char_p).value
  256. if el_name:
  257. elist.append(el_name)
  258. else:
  259. if pattern:
  260. return fnmatch.filter(elist, pattern)
  261. return elist
  262. def is_current(self):
  263. """Check if the MAPSET is the working MAPSET"""
  264. return (self.name == libgis.G_getenv('MAPSET') and
  265. self.location == libgis.G_getenv('LOCATION_NAME') and
  266. self.gisdbase == libgis.G_getenv('GISDBASE'))
  267. def current(self):
  268. """Set the mapset as current"""
  269. set_current_mapset(self.name, self.location, self.gisdbase)
  270. def delete(self):
  271. """Delete the mapset"""
  272. if self.is_current():
  273. raise GrassError('The mapset is in use.')
  274. shutil.rmtree(self.path())
  275. def path(self):
  276. """Return the complete path of the mapset"""
  277. return join(self.gisdbase, self.location, self.name)
  278. class VisibleMapset(object):
  279. """VisibleMapset object::
  280. >>> mapset = VisibleMapset('user1')
  281. >>> mapset
  282. ['user1', 'PERMANENT']
  283. ..
  284. """
  285. def __init__(self, mapset, location='', gisdbase=''):
  286. self.mapset = mapset
  287. self.location = Location(location, gisdbase)
  288. self._list = []
  289. self.spath = join(self.location.path(), self.mapset, 'SEARCH_PATH')
  290. def __repr__(self):
  291. return repr(self.read())
  292. def __iter__(self):
  293. for mapset in self.read():
  294. yield mapset
  295. def read(self):
  296. """Return the mapsets in the search path"""
  297. with open(self.spath, "a+") as f:
  298. lines = f.readlines()
  299. if lines:
  300. return [l.strip() for l in lines]
  301. lns = ['PERMANENT', ]
  302. self.write(lns)
  303. return lns
  304. def _write(self, mapsets):
  305. """Write to SEARCH_PATH file the changes in the search path
  306. :param mapsets: a list of mapset's names
  307. :type mapsets: list
  308. """
  309. with open(self.spath, "w+") as f:
  310. ms = self.location.mapsets()
  311. f.write('%s' % '\n'.join([m for m in mapsets if m in ms]))
  312. def add(self, mapset):
  313. """Add a mapset to the search path
  314. :param mapset: a mapset's name
  315. :type mapset: str
  316. """
  317. if mapset not in self.read() and mapset in self.location:
  318. with open(self.spath, "a+") as f:
  319. f.write('\n%s' % mapset)
  320. else:
  321. raise TypeError('Mapset not found')
  322. def remove(self, mapset):
  323. """Remove mapset to the search path
  324. :param mapset: a mapset's name
  325. :type mapset: str
  326. """
  327. mapsets = self.read()
  328. mapsets.remove(mapset)
  329. self._write(mapsets)
  330. def extend(self, mapsets):
  331. """Add more mapsets to the search path
  332. :param mapsets: a list of mapset's names
  333. :type mapsets: list
  334. """
  335. ms = self.location.mapsets()
  336. final = self.read()
  337. final.extend([m for m in mapsets if m in ms and m not in final])
  338. self._write(final)
  339. def reset(self):
  340. """Reset to the original search path"""
  341. final = [self.mapset, 'PERMANENT']
  342. self._write(final)