~ubuntu-branches/ubuntu/wily/grass/wily

« back to all changes in this revision

Viewing changes to scripts/v.unpack/v.unpack.py

Tags: 7.0.0~rc1+ds1-1~exp1
* New upstream release candidate.
* Repack upstream tarball, remove precompiled Python objects.
* Add upstream metadata.
* Update gbp.conf and Vcs-Git URL to use the experimental branch.
* Update watch file for GRASS 7.0.
* Drop build dependencies for Tcl/Tk, add build dependencies:
  python-numpy, libnetcdf-dev, netcdf-bin, libblas-dev, liblapack-dev
* Update Vcs-Browser URL to use cgit instead of gitweb.
* Update paths to use grass70.
* Add configure options: --with-netcdf, --with-blas, --with-lapack,
  remove --with-tcltk-includes.
* Update patches for GRASS 7.
* Update copyright file, changes:
  - Update copyright years
  - Group files by license
  - Remove unused license sections
* Add patches for various typos.
* Fix desktop file with patch instead of d/rules.
* Use minimal dh rules.
* Bump Standards-Version to 3.9.6, no changes.
* Use dpkg-maintscript-helper to replace directories with symlinks.
  (closes: #776349)
* Update my email to use @debian.org address.

Show diffs side-by-side

added added

removed removed

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