__init__.py 13 KB

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