v.unpack.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ############################################################################
  4. #
  5. # MODULE: v.unpack
  6. # AUTHOR(S): Luca Delucchi
  7. #
  8. # PURPOSE: Unpack up a vector map packed with v.pack
  9. # COPYRIGHT: (C) 2010-2017 by the GRASS Development Team
  10. #
  11. # This program is free software under the GNU General
  12. # Public License (>=v2). Read the file COPYING that
  13. # comes with GRASS for details.
  14. #
  15. #############################################################################
  16. #%module
  17. #% description: Imports a vector map as GRASS GIS specific archive file (packed with v.pack)
  18. #% keyword: vector
  19. #% keyword: import
  20. #% keyword: copying
  21. #%end
  22. #%option G_OPT_F_BIN_INPUT
  23. #% description: Name of input pack file
  24. #% key_desc: name.pack
  25. #%end
  26. #%option G_OPT_V_OUTPUT
  27. #% label: Name for output vector map
  28. #% description: Default: taken from input file internals
  29. #% required : no
  30. #% guisection: Output settings
  31. #%end
  32. #%flag
  33. #% key: o
  34. #% label: Override projection check (use current location's projection)
  35. #% description: Assume that the dataset has same projection as the current location
  36. #% guisection: Output settings
  37. #%end
  38. #%flag
  39. #% key: p
  40. #% label: Print projection information of input pack file and exit
  41. #% guisection: Print
  42. #%end
  43. import os
  44. import sys
  45. import shutil
  46. import tarfile
  47. import atexit
  48. from grass.script.utils import diff_files, try_rmdir
  49. from grass.script import core as grass
  50. from grass.script import db as grassdb
  51. from grass.exceptions import CalledModuleError
  52. # i18N
  53. import gettext
  54. gettext.install('grassmods', os.path.join(os.getenv("GISBASE"), 'locale'))
  55. def cleanup():
  56. try_rmdir(tmp_dir)
  57. def main():
  58. infile = options['input']
  59. # create temporary directory
  60. global tmp_dir
  61. tmp_dir = grass.tempdir()
  62. grass.debug('tmp_dir = %s' % tmp_dir)
  63. # check if the input file exists
  64. if not os.path.exists(infile):
  65. grass.fatal(_("File <%s> not found") % infile)
  66. # copy the files to tmp dir
  67. input_base = os.path.basename(infile)
  68. shutil.copyfile(infile, os.path.join(tmp_dir, input_base))
  69. os.chdir(tmp_dir)
  70. tar = tarfile.TarFile.open(name=input_base, mode='r')
  71. try:
  72. data_name = tar.getnames()[0]
  73. except:
  74. grass.fatal(_("Pack file unreadable"))
  75. if flags['p']:
  76. # print proj info and exit
  77. try:
  78. for fname in ['PROJ_INFO', 'PROJ_UNITS']:
  79. f = tar.extractfile(fname)
  80. sys.stdout.write(f.read())
  81. except KeyError:
  82. grass.fatal(_("Pack file unreadable: file '{}' missing".format(fname)))
  83. tar.close()
  84. return 0
  85. # set the output name
  86. if options['output']:
  87. map_name = options['output']
  88. else:
  89. map_name = data_name
  90. # grass env
  91. gisenv = grass.gisenv()
  92. mset_dir = os.path.join(gisenv['GISDBASE'],
  93. gisenv['LOCATION_NAME'],
  94. gisenv['MAPSET'])
  95. new_dir = os.path.join(mset_dir, 'vector', map_name)
  96. gfile = grass.find_file(name=map_name, element='vector', mapset='.')
  97. overwrite = os.getenv('GRASS_OVERWRITE')
  98. if gfile['file'] and overwrite != '1':
  99. grass.fatal(_("Vector map <%s> already exists") % map_name)
  100. elif overwrite == '1' and gfile['file']:
  101. grass.warning(_("Vector map <%s> already exists and will be overwritten") % map_name)
  102. grass.run_command('g.remove', flags='f', quiet=True, type='vector',
  103. name=map_name)
  104. shutil.rmtree(new_dir, True)
  105. # extract data
  106. tar.extractall()
  107. tar.close()
  108. if os.path.exists(os.path.join(data_name, 'coor')):
  109. pass
  110. elif os.path.exists(os.path.join(data_name, 'cell')):
  111. grass.fatal(_("This GRASS GIS pack file contains raster data. Use "
  112. "r.unpack to unpack <%s>" % map_name))
  113. else:
  114. grass.fatal(_("Pack file unreadable"))
  115. # check projection compatibility in a rather crappy way
  116. loc_proj = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_INFO')
  117. loc_proj_units = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_UNITS')
  118. skip_projection_check = False
  119. if not os.path.exists(os.path.join(tmp_dir, 'PROJ_INFO')):
  120. if os.path.exists(loc_proj):
  121. grass.fatal(
  122. _("PROJ_INFO file is missing, unpack vector map in XY (unprojected) location."))
  123. skip_projection_check = True # XY location
  124. if not skip_projection_check:
  125. diff_result_1 = diff_result_2 = None
  126. if not grass.compare_key_value_text_files(filename_a=os.path.join(tmp_dir, 'PROJ_INFO'),
  127. filename_b=loc_proj, proj=True):
  128. diff_result_1 = diff_files(os.path.join(tmp_dir, 'PROJ_INFO'),
  129. loc_proj)
  130. if not grass.compare_key_value_text_files(filename_a=os.path.join(tmp_dir, 'PROJ_UNITS'),
  131. filename_b=loc_proj_units,
  132. units=True):
  133. diff_result_2 = diff_files(os.path.join(tmp_dir, 'PROJ_UNITS'),
  134. loc_proj_units)
  135. if diff_result_1 or diff_result_2:
  136. if flags['o']:
  137. grass.warning(_("Projection information does not match. Proceeding..."))
  138. else:
  139. if diff_result_1:
  140. grass.warning(_("Difference between PROJ_INFO file of packed map "
  141. "and of current location:\n{diff}").format(diff=''.join(diff_result_1)))
  142. if diff_result_2:
  143. grass.warning(_("Difference between PROJ_UNITS file of packed map "
  144. "and of current location:\n{diff}").format(diff=''.join(diff_result_2)))
  145. grass.fatal(_("Projection of dataset does not appear to match current location."
  146. " In case of no significant differences in the projection definitions,"
  147. " use the -o flag to ignore them and use"
  148. " current location definition."))
  149. # new db
  150. fromdb = os.path.join(tmp_dir, 'db.sqlite')
  151. # copy file
  152. shutil.copytree(data_name, new_dir)
  153. # exist fromdb
  154. if os.path.exists(fromdb):
  155. # the db connection in the output mapset
  156. dbconn = grassdb.db_connection(force=True)
  157. todb = dbconn['database']
  158. # return all tables
  159. list_fromtable = grass.read_command('db.tables', driver='sqlite',
  160. database=fromdb).splitlines()
  161. # return the list of old connection for extract layer number and key
  162. dbln = open(os.path.join(new_dir, 'dbln'), 'r')
  163. dbnlist = dbln.readlines()
  164. dbln.close()
  165. # check if dbf or sqlite directory exists
  166. if dbconn['driver'] == 'dbf' and not os.path.exists(os.path.join(mset_dir, 'dbf')):
  167. os.mkdir(os.path.join(mset_dir, 'dbf'))
  168. elif dbconn['driver'] == 'sqlite' and not os.path.exists(os.path.join(mset_dir, 'sqlite')):
  169. os.mkdir(os.path.join(mset_dir, 'sqlite'))
  170. # for each old connection
  171. for t in dbnlist:
  172. # it split the line of each connection, to found layer number and key
  173. if len(t.split('|')) != 1:
  174. values = t.split('|')
  175. else:
  176. values = t.split(' ')
  177. from_table = values[1]
  178. layer = values[0].split('/')[0]
  179. # we need to take care about the table name in case of several layer
  180. if options["output"]:
  181. if len(dbnlist) > 1:
  182. to_table = "%s_%s" % (map_name, layer)
  183. else:
  184. to_table = map_name
  185. else:
  186. to_table = from_table
  187. grass.verbose(_("Coping table <%s> as table <%s>") % (from_table,
  188. to_table))
  189. # copy the table in the default database
  190. try:
  191. grass.run_command('db.copy', to_driver=dbconn['driver'],
  192. to_database=todb, to_table=to_table,
  193. from_driver='sqlite',
  194. from_database=fromdb,
  195. from_table=from_table)
  196. except CalledModuleError:
  197. grass.fatal(_("Unable to copy table <%s> as table <%s>") % (from_table, to_table))
  198. grass.verbose(_("Connect table <%s> to vector map <%s> at layer <%s>") %
  199. (to_table, map_name, layer))
  200. # and connect the new tables with the right layer
  201. try:
  202. grass.run_command('v.db.connect', flags='o', quiet=True,
  203. driver=dbconn['driver'], database=todb,
  204. map=map_name, key=values[2],
  205. layer=layer, table=to_table)
  206. except CalledModuleError:
  207. grass.fatal(_("Unable to connect table <%s> to vector map <%s>") %
  208. (to_table, map_name))
  209. grass.message(_("Vector map <%s> successfully unpacked") % map_name)
  210. if __name__ == "__main__":
  211. options, flags = grass.parser()
  212. atexit.register(cleanup)
  213. sys.exit(main())