v.unpack.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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-2013 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. import os
  39. import sys
  40. import shutil
  41. import tarfile
  42. import atexit
  43. from grass.script.utils import diff_files, try_rmdir
  44. from grass.script import core as grass
  45. from grass.script import db as grassdb
  46. from grass.exceptions import CalledModuleError
  47. def cleanup():
  48. try_rmdir(tmp_dir)
  49. def main():
  50. infile = options['input']
  51. # create temporary directory
  52. global tmp_dir
  53. tmp_dir = grass.tempdir()
  54. grass.debug('tmp_dir = %s' % tmp_dir)
  55. # check if the input file exists
  56. if not os.path.exists(infile):
  57. grass.fatal(_("File <%s> not found") % infile)
  58. # copy the files to tmp dir
  59. input_base = os.path.basename(infile)
  60. shutil.copyfile(infile, os.path.join(tmp_dir, input_base))
  61. os.chdir(tmp_dir)
  62. tar = tarfile.TarFile.open(name=input_base, mode='r')
  63. try:
  64. data_name = tar.getnames()[0]
  65. except:
  66. grass.fatal(_("Pack file unreadable"))
  67. # set the output name
  68. if options['output']:
  69. map_name = options['output']
  70. else:
  71. map_name = data_name
  72. # grass env
  73. gisenv = grass.gisenv()
  74. mset_dir = os.path.join(gisenv['GISDBASE'],
  75. gisenv['LOCATION_NAME'],
  76. gisenv['MAPSET'])
  77. new_dir = os.path.join(mset_dir, 'vector', map_name)
  78. gfile = grass.find_file(name=map_name, element='vector', mapset='.')
  79. overwrite = os.getenv('GRASS_OVERWRITE')
  80. if gfile['file'] and overwrite != '1':
  81. grass.fatal(_("Vector map <%s> already exists") % map_name)
  82. elif overwrite == '1' and gfile['file']:
  83. grass.warning(_("Vector map <%s> already exists and will be overwritten") % map_name)
  84. grass.run_command('g.remove', flags='f', quiet=True, type='vector',
  85. name=map_name)
  86. shutil.rmtree(new_dir, True)
  87. # extract data
  88. tar.extractall()
  89. if os.path.exists(os.path.join(data_name, 'coor')):
  90. pass
  91. elif os.path.exists(os.path.join(data_name, 'cell')):
  92. grass.fatal(_("This GRASS GIS pack file contains raster data. Use "
  93. "r.unpack to unpack <%s>" % map_name))
  94. else:
  95. grass.fatal(_("Pack file unreadable"))
  96. # check projection compatibility in a rather crappy way
  97. loc_proj = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_INFO')
  98. loc_proj_units = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_UNITS')
  99. skip_projection_check = False
  100. if not os.path.exists(os.path.join(tmp_dir, 'PROJ_INFO')):
  101. if os.path.exists(loc_proj):
  102. grass.fatal(_("PROJ_INFO file is missing, unpack vector map in XY (unprojected) location."))
  103. skip_projection_check = True # XY location
  104. if not skip_projection_check:
  105. diff_result_1 = diff_result_2 = None
  106. if not grass.compare_key_value_text_files(filename_a=os.path.join(tmp_dir, 'PROJ_INFO'),
  107. filename_b=loc_proj, proj=True):
  108. diff_result_1 = diff_files(os.path.join(tmp_dir, 'PROJ_INFO'),
  109. loc_proj)
  110. if not grass.compare_key_value_text_files(filename_a=os.path.join(tmp_dir, 'PROJ_UNITS'),
  111. filename_b=loc_proj_units,
  112. units=True):
  113. diff_result_2 = diff_files(os.path.join(tmp_dir, 'PROJ_UNITS'),
  114. loc_proj_units)
  115. if diff_result_1 or diff_result_2:
  116. if flags['o']:
  117. grass.warning(_("Projection information does not match. Proceeding..."))
  118. else:
  119. if diff_result_1:
  120. grass.warning(_("Difference between PROJ_INFO file of packed map "
  121. "and of current location:\n{diff}").format(diff=''.join(diff_result_1)))
  122. if diff_result_2:
  123. grass.warning(_("Difference between PROJ_UNITS file of packed map "
  124. "and of current location:\n{diff}").format(diff=''.join(diff_result_2)))
  125. grass.fatal(_("Projection of dataset does not appear to match current location."
  126. " In case of no significant differences in the projection definitions,"
  127. " use the -o flag to ignore them and use"
  128. " current location definition."))
  129. # new db
  130. fromdb = os.path.join(tmp_dir, 'db.sqlite')
  131. # copy file
  132. shutil.copytree(data_name, new_dir)
  133. # exist fromdb
  134. if os.path.exists(fromdb):
  135. # the db connection in the output mapset
  136. dbconn = grassdb.db_connection(force=True)
  137. todb = dbconn['database']
  138. # return all tables
  139. list_fromtable = grass.read_command('db.tables', driver='sqlite',
  140. database=fromdb).splitlines()
  141. # return the list of old connection for extract layer number and key
  142. dbln = open(os.path.join(new_dir, 'dbln'), 'r')
  143. dbnlist = dbln.readlines()
  144. dbln.close()
  145. # check if dbf or sqlite directory exists
  146. if dbconn['driver'] == 'dbf' and not os.path.exists(os.path.join(mset_dir, 'dbf')):
  147. os.mkdir(os.path.join(mset_dir, 'dbf'))
  148. elif dbconn['driver'] == 'sqlite' and not os.path.exists(os.path.join(mset_dir, 'sqlite')):
  149. os.mkdir(os.path.join(mset_dir, 'sqlite'))
  150. # for each old connection
  151. for t in dbnlist:
  152. # it split the line of each connection, to found layer number and key
  153. if len(t.split('|')) != 1:
  154. values = t.split('|')
  155. else:
  156. values = t.split(' ')
  157. from_table = values[1]
  158. layer = values[0].split('/')[0]
  159. # we need to take care about the table name in case of several layer
  160. if options["output"]:
  161. if len(dbnlist) > 1:
  162. to_table = "%s_%s" % (map_name, layer)
  163. else:
  164. to_table = map_name
  165. else:
  166. to_table = from_table
  167. grass.verbose(_("Coping table <%s> as table <%s>") % (from_table,
  168. to_table))
  169. # copy the table in the default database
  170. try:
  171. grass.run_command('db.copy', to_driver=dbconn['driver'],
  172. to_database=todb, to_table=to_table,
  173. from_driver='sqlite',
  174. from_database=fromdb,
  175. from_table=from_table)
  176. except CalledModuleError:
  177. grass.fatal(_("Unable to copy table <%s> as table <%s>") % (from_table, to_table))
  178. grass.verbose(_("Connect table <%s> to vector map <%s> at layer <%s>") %
  179. (to_table, map_name, layer))
  180. # and connect the new tables with the right layer
  181. try:
  182. grass.run_command('v.db.connect', flags='o', quiet=True,
  183. driver=dbconn['driver'], database=todb,
  184. map=map_name, key=values[2],
  185. layer=layer, table=to_table)
  186. except CalledModuleError:
  187. grass.fatal(_("Unable to connect table <%s> to vector map <%s>") %
  188. (to_table, map_name))
  189. grass.message(_("Vector map <%s> succesfully unpacked") % map_name)
  190. if __name__ == "__main__":
  191. options, flags = grass.parser()
  192. atexit.register(cleanup)
  193. sys.exit(main())