__init__.py 13 KB

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