v.unpack.py 8.5 KB

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