|
1 | 1 | from __future__ import print_function
|
2 | 2 | from __future__ import unicode_literals
|
3 | 3 |
|
| 4 | +import contextlib |
4 | 5 | import distutils.sysconfig
|
5 | 6 | import os
|
6 | 7 | import pipes
|
| 8 | +import shutil |
7 | 9 | import subprocess
|
8 | 10 | import sys
|
| 11 | +import tempfile |
9 | 12 |
|
10 | 13 | from setuptools.command.build_ext import build_ext as _build_ext
|
11 | 14 |
|
12 | 15 |
|
13 | 16 | PYPY = '__pypy__' in sys.builtin_module_names
|
14 | 17 |
|
15 | 18 |
|
| 19 | +def _get_cflags(compiler): |
| 20 | + return ' '.join('-I{}'.format(p) for p in compiler.include_dirs) |
| 21 | + |
| 22 | + |
16 | 23 | def _get_ldflags_pypy():
|
17 | 24 | if PYPY: # pragma: no cover (pypy only)
|
18 | 25 | return '-L{} -lpypy-c'.format(
|
@@ -60,6 +67,15 @@ def _print_cmd(env, cmd):
|
60 | 67 | )
|
61 | 68 |
|
62 | 69 |
|
| 70 | +@contextlib.contextmanager |
| 71 | +def _tmpdir(): |
| 72 | + tempdir = tempfile.mkdtemp() |
| 73 | + try: |
| 74 | + yield tempdir |
| 75 | + finally: |
| 76 | + shutil.rmtree(tempdir) |
| 77 | + |
| 78 | + |
63 | 79 | class build_ext(_build_ext):
|
64 | 80 | def build_extension(self, ext):
|
65 | 81 | # If there are no .go files then the parent should handle this
|
@@ -88,20 +104,32 @@ def build_extension(self, ext):
|
88 | 104 | source_dir, = source_dirs
|
89 | 105 | source_dir = os.path.abspath(source_dir)
|
90 | 106 |
|
91 |
| - env = { |
92 |
| - 'CGO_CFLAGS': ' '.join( |
93 |
| - '-I{}'.format(p) for p in self.compiler.include_dirs |
94 |
| - ), |
95 |
| - 'CGO_LDFLAGS': _get_ldflags(), |
96 |
| - } |
97 |
| - cmd = ( |
98 |
| - 'go', 'build', '-buildmode=c-shared', |
99 |
| - '-o', os.path.abspath(self.get_ext_fullpath(ext.name)), |
100 |
| - ) |
101 |
| - _print_cmd(env, cmd) |
102 |
| - subprocess.check_call( |
103 |
| - cmd, cwd=source_dir, env=dict(os.environ, **env), |
104 |
| - ) |
| 107 | + # Copy the package into a temporary GOPATH environment |
| 108 | + with _tmpdir() as tempdir: |
| 109 | + srcdir = os.path.join(tempdir, 'src') |
| 110 | + os.mkdir(srcdir) |
| 111 | + pkg_path = os.path.join(srcdir, '_mypkg') |
| 112 | + shutil.copytree(source_dir, pkg_path) |
| 113 | + |
| 114 | + env = { |
| 115 | + 'GOPATH': tempdir, |
| 116 | + 'CGO_CFLAGS': _get_cflags(self.compiler), |
| 117 | + 'CGO_LDFLAGS': _get_ldflags(), |
| 118 | + } |
| 119 | + cmd_get = ('go', 'get') |
| 120 | + _print_cmd(env, cmd_get) |
| 121 | + subprocess.check_call( |
| 122 | + cmd_get, cwd=pkg_path, env=dict(os.environ, **env), |
| 123 | + ) |
| 124 | + |
| 125 | + cmd_build = ( |
| 126 | + 'go', 'build', '-buildmode=c-shared', |
| 127 | + '-o', os.path.abspath(self.get_ext_fullpath(ext.name)), |
| 128 | + ) |
| 129 | + _print_cmd(env, cmd_build) |
| 130 | + subprocess.check_call( |
| 131 | + cmd_build, cwd=pkg_path, env=dict(os.environ, **env), |
| 132 | + ) |
105 | 133 |
|
106 | 134 |
|
107 | 135 | def set_build_ext(dist, attr, value):
|
|
0 commit comments