We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
rio merge error
When running `rio merge` on the latest version (`0.27`), I am receiving this error:

```
Traceback (most recent call last):
  File "/Users/dnomadb/venv/bin/rio", line 11, in <module>
    sys.exit(main_group())
  File "/Users/dnomadb/venv/lib/python2.7/site-packages/click/core.py", line 700, in __call__
    return self.main(*args, **kwargs)
  File "/Users/dnomadb/venv/lib/python2.7/site-packages/click/core.py", line 680, in main
    rv = self.invoke(ctx)
  File "/Users/dnomadb/venv/lib/python2.7/site-packages/click/core.py", line 1027, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Users/dnomadb/venv/lib/python2.7/site-packages/click/core.py", line 873, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/dnomadb/venv/lib/python2.7/site-packages/click/core.py", line 508, in invoke
    return callback(*args, **kwargs)
  File "/Users/dnomadb/venv/lib/python2.7/site-packages/click/decorators.py", line 16, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/Users/dnomadb/venv/lib/python2.7/site-packages/rasterio/rio/merge.py", line 54, in merge
    from rasterio.tools.merge import merge as merge_tool
ImportError: No module named tools.merge
```

When reverting back to `0.26`, I don't see it and the operation completes as expected.

cc @sgillies 


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `setup.py`
Content:
```
1 #!/usr/bin/env python
2 
3 # Two environmental variables influence this script.
4 #
5 # GDAL_CONFIG: the path to a gdal-config program that points to GDAL headers,
6 # libraries, and data files.
7 #
8 # PACKAGE_DATA: if defined, GDAL and PROJ4 data files will be copied into the
9 # source or binary distribution. This is essential when creating self-contained
10 # binary wheels.
11 
12 import logging
13 import os
14 import pprint
15 import shutil
16 import subprocess
17 import sys
18 
19 from setuptools import setup
20 from setuptools.extension import Extension
21 
22 logging.basicConfig()
23 log = logging.getLogger()
24 
25 # python -W all setup.py ...
26 if 'all' in sys.warnoptions:
27     log.level = logging.DEBUG
28 
29 def check_output(cmd):
30     # since subprocess.check_output doesn't exist in 2.6
31     # we wrap it here.
32     try:
33         out = subprocess.check_output(cmd)
34         return out.decode('utf')
35     except AttributeError:
36         # For some reasone check_output doesn't exist
37         # So fall back on Popen
38         p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
39         out, err = p.communicate()
40         return out
41 
42 def copy_data_tree(datadir, destdir):
43     try:
44         shutil.rmtree(destdir)
45     except OSError:
46         pass
47     shutil.copytree(datadir, destdir)
48 
49 # Parse the version from the rasterio module.
50 with open('rasterio/__init__.py') as f:
51     for line in f:
52         if line.find("__version__") >= 0:
53             version = line.split("=")[1].strip()
54             version = version.strip('"')
55             version = version.strip("'")
56             continue
57 
58 with open('VERSION.txt', 'w') as f:
59     f.write(version)
60 
61 # Use Cython if available.
62 try:
63     from Cython.Build import cythonize
64 except ImportError:
65     cythonize = None
66 
67 # By default we'll try to get options via gdal-config. On systems without,
68 # options will need to be set in setup.cfg or on the setup command line.
69 include_dirs = []
70 library_dirs = []
71 libraries = []
72 extra_link_args = []
73 gdal_output = [None]*3
74 
75 try:
76     import numpy
77     include_dirs.append(numpy.get_include())
78 except ImportError:
79     log.critical("Numpy and its headers are required to run setup(). Exiting.")
80     sys.exit(1)
81 
82 try:
83     gdal_config = os.environ.get('GDAL_CONFIG', 'gdal-config')
84     for i, flag in enumerate(("--cflags", "--libs", "--datadir")):
85         gdal_output[i] = check_output([gdal_config, flag]).strip()
86 
87     for item in gdal_output[0].split():
88         if item.startswith("-I"):
89             include_dirs.extend(item[2:].split(":"))
90     for item in gdal_output[1].split():
91         if item.startswith("-L"):
92             library_dirs.extend(item[2:].split(":"))
93         elif item.startswith("-l"):
94             libraries.append(item[2:])
95         else:
96             # e.g. -framework GDAL
97             extra_link_args.append(item)
98 
99 except Exception as e:
100     if os.name == "nt":
101         log.info(("Building on Windows requires extra options to setup.py to locate needed GDAL files.\n"
102                  "More information is available in the README."))
103     else:
104         log.warning("Failed to get options via gdal-config: %s", str(e))
105 
106 
107 # Conditionally copy the GDAL data. To be used in conjunction with
108 # the bdist_wheel command to make self-contained binary wheels.
109 if os.environ.get('PACKAGE_DATA'):
110     destdir = 'rasterio/gdal_data'
111     if gdal_output[2]:
112         log.info("Copying gdal data from %s" % gdal_output[2])
113         copy_data_tree(gdal_output[2], destdir)
114     else:
115         # check to see if GDAL_DATA is defined
116         gdal_data = os.environ.get('GDAL_DATA', None)
117         if gdal_data:
118             log.info("Copying gdal_data from %s" % gdal_data)
119             copy_data_tree(gdal_data, destdir)
120 
121     # Conditionally copy PROJ.4 data.
122     projdatadir = os.environ.get('PROJ_LIB', '/usr/local/share/proj')
123     if os.path.exists(projdatadir):
124         log.info("Copying proj_data from %s" % projdatadir)
125         copy_data_tree(projdatadir, 'rasterio/proj_data')
126 
127 ext_options = dict(
128     include_dirs=include_dirs,
129     library_dirs=library_dirs,
130     libraries=libraries,
131     extra_link_args=extra_link_args)
132 
133 if not os.name == "nt":
134     # These options fail on Windows if using Visual Studio
135     ext_options['extra_compile_args'] = ['-Wno-unused-parameter',
136                                          '-Wno-unused-function']
137 
138 log.debug('ext_options:\n%s', pprint.pformat(ext_options))
139 
140 # When building from a repo, Cython is required.
141 if os.path.exists("MANIFEST.in") and "clean" not in sys.argv:
142     log.info("MANIFEST.in found, presume a repo, cythonizing...")
143     if not cythonize:
144         log.critical(
145             "Cython.Build.cythonize not found. "
146             "Cython is required to build from a repo.")
147         sys.exit(1)
148     ext_modules = cythonize([
149         Extension(
150             'rasterio._base', ['rasterio/_base.pyx'], **ext_options),
151         Extension(
152             'rasterio._io', ['rasterio/_io.pyx'], **ext_options),
153         Extension(
154             'rasterio._copy', ['rasterio/_copy.pyx'], **ext_options),
155         Extension(
156             'rasterio._features', ['rasterio/_features.pyx'], **ext_options),
157         Extension(
158             'rasterio._drivers', ['rasterio/_drivers.pyx'], **ext_options),
159         Extension(
160             'rasterio._warp', ['rasterio/_warp.pyx'], **ext_options),
161         Extension(
162             'rasterio._fill', ['rasterio/_fill.pyx', 'rasterio/rasterfill.cpp'], **ext_options),
163         Extension(
164             'rasterio._err', ['rasterio/_err.pyx'], **ext_options),
165         Extension(
166             'rasterio._example', ['rasterio/_example.pyx'], **ext_options),
167         ], quiet=True)
168 
169 # If there's no manifest template, as in an sdist, we just specify .c files.
170 else:
171     ext_modules = [
172         Extension(
173             'rasterio._base', ['rasterio/_base.c'], **ext_options),
174         Extension(
175             'rasterio._io', ['rasterio/_io.c'], **ext_options),
176         Extension(
177             'rasterio._copy', ['rasterio/_copy.c'], **ext_options),
178         Extension(
179             'rasterio._features', ['rasterio/_features.c'], **ext_options),
180         Extension(
181             'rasterio._drivers', ['rasterio/_drivers.c'], **ext_options),
182         Extension(
183             'rasterio._warp', ['rasterio/_warp.cpp'], **ext_options),
184         Extension(
185             'rasterio._fill', ['rasterio/_fill.cpp', 'rasterio/rasterfill.cpp'], **ext_options),
186         Extension(
187             'rasterio._err', ['rasterio/_err.c'], **ext_options),
188         Extension(
189             'rasterio._example', ['rasterio/_example.c'], **ext_options),
190             ]
191 
192 with open('README.rst') as f:
193     readme = f.read()
194 
195 # Runtime requirements.
196 inst_reqs = [
197     'affine>=1.0',
198     'cligj>=0.2.0',
199     'Numpy>=1.7',
200     'snuggs>=1.3.1',
201     'click-plugins']
202 
203 if sys.version_info < (3, 4):
204     inst_reqs.append('enum34')
205 
206 setup_args = dict(
207     name='rasterio',
208     version=version,
209     description="Fast and direct raster I/O for use with Numpy and SciPy",
210     long_description=readme,
211     classifiers=[
212         'Development Status :: 4 - Beta',
213         'Intended Audience :: Developers',
214         'Intended Audience :: Information Technology',
215         'Intended Audience :: Science/Research',
216         'License :: OSI Approved :: BSD License',
217         'Programming Language :: C',
218         'Programming Language :: Python :: 2.6',
219         'Programming Language :: Python :: 2.7',
220         'Programming Language :: Python :: 3.3',
221         'Programming Language :: Python :: 3.4',
222         'Topic :: Multimedia :: Graphics :: Graphics Conversion',
223         'Topic :: Scientific/Engineering :: GIS'],
224     keywords='raster gdal',
225     author='Sean Gillies',
226     author_email='sean@mapbox.com',
227     url='https://github.com/mapbox/rasterio',
228     license='BSD',
229     package_dir={'': '.'},
230     packages=['rasterio', 'rasterio.rio'],
231     entry_points='''
232         [console_scripts]
233         rio=rasterio.rio.main:main_group
234 
235         [rasterio.rio_commands]
236         bounds=rasterio.rio.features:bounds
237         calc=rasterio.rio.calc:calc
238         clip=rasterio.rio.convert:clip
239         convert=rasterio.rio.convert:convert
240         edit-info=rasterio.rio.info:edit
241         env=rasterio.rio.info:env
242         info=rasterio.rio.info:info
243         insp=rasterio.rio.info:insp
244         mask=rasterio.rio.features:mask
245         merge=rasterio.rio.merge:merge
246         overview=rasterio.rio.overview:overview
247         rasterize=rasterio.rio.features:rasterize
248         sample=rasterio.rio.sample:sample
249         shapes=rasterio.rio.features:shapes
250         stack=rasterio.rio.bands:stack
251         warp=rasterio.rio.warp:warp
252         transform=rasterio.rio.info:transform
253     ''',
254     include_package_data=True,
255     ext_modules=ext_modules,
256     zip_safe=False,
257     install_requires=inst_reqs,
258     extras_require={
259         'ipython': ['ipython>=2.0']})
260 
261 if os.environ.get('PACKAGE_DATA'):
262     setup_args['package_data'] = {'rasterio': ['gdal_data/*', 'proj_data/*']}
263 
264 setup(**setup_args)
265
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -227,7 +227,7 @@
     url='https://github.com/mapbox/rasterio',
     license='BSD',
     package_dir={'': '.'},
-    packages=['rasterio', 'rasterio.rio'],
+    packages=['rasterio', 'rasterio.rio', 'rasterio.tools'],
     entry_points='''
         [console_scripts]
         rio=rasterio.rio.main:main_group

{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -227,7 +227,7 @@\n     url='https://github.com/mapbox/rasterio',\n     license='BSD',\n     package_dir={'': '.'},\n-    packages=['rasterio', 'rasterio.rio'],\n+    packages=['rasterio', 'rasterio.rio', 'rasterio.tools'],\n     entry_points='''\n         [console_scripts]\n         rio=rasterio.rio.main:main_group\n", "issue": "rio merge error\nWhen running `rio merge` on the latest version (`0.27`), I am receiving this error:\n\n```\nTraceback (most recent call last):\n  File \"/Users/dnomadb/venv/bin/rio\", line 11, in <module>\n    sys.exit(main_group())\n  File \"/Users/dnomadb/venv/lib/python2.7/site-packages/click/core.py\", line 700, in __call__\n    return self.main(*args, **kwargs)\n  File \"/Users/dnomadb/venv/lib/python2.7/site-packages/click/core.py\", line 680, in main\n    rv = self.invoke(ctx)\n  File \"/Users/dnomadb/venv/lib/python2.7/site-packages/click/core.py\", line 1027, in invoke\n    return _process_result(sub_ctx.command.invoke(sub_ctx))\n  File \"/Users/dnomadb/venv/lib/python2.7/site-packages/click/core.py\", line 873, in invoke\n    return ctx.invoke(self.callback, **ctx.params)\n  File \"/Users/dnomadb/venv/lib/python2.7/site-packages/click/core.py\", line 508, in invoke\n    return callback(*args, **kwargs)\n  File \"/Users/dnomadb/venv/lib/python2.7/site-packages/click/decorators.py\", line 16, in new_func\n    return f(get_current_context(), *args, **kwargs)\n  File \"/Users/dnomadb/venv/lib/python2.7/site-packages/rasterio/rio/merge.py\", line 54, in merge\n    from rasterio.tools.merge import merge as merge_tool\nImportError: No module named tools.merge\n```\n\nWhen reverting back to `0.26`, I don't see it and the operation completes as expected.\n\ncc @sgillies \n\n", "before_files": [{"content": "#!/usr/bin/env python\n\n# Two environmental variables influence this script.\n#\n# GDAL_CONFIG: the path to a gdal-config program that points to GDAL headers,\n# libraries, and data files.\n#\n# PACKAGE_DATA: if defined, GDAL and PROJ4 data files will be copied into the\n# source or binary distribution. This is essential when creating self-contained\n# binary wheels.\n\nimport logging\nimport os\nimport pprint\nimport shutil\nimport subprocess\nimport sys\n\nfrom setuptools import setup\nfrom setuptools.extension import Extension\n\nlogging.basicConfig()\nlog = logging.getLogger()\n\n# python -W all setup.py ...\nif 'all' in sys.warnoptions:\n    log.level = logging.DEBUG\n\ndef check_output(cmd):\n    # since subprocess.check_output doesn't exist in 2.6\n    # we wrap it here.\n    try:\n        out = subprocess.check_output(cmd)\n        return out.decode('utf')\n    except AttributeError:\n        # For some reasone check_output doesn't exist\n        # So fall back on Popen\n        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)\n        out, err = p.communicate()\n        return out\n\ndef copy_data_tree(datadir, destdir):\n    try:\n        shutil.rmtree(destdir)\n    except OSError:\n        pass\n    shutil.copytree(datadir, destdir)\n\n# Parse the version from the rasterio module.\nwith open('rasterio/__init__.py') as f:\n    for line in f:\n        if line.find(\"__version__\") >= 0:\n            version = line.split(\"=\")[1].strip()\n            version = version.strip('\"')\n            version = version.strip(\"'\")\n            continue\n\nwith open('VERSION.txt', 'w') as f:\n    f.write(version)\n\n# Use Cython if available.\ntry:\n    from Cython.Build import cythonize\nexcept ImportError:\n    cythonize = None\n\n# By default we'll try to get options via gdal-config. On systems without,\n# options will need to be set in setup.cfg or on the setup command line.\ninclude_dirs = []\nlibrary_dirs = []\nlibraries = []\nextra_link_args = []\ngdal_output = [None]*3\n\ntry:\n    import numpy\n    include_dirs.append(numpy.get_include())\nexcept ImportError:\n    log.critical(\"Numpy and its headers are required to run setup(). Exiting.\")\n    sys.exit(1)\n\ntry:\n    gdal_config = os.environ.get('GDAL_CONFIG', 'gdal-config')\n    for i, flag in enumerate((\"--cflags\", \"--libs\", \"--datadir\")):\n        gdal_output[i] = check_output([gdal_config, flag]).strip()\n\n    for item in gdal_output[0].split():\n        if item.startswith(\"-I\"):\n            include_dirs.extend(item[2:].split(\":\"))\n    for item in gdal_output[1].split():\n        if item.startswith(\"-L\"):\n            library_dirs.extend(item[2:].split(\":\"))\n        elif item.startswith(\"-l\"):\n            libraries.append(item[2:])\n        else:\n            # e.g. -framework GDAL\n            extra_link_args.append(item)\n\nexcept Exception as e:\n    if os.name == \"nt\":\n        log.info((\"Building on Windows requires extra options to setup.py to locate needed GDAL files.\\n\"\n                 \"More information is available in the README.\"))\n    else:\n        log.warning(\"Failed to get options via gdal-config: %s\", str(e))\n\n\n# Conditionally copy the GDAL data. To be used in conjunction with\n# the bdist_wheel command to make self-contained binary wheels.\nif os.environ.get('PACKAGE_DATA'):\n    destdir = 'rasterio/gdal_data'\n    if gdal_output[2]:\n        log.info(\"Copying gdal data from %s\" % gdal_output[2])\n        copy_data_tree(gdal_output[2], destdir)\n    else:\n        # check to see if GDAL_DATA is defined\n        gdal_data = os.environ.get('GDAL_DATA', None)\n        if gdal_data:\n            log.info(\"Copying gdal_data from %s\" % gdal_data)\n            copy_data_tree(gdal_data, destdir)\n\n    # Conditionally copy PROJ.4 data.\n    projdatadir = os.environ.get('PROJ_LIB', '/usr/local/share/proj')\n    if os.path.exists(projdatadir):\n        log.info(\"Copying proj_data from %s\" % projdatadir)\n        copy_data_tree(projdatadir, 'rasterio/proj_data')\n\next_options = dict(\n    include_dirs=include_dirs,\n    library_dirs=library_dirs,\n    libraries=libraries,\n    extra_link_args=extra_link_args)\n\nif not os.name == \"nt\":\n    # These options fail on Windows if using Visual Studio\n    ext_options['extra_compile_args'] = ['-Wno-unused-parameter',\n                                         '-Wno-unused-function']\n\nlog.debug('ext_options:\\n%s', pprint.pformat(ext_options))\n\n# When building from a repo, Cython is required.\nif os.path.exists(\"MANIFEST.in\") and \"clean\" not in sys.argv:\n    log.info(\"MANIFEST.in found, presume a repo, cythonizing...\")\n    if not cythonize:\n        log.critical(\n            \"Cython.Build.cythonize not found. \"\n            \"Cython is required to build from a repo.\")\n        sys.exit(1)\n    ext_modules = cythonize([\n        Extension(\n            'rasterio._base', ['rasterio/_base.pyx'], **ext_options),\n        Extension(\n            'rasterio._io', ['rasterio/_io.pyx'], **ext_options),\n        Extension(\n            'rasterio._copy', ['rasterio/_copy.pyx'], **ext_options),\n        Extension(\n            'rasterio._features', ['rasterio/_features.pyx'], **ext_options),\n        Extension(\n            'rasterio._drivers', ['rasterio/_drivers.pyx'], **ext_options),\n        Extension(\n            'rasterio._warp', ['rasterio/_warp.pyx'], **ext_options),\n        Extension(\n            'rasterio._fill', ['rasterio/_fill.pyx', 'rasterio/rasterfill.cpp'], **ext_options),\n        Extension(\n            'rasterio._err', ['rasterio/_err.pyx'], **ext_options),\n        Extension(\n            'rasterio._example', ['rasterio/_example.pyx'], **ext_options),\n        ], quiet=True)\n\n# If there's no manifest template, as in an sdist, we just specify .c files.\nelse:\n    ext_modules = [\n        Extension(\n            'rasterio._base', ['rasterio/_base.c'], **ext_options),\n        Extension(\n            'rasterio._io', ['rasterio/_io.c'], **ext_options),\n        Extension(\n            'rasterio._copy', ['rasterio/_copy.c'], **ext_options),\n        Extension(\n            'rasterio._features', ['rasterio/_features.c'], **ext_options),\n        Extension(\n            'rasterio._drivers', ['rasterio/_drivers.c'], **ext_options),\n        Extension(\n            'rasterio._warp', ['rasterio/_warp.cpp'], **ext_options),\n        Extension(\n            'rasterio._fill', ['rasterio/_fill.cpp', 'rasterio/rasterfill.cpp'], **ext_options),\n        Extension(\n            'rasterio._err', ['rasterio/_err.c'], **ext_options),\n        Extension(\n            'rasterio._example', ['rasterio/_example.c'], **ext_options),\n            ]\n\nwith open('README.rst') as f:\n    readme = f.read()\n\n# Runtime requirements.\ninst_reqs = [\n    'affine>=1.0',\n    'cligj>=0.2.0',\n    'Numpy>=1.7',\n    'snuggs>=1.3.1',\n    'click-plugins']\n\nif sys.version_info < (3, 4):\n    inst_reqs.append('enum34')\n\nsetup_args = dict(\n    name='rasterio',\n    version=version,\n    description=\"Fast and direct raster I/O for use with Numpy and SciPy\",\n    long_description=readme,\n    classifiers=[\n        'Development Status :: 4 - Beta',\n        'Intended Audience :: Developers',\n        'Intended Audience :: Information Technology',\n        'Intended Audience :: Science/Research',\n        'License :: OSI Approved :: BSD License',\n        'Programming Language :: C',\n        'Programming Language :: Python :: 2.6',\n        'Programming Language :: Python :: 2.7',\n        'Programming Language :: Python :: 3.3',\n        'Programming Language :: Python :: 3.4',\n        'Topic :: Multimedia :: Graphics :: Graphics Conversion',\n        'Topic :: Scientific/Engineering :: GIS'],\n    keywords='raster gdal',\n    author='Sean Gillies',\n    author_email='sean@mapbox.com',\n    url='https://github.com/mapbox/rasterio',\n    license='BSD',\n    package_dir={'': '.'},\n    packages=['rasterio', 'rasterio.rio'],\n    entry_points='''\n        [console_scripts]\n        rio=rasterio.rio.main:main_group\n\n        [rasterio.rio_commands]\n        bounds=rasterio.rio.features:bounds\n        calc=rasterio.rio.calc:calc\n        clip=rasterio.rio.convert:clip\n        convert=rasterio.rio.convert:convert\n        edit-info=rasterio.rio.info:edit\n        env=rasterio.rio.info:env\n        info=rasterio.rio.info:info\n        insp=rasterio.rio.info:insp\n        mask=rasterio.rio.features:mask\n        merge=rasterio.rio.merge:merge\n        overview=rasterio.rio.overview:overview\n        rasterize=rasterio.rio.features:rasterize\n        sample=rasterio.rio.sample:sample\n        shapes=rasterio.rio.features:shapes\n        stack=rasterio.rio.bands:stack\n        warp=rasterio.rio.warp:warp\n        transform=rasterio.rio.info:transform\n    ''',\n    include_package_data=True,\n    ext_modules=ext_modules,\n    zip_safe=False,\n    install_requires=inst_reqs,\n    extras_require={\n        'ipython': ['ipython>=2.0']})\n\nif os.environ.get('PACKAGE_DATA'):\n    setup_args['package_data'] = {'rasterio': ['gdal_data/*', 'proj_data/*']}\n\nsetup(**setup_args)\n", "path": "setup.py"}], "after_files": [{"content": "#!/usr/bin/env python\n\n# Two environmental variables influence this script.\n#\n# GDAL_CONFIG: the path to a gdal-config program that points to GDAL headers,\n# libraries, and data files.\n#\n# PACKAGE_DATA: if defined, GDAL and PROJ4 data files will be copied into the\n# source or binary distribution. This is essential when creating self-contained\n# binary wheels.\n\nimport logging\nimport os\nimport pprint\nimport shutil\nimport subprocess\nimport sys\n\nfrom setuptools import setup\nfrom setuptools.extension import Extension\n\nlogging.basicConfig()\nlog = logging.getLogger()\n\n# python -W all setup.py ...\nif 'all' in sys.warnoptions:\n    log.level = logging.DEBUG\n\ndef check_output(cmd):\n    # since subprocess.check_output doesn't exist in 2.6\n    # we wrap it here.\n    try:\n        out = subprocess.check_output(cmd)\n        return out.decode('utf')\n    except AttributeError:\n        # For some reasone check_output doesn't exist\n        # So fall back on Popen\n        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)\n        out, err = p.communicate()\n        return out\n\ndef copy_data_tree(datadir, destdir):\n    try:\n        shutil.rmtree(destdir)\n    except OSError:\n        pass\n    shutil.copytree(datadir, destdir)\n\n# Parse the version from the rasterio module.\nwith open('rasterio/__init__.py') as f:\n    for line in f:\n        if line.find(\"__version__\") >= 0:\n            version = line.split(\"=\")[1].strip()\n            version = version.strip('\"')\n            version = version.strip(\"'\")\n            continue\n\nwith open('VERSION.txt', 'w') as f:\n    f.write(version)\n\n# Use Cython if available.\ntry:\n    from Cython.Build import cythonize\nexcept ImportError:\n    cythonize = None\n\n# By default we'll try to get options via gdal-config. On systems without,\n# options will need to be set in setup.cfg or on the setup command line.\ninclude_dirs = []\nlibrary_dirs = []\nlibraries = []\nextra_link_args = []\ngdal_output = [None]*3\n\ntry:\n    import numpy\n    include_dirs.append(numpy.get_include())\nexcept ImportError:\n    log.critical(\"Numpy and its headers are required to run setup(). Exiting.\")\n    sys.exit(1)\n\ntry:\n    gdal_config = os.environ.get('GDAL_CONFIG', 'gdal-config')\n    for i, flag in enumerate((\"--cflags\", \"--libs\", \"--datadir\")):\n        gdal_output[i] = check_output([gdal_config, flag]).strip()\n\n    for item in gdal_output[0].split():\n        if item.startswith(\"-I\"):\n            include_dirs.extend(item[2:].split(\":\"))\n    for item in gdal_output[1].split():\n        if item.startswith(\"-L\"):\n            library_dirs.extend(item[2:].split(\":\"))\n        elif item.startswith(\"-l\"):\n            libraries.append(item[2:])\n        else:\n            # e.g. -framework GDAL\n            extra_link_args.append(item)\n\nexcept Exception as e:\n    if os.name == \"nt\":\n        log.info((\"Building on Windows requires extra options to setup.py to locate needed GDAL files.\\n\"\n                 \"More information is available in the README.\"))\n    else:\n        log.warning(\"Failed to get options via gdal-config: %s\", str(e))\n\n\n# Conditionally copy the GDAL data. To be used in conjunction with\n# the bdist_wheel command to make self-contained binary wheels.\nif os.environ.get('PACKAGE_DATA'):\n    destdir = 'rasterio/gdal_data'\n    if gdal_output[2]:\n        log.info(\"Copying gdal data from %s\" % gdal_output[2])\n        copy_data_tree(gdal_output[2], destdir)\n    else:\n        # check to see if GDAL_DATA is defined\n        gdal_data = os.environ.get('GDAL_DATA', None)\n        if gdal_data:\n            log.info(\"Copying gdal_data from %s\" % gdal_data)\n            copy_data_tree(gdal_data, destdir)\n\n    # Conditionally copy PROJ.4 data.\n    projdatadir = os.environ.get('PROJ_LIB', '/usr/local/share/proj')\n    if os.path.exists(projdatadir):\n        log.info(\"Copying proj_data from %s\" % projdatadir)\n        copy_data_tree(projdatadir, 'rasterio/proj_data')\n\next_options = dict(\n    include_dirs=include_dirs,\n    library_dirs=library_dirs,\n    libraries=libraries,\n    extra_link_args=extra_link_args)\n\nif not os.name == \"nt\":\n    # These options fail on Windows if using Visual Studio\n    ext_options['extra_compile_args'] = ['-Wno-unused-parameter',\n                                         '-Wno-unused-function']\n\nlog.debug('ext_options:\\n%s', pprint.pformat(ext_options))\n\n# When building from a repo, Cython is required.\nif os.path.exists(\"MANIFEST.in\") and \"clean\" not in sys.argv:\n    log.info(\"MANIFEST.in found, presume a repo, cythonizing...\")\n    if not cythonize:\n        log.critical(\n            \"Cython.Build.cythonize not found. \"\n            \"Cython is required to build from a repo.\")\n        sys.exit(1)\n    ext_modules = cythonize([\n        Extension(\n            'rasterio._base', ['rasterio/_base.pyx'], **ext_options),\n        Extension(\n            'rasterio._io', ['rasterio/_io.pyx'], **ext_options),\n        Extension(\n            'rasterio._copy', ['rasterio/_copy.pyx'], **ext_options),\n        Extension(\n            'rasterio._features', ['rasterio/_features.pyx'], **ext_options),\n        Extension(\n            'rasterio._drivers', ['rasterio/_drivers.pyx'], **ext_options),\n        Extension(\n            'rasterio._warp', ['rasterio/_warp.pyx'], **ext_options),\n        Extension(\n            'rasterio._fill', ['rasterio/_fill.pyx', 'rasterio/rasterfill.cpp'], **ext_options),\n        Extension(\n            'rasterio._err', ['rasterio/_err.pyx'], **ext_options),\n        Extension(\n            'rasterio._example', ['rasterio/_example.pyx'], **ext_options),\n        ], quiet=True)\n\n# If there's no manifest template, as in an sdist, we just specify .c files.\nelse:\n    ext_modules = [\n        Extension(\n            'rasterio._base', ['rasterio/_base.c'], **ext_options),\n        Extension(\n            'rasterio._io', ['rasterio/_io.c'], **ext_options),\n        Extension(\n            'rasterio._copy', ['rasterio/_copy.c'], **ext_options),\n        Extension(\n            'rasterio._features', ['rasterio/_features.c'], **ext_options),\n        Extension(\n            'rasterio._drivers', ['rasterio/_drivers.c'], **ext_options),\n        Extension(\n            'rasterio._warp', ['rasterio/_warp.cpp'], **ext_options),\n        Extension(\n            'rasterio._fill', ['rasterio/_fill.cpp', 'rasterio/rasterfill.cpp'], **ext_options),\n        Extension(\n            'rasterio._err', ['rasterio/_err.c'], **ext_options),\n        Extension(\n            'rasterio._example', ['rasterio/_example.c'], **ext_options),\n            ]\n\nwith open('README.rst') as f:\n    readme = f.read()\n\n# Runtime requirements.\ninst_reqs = [\n    'affine>=1.0',\n    'cligj>=0.2.0',\n    'Numpy>=1.7',\n    'snuggs>=1.3.1',\n    'click-plugins']\n\nif sys.version_info < (3, 4):\n    inst_reqs.append('enum34')\n\nsetup_args = dict(\n    name='rasterio',\n    version=version,\n    description=\"Fast and direct raster I/O for use with Numpy and SciPy\",\n    long_description=readme,\n    classifiers=[\n        'Development Status :: 4 - Beta',\n        'Intended Audience :: Developers',\n        'Intended Audience :: Information Technology',\n        'Intended Audience :: Science/Research',\n        'License :: OSI Approved :: BSD License',\n        'Programming Language :: C',\n        'Programming Language :: Python :: 2.6',\n        'Programming Language :: Python :: 2.7',\n        'Programming Language :: Python :: 3.3',\n        'Programming Language :: Python :: 3.4',\n        'Topic :: Multimedia :: Graphics :: Graphics Conversion',\n        'Topic :: Scientific/Engineering :: GIS'],\n    keywords='raster gdal',\n    author='Sean Gillies',\n    author_email='sean@mapbox.com',\n    url='https://github.com/mapbox/rasterio',\n    license='BSD',\n    package_dir={'': '.'},\n    packages=['rasterio', 'rasterio.rio', 'rasterio.tools'],\n    entry_points='''\n        [console_scripts]\n        rio=rasterio.rio.main:main_group\n\n        [rasterio.rio_commands]\n        bounds=rasterio.rio.features:bounds\n        calc=rasterio.rio.calc:calc\n        clip=rasterio.rio.convert:clip\n        convert=rasterio.rio.convert:convert\n        edit-info=rasterio.rio.info:edit\n        env=rasterio.rio.info:env\n        info=rasterio.rio.info:info\n        insp=rasterio.rio.info:insp\n        mask=rasterio.rio.features:mask\n        merge=rasterio.rio.merge:merge\n        overview=rasterio.rio.overview:overview\n        rasterize=rasterio.rio.features:rasterize\n        sample=rasterio.rio.sample:sample\n        shapes=rasterio.rio.features:shapes\n        stack=rasterio.rio.bands:stack\n        warp=rasterio.rio.warp:warp\n        transform=rasterio.rio.info:transform\n    ''',\n    include_package_data=True,\n    ext_modules=ext_modules,\n    zip_safe=False,\n    install_requires=inst_reqs,\n    extras_require={\n        'ipython': ['ipython>=2.0']})\n\nif os.environ.get('PACKAGE_DATA'):\n    setup_args['package_data'] = {'rasterio': ['gdal_data/*', 'proj_data/*']}\n\nsetup(**setup_args)\n", "path": "setup.py"}]}