v.unpack.py 8.6 KB

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