v.unpack.py 7.8 KB

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