__init__.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python2.7
  3. from __future__ import print_function
  4. #import os
  5. from os import listdir
  6. from os.path import join
  7. import shutil
  8. import ctypes as ct
  9. import fnmatch
  10. from grass import script
  11. #from grass.script import setup
  12. #
  13. #
  14. #GISBASE = "/home/pietro/docdat/src/gis/grass/grass70/dist.x86_64-unknown-linux-gnu"
  15. #LOCATION = "nc_basic_spm_grass7'"
  16. #GISDBASE = "/home/pietro/docdat/gis"
  17. #MAPSET = "sqlite"
  18. #GUI = "wxpython"
  19. #
  20. #setup.init(GISBASE, GISDBASE, LOCATION, MAPSET)
  21. script.gisenv()
  22. import grass.lib.gis as libgis
  23. from grass.pygrass.functions import getenv
  24. from grass.pygrass.errors import GrassError
  25. import region
  26. #write dec to check if user have permissions or not
  27. ETYPE = {'rast': libgis.G_ELEMENT_RASTER,
  28. 'rast3d': libgis.G_ELEMENT_RASTER3D,
  29. 'vect': libgis.G_ELEMENT_VECTOR,
  30. 'oldvect': libgis.G_ELEMENT_OLDVECTOR,
  31. 'asciivect': libgis.G_ELEMENT_ASCIIVECTOR,
  32. 'icon': libgis.G_ELEMENT_ICON,
  33. 'labels': libgis.G_ELEMENT_LABEL,
  34. 'sites': libgis.G_ELEMENT_SITE,
  35. 'region': libgis.G_ELEMENT_REGION,
  36. 'region3d': libgis.G_ELEMENT_REGION3D,
  37. 'group': libgis.G_ELEMENT_GROUP,
  38. 'view3d': libgis.G_ELEMENT_3DVIEW}
  39. CHECK_IS = {"GISBASE": libgis.G_is_gisbase,
  40. "GISDBASE": lambda x: True,
  41. "LOCATION_NAME": libgis.G_is_location,
  42. "MAPSET": libgis.G_is_mapset}
  43. def _check(value, path, type):
  44. #import pdb; pdb.set_trace()
  45. if value and CHECK_IS[type](join(path, value)):
  46. return value
  47. elif value is '':
  48. return getenv(type)
  49. else:
  50. raise GrassError("%s <%s> not found." % (type.title(),
  51. join(path, value)))
  52. def set_current_mapset(mapset, location=None, gisdbase=None):
  53. libgis.G_setenv('MAPSET', mapset)
  54. if location:
  55. libgis.G_setenv('LOCATION_NAME', location)
  56. if gisdbase:
  57. libgis.G_setenv('GISDBASEE', gisdbase)
  58. def make_mapset(mapset, location=None, gisdbase=None):
  59. res = libgis.G_make_mapset(gisdbase, location, mapset)
  60. if res == -1:
  61. raise GrassError("I cannot create a new mapset.")
  62. elif res == -2:
  63. raise GrassError("Illegal name.")
  64. class Gisdbase(object):
  65. """Return Gisdbase object. ::
  66. >>> from grass.script.core import gisenv
  67. >>> gisdbase = Gisdbase()
  68. >>> gisdbase.name == gisenv()['GISDBASE']
  69. True
  70. """
  71. def __init__(self, gisdbase=''):
  72. self.name = gisdbase
  73. def _get_name(self):
  74. return self._name
  75. def _set_name(self, name):
  76. self._name = _check(name, '', "GISDBASE")
  77. name = property(fget=_get_name, fset=_set_name)
  78. def __str__(self):
  79. return self.name
  80. def __repr__(self):
  81. return 'Gisdbase(%s)' % self.name
  82. def __getitem__(self, location):
  83. """Return a Location object. ::
  84. >>> from grass.script.core import gisenv
  85. >>> loc_env = gisenv()['LOCATION_NAME']
  86. >>> gisdbase = Gisdbase()
  87. >>> loc_py = gisdbase[loc_env]
  88. >>> loc_env == loc_py.name
  89. True
  90. ..
  91. """
  92. if location in self.locations():
  93. return Location(location, self.name)
  94. else:
  95. raise KeyError('Location: %s does not exist' % location)
  96. def __iter__(self):
  97. for loc in self.locations():
  98. yield Location(loc, self.name)
  99. def new_location(self):
  100. if libgis.G__make_location() != 0:
  101. raise GrassError("I cannot create a new mapset.")
  102. def locations(self):
  103. """Return a list of locations that are available in the gisdbase: ::
  104. >>> gisdbase = Gisdbase()
  105. >>> gisdbase.locations() # doctest: +ELLIPSIS
  106. [...]
  107. ..
  108. """
  109. locations = []
  110. for loc in listdir(self.name):
  111. if libgis.G_is_location(join(self.name, loc)):
  112. locations.append(loc)
  113. locations.sort()
  114. return locations
  115. class Location(object):
  116. """Location object ::
  117. >>> from grass.script.core import gisenv
  118. >>> location = Location()
  119. >>> location # doctest: +ELLIPSIS
  120. Location(...)
  121. >>> location.gisdbase == gisenv()['GISDBASE']
  122. True
  123. >>> location.name == gisenv()['LOCATION_NAME']
  124. True
  125. """
  126. def __init__(self, location='', gisdbase=''):
  127. self.gisdbase = gisdbase
  128. self.name = location
  129. def _get_gisdb(self):
  130. return self._gisdb
  131. def _set_gisdb(self, gisdb):
  132. self._gisdb = _check(gisdb, '', "GISDBASE")
  133. gisdbase = property(fget=_get_gisdb, fset=_set_gisdb)
  134. def _get_name(self):
  135. return self._name
  136. def _set_name(self, name):
  137. self._name = _check(name, self._gisdb, "LOCATION_NAME")
  138. name = property(fget=_get_name, fset=_set_name)
  139. def __getitem__(self, mapset):
  140. if mapset in self.mapsets():
  141. return Mapset(mapset)
  142. else:
  143. raise KeyError('Mapset: %s does not exist' % mapset)
  144. def __iter__(self):
  145. for mapset in libgis.G_available_mapsets():
  146. mapset_name = ct.cast(mapset, ct.c_char_p).value
  147. if mapset_name and libgis.G__mapset_permissions(mapset):
  148. yield mapset_name
  149. else:
  150. break
  151. def __len__(self):
  152. return len(self.mapsets())
  153. def __str__(self):
  154. return self.name
  155. def __repr__(self):
  156. return 'Location(%r)' % self.name
  157. def mapsets(self, pattern=None):
  158. """Return a list of the available mapsets. ::
  159. >>> location = Location()
  160. >>> location.mapsets()
  161. ['PERMANENT', 'user1']
  162. """
  163. mapsets = [mapset for mapset in self]
  164. if pattern:
  165. return fnmatch.filter(mapsets, pattern)
  166. return mapsets
  167. def path(self):
  168. return join(self.gisdbase, self.name)
  169. class Mapset(object):
  170. """Mapset ::
  171. >>> mapset = Mapset()
  172. >>> mapset
  173. Mapset('user1')
  174. >>> mapset.gisdbase # doctest: +ELLIPSIS
  175. '/home/...'
  176. >>> mapset.location
  177. 'nc_basic_spm_grass7'
  178. >>> mapset.name
  179. 'user1'
  180. """
  181. def __init__(self, mapset='', location='', gisdbase=''):
  182. self.gisdbase = gisdbase
  183. self.location = location
  184. self.name = mapset
  185. self.visible = VisibleMapset(self.name, self.location, self.gisdbase)
  186. def _get_gisdb(self):
  187. return self._gisdb
  188. def _set_gisdb(self, gisdb):
  189. self._gisdb = _check(gisdb, '', "GISDBASE")
  190. gisdbase = property(fget=_get_gisdb, fset=_set_gisdb)
  191. def _get_loc(self):
  192. return self._loc
  193. def _set_loc(self, loc):
  194. self._loc = _check(loc, self._gisdb, "LOCATION_NAME")
  195. location = property(fget=_get_loc, fset=_set_loc)
  196. def _get_name(self):
  197. return self._name
  198. def _set_name(self, name):
  199. self._name = _check(name, join(self._gisdb, self._loc), "MAPSET")
  200. name = property(fget=_get_name, fset=_set_name)
  201. def __str__(self):
  202. return self.name
  203. def __repr__(self):
  204. return 'Mapset(%r)' % self.name
  205. def glist(self, type, pattern=None):
  206. """Return a list of grass types like:
  207. * 'asciivect',
  208. * 'group',
  209. * 'icon',
  210. * 'labels',
  211. * 'oldvect',
  212. * 'rast',
  213. * 'rast3d',
  214. * 'region',
  215. * 'region3d',
  216. * 'sites',
  217. * 'vect',
  218. * 'view3d'
  219. ::
  220. >>> mapset = Mapset('PERMANENT')
  221. >>> rast = mapset.glist('rast')
  222. >>> rast.sort()
  223. >>> rast # doctest: +ELLIPSIS
  224. ['basins', 'elevation', ...]
  225. >>> mapset.glist('rast', pattern='el*')
  226. ['elevation_shade', 'elevation']
  227. """
  228. if type not in ETYPE:
  229. str_err = "Type %s is not valid, valid types are: %s."
  230. raise TypeError(str_err % (type, ', '.join(ETYPE.keys())))
  231. clist = libgis.G_list(ETYPE[type], self.gisdbase,
  232. self.location, self.name)
  233. elist = []
  234. for el in clist:
  235. el_name = ct.cast(el, ct.c_char_p).value
  236. if el_name:
  237. elist.append(el_name)
  238. else:
  239. if pattern:
  240. return fnmatch.filter(elist, pattern)
  241. return elist
  242. def is_current(self):
  243. return (self.name == libgis.G_getenv('MAPSET') and
  244. self.location == libgis.G_getenv('LOCATION_NAME') and
  245. self.gisdbase == libgis.G_getenv('GISDBASE'))
  246. def current(self):
  247. """Set the mapset as current"""
  248. set_current_mapset(self.name, self.location, self.gisdbase)
  249. def delete(self):
  250. """Delete the mapset"""
  251. if self.is_current():
  252. raise GrassError('The mapset is in use.')
  253. shutil.rmtree(self.path())
  254. def path(self):
  255. return join(self.gisdbase, self.location, self.name)