__init__.py 13 KB

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