File size: 4,547 Bytes
cb1578f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#
# Copyright (c) 2019-2024 Leland Brown.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
# HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
#

try:
    from debug_logging import debug_log       as _debug_log
    from debug_logging import debug_exception as _debug_exception
except Exception:
    def _debug_log(severity, message): pass
    def _debug_exception(severity, message): pass


# import GDAL modules

import osgeo.gdal as gdal
import osgeo.osr as osr

import os.path
import subprocess
import sys


class GdalDataError(RuntimeError):
    pass


def _init_gdal_data():
    # set GDAL_DATA config value needed to evaluate EPSG codes, etc.

    # setup_gdal_data() must be called before calling ExportToPCI() on
    # an uninitialized osr.SpatialReference, or else later calls to
    # TransformPoint() will give weird errors even on unrelated objects

    if gdal.GetConfigOption("GDAL_DATA"):
        return

    _debug_log(1, "GDAL_DATA config option not pre-set.")

    gdal_data_path = None

    #try:
    #    # try running "gdal-config --datadir" to get gdal data path
    #    gdal_config = os.path.join(sys.prefix, "bin", "gdal-config")
    #    proc = subprocess.Popen(
    #        [gdal_config, "--datadir"],
    #        stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    #    out = proc.communicate()[0]
    #    if not proc.returncode:
    #        # use returned value
    #        gdal_data_path = out.decode(sys.getdefaultencoding()).rstrip()
    #    else:
    #        debug_log(2, "Return code " + str(proc.returnCode) + " from gdal-config.")
    #except Exception:
    #    debug_exception(1, "Exception running gdal-config.")

    try:
        # try running "gdal-config --datadir" to get gdal data path
        gdal_config = os.path.join(sys.prefix, "bin", "gdal-config")
        out = subprocess.check_output(
            [gdal_config, "--datadir"],
            stderr=subprocess.DEVNULL
        )
        gdal_data_path = out.decode(sys.getdefaultencoding()).rstrip()
    except subprocess.CalledProcessError as e:
        _debug_log(
            2, "Return code " + str(e.returncode) + " from gdal-config.")
    except Exception:
        _debug_exception(1, "Exception running gdal-config.")

    if not gdal_data_path:
        # otherwise guess location and look for file "epsg.wkt"

        base_paths = []
        base_paths.append(sys.prefix)
        base_paths.append(os.path.join(sys.prefix, "Library"))
        base_paths.append("/usr/local")
        base_paths.append("/usr")

        path_tails = []
        path_tails.append("gdal")
        path_tails.append(os.path.join("gdal", "data"))
        path_tails.append("epsg_csv")
        path_tails.append("")

        try:
            for base in base_paths:
                for tail in path_tails:
                    test_path = os.path.join(base, "share", tail)
                    test_file = os.path.join(test_path, "epsg.wkt")
                    if os.path.isfile(test_file):
                        raise StopIteration
        except StopIteration:
            # GDAL files found
            gdal_data_path = test_path
        else:
            # files not found
            raise GdalDataError(
                "Can't find path to GDAL data files.")

    gdal.SetConfigOption("GDAL_DATA", gdal_data_path)


_init_gdal_data()