__init__.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. from grass import script
  11. #from grass.script import setup
  12. #
  13. #
  14. #GISBASE = "/home/pietro/docdat/src/gis/grass/grass71/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. #write dec to check if user have permissions or not
  26. ETYPE = {'rast': libgis.G_ELEMENT_RASTER,
  27. 'rast3d': libgis.G_ELEMENT_RASTER3D,
  28. 'vect': libgis.G_ELEMENT_VECTOR,
  29. 'oldvect': libgis.G_ELEMENT_OLDVECTOR,
  30. 'asciivect': libgis.G_ELEMENT_ASCIIVECTOR,
  31. 'icon': libgis.G_ELEMENT_ICON,
  32. 'labels': libgis.G_ELEMENT_LABEL,
  33. 'sites': libgis.G_ELEMENT_SITE,
  34. 'region': libgis.G_ELEMENT_REGION,
  35. 'region3d': libgis.G_ELEMENT_REGION3D,
  36. 'group': libgis.G_ELEMENT_GROUP,
  37. 'view3d': libgis.G_ELEMENT_3DVIEW}
  38. CHECK_IS = {"GISBASE": libgis.G_is_gisbase,
  39. "GISDBASE": lambda x: True,
  40. "LOCATION_NAME": libgis.G_is_location,
  41. "MAPSET": libgis.G_is_mapset}
  42. def _check(value, path, type):
  43. if value and CHECK_IS[type](join(path, value)):
  44. return value
  45. elif value is '':
  46. return getenv(type)
  47. else:
  48. raise GrassError("%s <%s> not found" % (type.title(),
  49. join(path, value)))
  50. def set_current_mapset(mapset, location=None, gisdbase=None):
  51. libgis.G_setenv('MAPSET', mapset)
  52. if location:
  53. libgis.G_setenv('LOCATION_NAME', location)
  54. if gisdbase:
  55. libgis.G_setenv('GISDBASE', gisdbase)
  56. def make_mapset(mapset, location=None, gisdbase=None):
  57. res = libgis.G_make_mapset(gisdbase, location, mapset)
  58. if res == -1:
  59. raise GrassError("Cannot create new mapset")
  60. elif res == -2:
  61. raise GrassError("Illegal name")
  62. class Gisdbase(object):
  63. """Return Gisdbase object. ::
  64. >>> from grass.script.core import gisenv
  65. >>> gisdbase = Gisdbase()
  66. >>> gisdbase.name == gisenv()['GISDBASE']
  67. True
  68. """
  69. def __init__(self, gisdbase=''):
  70. self.name = gisdbase
  71. def _get_name(self):
  72. return self._name
  73. def _set_name(self, name):
  74. self._name = _check(name, '', "GISDBASE")
  75. name = property(fget=_get_name, fset=_set_name)
  76. def __str__(self):
  77. return self.name
  78. def __repr__(self):
  79. return 'Gisdbase(%s)' % self.name
  80. def __getitem__(self, location):
  81. """Return a Location object. ::
  82. >>> from grass.script.core import gisenv
  83. >>> loc_env = gisenv()['LOCATION_NAME']
  84. >>> gisdbase = Gisdbase()
  85. >>> loc_py = gisdbase[loc_env]
  86. >>> loc_env == loc_py.name
  87. True
  88. ..
  89. """
  90. if location in self.locations():
  91. return Location(location, self.name)
  92. else:
  93. raise KeyError('Location: %s does not exist' % location)
  94. def __iter__(self):
  95. for loc in self.locations():
  96. yield Location(loc, self.name)
  97. def new_location(self):
  98. if libgis.G__make_location() != 0:
  99. raise GrassError("Cannot create new location")
  100. def locations(self):
  101. """Return a list of locations that are available in the gisdbase: ::
  102. >>> gisdbase = Gisdbase()
  103. >>> gisdbase.locations() # doctest: +ELLIPSIS
  104. [...]
  105. ..
  106. """
  107. locations = []
  108. for loc in listdir(self.name):
  109. if libgis.G_is_location(join(self.name, loc)):
  110. locations.append(loc)
  111. locations.sort()
  112. return locations
  113. class Location(object):
  114. """Location object ::
  115. >>> from grass.script.core import gisenv
  116. >>> location = Location()
  117. >>> location # doctest: +ELLIPSIS
  118. Location(...)
  119. >>> location.gisdbase == gisenv()['GISDBASE']
  120. True
  121. >>> location.name == gisenv()['LOCATION_NAME']
  122. True
  123. """
  124. def __init__(self, location='', gisdbase=''):
  125. self.gisdbase = gisdbase
  126. self.name = location
  127. def _get_gisdb(self):
  128. return self._gisdb
  129. def _set_gisdb(self, gisdb):
  130. self._gisdb = _check(gisdb, '', "GISDBASE")
  131. gisdbase = property(fget=_get_gisdb, fset=_set_gisdb)
  132. def _get_name(self):
  133. return self._name
  134. def _set_name(self, name):
  135. self._name = _check(name, self._gisdb, "LOCATION_NAME")
  136. name = property(fget=_get_name, fset=_set_name)
  137. def __getitem__(self, mapset):
  138. if mapset in self.mapsets():
  139. return Mapset(mapset)
  140. else:
  141. raise KeyError('Mapset: %s does not exist' % mapset)
  142. def __iter__(self):
  143. lpath = self.path()
  144. return (m for m in listdir(lpath)
  145. if (isdir(join(lpath, m)) and _check(m, lpath, "MAPSET")))
  146. def __len__(self):
  147. return len(self.mapsets())
  148. def __str__(self):
  149. return self.name
  150. def __repr__(self):
  151. return 'Location(%r)' % self.name
  152. def mapsets(self, pattern=None, permissions=True):
  153. """Return a list of the available mapsets. ::
  154. >>> location = Location()
  155. >>> location.mapsets()
  156. ['PERMANENT', 'user1']
  157. """
  158. mapsets = [mapset for mapset in self]
  159. if permissions:
  160. mapsets = [mapset for mapset in mapsets
  161. if libgis.G__mapset_permissions(mapset)]
  162. if pattern:
  163. return fnmatch.filter(mapsets, pattern)
  164. return mapsets
  165. def path(self):
  166. return join(self.gisdbase, self.name)
  167. class Mapset(object):
  168. """Mapset ::
  169. >>> mapset = Mapset()
  170. >>> mapset
  171. Mapset('user1')
  172. >>> mapset.gisdbase # doctest: +ELLIPSIS
  173. '/home/...'
  174. >>> mapset.location
  175. 'nc_basic_spm_grass7'
  176. >>> mapset.name
  177. 'user1'
  178. """
  179. def __init__(self, mapset='', location='', gisdbase=''):
  180. self.gisdbase = gisdbase
  181. self.location = location
  182. self.name = mapset
  183. self.visible = VisibleMapset(self.name, self.location, self.gisdbase)
  184. def _get_gisdb(self):
  185. return self._gisdb
  186. def _set_gisdb(self, gisdb):
  187. self._gisdb = _check(gisdb, '', "GISDBASE")
  188. gisdbase = property(fget=_get_gisdb, fset=_set_gisdb)
  189. def _get_loc(self):
  190. return self._loc
  191. def _set_loc(self, loc):
  192. self._loc = _check(loc, self._gisdb, "LOCATION_NAME")
  193. location = property(fget=_get_loc, fset=_set_loc)
  194. def _get_name(self):
  195. return self._name
  196. def _set_name(self, name):
  197. self._name = _check(name, join(self._gisdb, self._loc), "MAPSET")
  198. name = property(fget=_get_name, fset=_set_name)
  199. def __str__(self):
  200. return self.name
  201. def __repr__(self):
  202. return 'Mapset(%r)' % self.name
  203. def glist(self, type, pattern=None):
  204. """Return a list of grass types like:
  205. * 'asciivect',
  206. * 'group',
  207. * 'icon',
  208. * 'labels',
  209. * 'oldvect',
  210. * 'rast',
  211. * 'rast3d',
  212. * 'region',
  213. * 'region3d',
  214. * 'sites',
  215. * 'vect',
  216. * 'view3d'
  217. ::
  218. >>> mapset = Mapset('PERMANENT')
  219. >>> rast = mapset.glist('rast')
  220. >>> rast.sort()
  221. >>> rast # doctest: +ELLIPSIS
  222. ['basins', 'elevation', ...]
  223. >>> mapset.glist('rast', pattern='el*')
  224. ['elevation_shade', 'elevation']
  225. """
  226. if type not in ETYPE:
  227. str_err = "Type %s is not valid, valid types are: %s."
  228. raise TypeError(str_err % (type, ', '.join(ETYPE.keys())))
  229. clist = libgis.G_list(ETYPE[type], self.gisdbase,
  230. self.location, self.name)
  231. elist = []
  232. for el in clist:
  233. el_name = ct.cast(el, ct.c_char_p).value
  234. if el_name:
  235. elist.append(el_name)
  236. else:
  237. if pattern:
  238. return fnmatch.filter(elist, pattern)
  239. return elist
  240. def is_current(self):
  241. return (self.name == libgis.G_getenv('MAPSET') and
  242. self.location == libgis.G_getenv('LOCATION_NAME') and
  243. self.gisdbase == libgis.G_getenv('GISDBASE'))
  244. def current(self):
  245. """Set the mapset as current"""
  246. set_current_mapset(self.name, self.location, self.gisdbase)
  247. def delete(self):
  248. """Delete the mapset"""
  249. if self.is_current():
  250. raise GrassError('The mapset is in use.')
  251. shutil.rmtree(self.path())
  252. def path(self):
  253. return join(self.gisdbase, self.location, self.name)
  254. class VisibleMapset(object):
  255. def __init__(self, mapset, location='', gisdbase=''):
  256. self.mapset = mapset
  257. self.location = Location(location, gisdbase)
  258. self._list = []
  259. self.spath = join(self.location.path(), self.mapset, 'SEARCH_PATH')
  260. def __repr__(self):
  261. return repr(self.read())
  262. def __iter__(self):
  263. for mapset in self.read():
  264. yield mapset
  265. def read(self):
  266. with open(self.spath, "a+") as f:
  267. lines = f.readlines()
  268. #lines.remove('')
  269. if lines:
  270. return [l.strip() for l in lines]
  271. lns = ['PERMANENT', ]
  272. self.write(lns)
  273. return lns
  274. def write(self, mapsets):
  275. with open(self.spath, "w+") as f:
  276. ms = self.location.mapsets()
  277. f.write('%s' % '\n'.join([m for m in mapsets if m in ms]))
  278. def add(self, mapset):
  279. if mapset not in self.read() and mapset in self.location:
  280. with open(self.spath, "a+") as f:
  281. f.write('\n%s' % mapset)
  282. else:
  283. raise TypeError('Mapset not found')
  284. def remove(self, mapset):
  285. mapsets = self.read()
  286. mapsets.remove(mapset)
  287. self.write(mapsets)
  288. def extend(self, mapsets):
  289. ms = self.location.mapsets()
  290. final = self.read()
  291. final.extend([m for m in mapsets if m in ms and m not in final])
  292. self.write(final)