buildtools/wafsamba: Ensure we detect the correct python.
[sfrench/samba-autobuild/.git] / buildtools / wafsamba / samba_python.py
1 # waf build tool for building IDL files with pidl
2
3 import os, sys
4 from waflib import Build, Logs, Utils, Configure, Errors
5 from waflib.Configure import conf
6
7 @conf
8 def SAMBA_CHECK_PYTHON(conf, mandatory=True, version=(2,4,2)):
9     # enable tool to build python extensions
10     if conf.env.HAVE_PYTHON_H:
11         conf.check_python_version(version)
12         return
13
14     interpreters = []
15
16     if conf.env['EXTRA_PYTHON']:
17         conf.all_envs['extrapython'] = conf.env.derive()
18         conf.setenv('extrapython')
19         conf.env['PYTHON'] = conf.env['EXTRA_PYTHON']
20         conf.env['IS_EXTRA_PYTHON'] = 'yes'
21         conf.find_program('python', var='PYTHON', mandatory=True)
22         conf.load('python')
23         try:
24             conf.check_python_version((3, 3, 0))
25         except Exception:
26             Logs.warn('extra-python needs to be Python 3.3 or later')
27             raise
28         interpreters.append(conf.env['PYTHON'])
29         conf.setenv('default')
30
31     if not os.getenv('PYTHON', None):
32         conf.env['PYTHON'] = sys.executable
33     conf.find_program('python', var='PYTHON', mandatory=mandatory)
34     conf.load('python')
35     path_python = conf.find_program('python')
36     conf.env.PYTHON_SPECIFIED = (conf.env.PYTHON != path_python)
37     conf.check_python_version(version)
38
39     interpreters.append(conf.env['PYTHON'])
40     conf.env.python_interpreters = interpreters
41
42
43 @conf
44 def SAMBA_CHECK_PYTHON_HEADERS(conf, mandatory=True):
45     if conf.env.disable_python:
46         if mandatory:
47             raise Errors.WafError("Cannot check for python headers when "
48                                  "--disable-python specified")
49
50         conf.msg("python headers", "Check disabled due to --disable-python")
51         # we don't want PYTHONDIR in config.h, as otherwise changing
52         # --prefix causes a complete rebuild
53         conf.env.DEFINES = [x for x in conf.env.DEFINES
54             if not x.startswith('PYTHONDIR=')
55             and not x.startswith('PYTHONARCHDIR=')]
56
57         return
58
59     if conf.env["python_headers_checked"] == []:
60         if conf.env['EXTRA_PYTHON']:
61             conf.setenv('extrapython')
62             _check_python_headers(conf, mandatory=True)
63             conf.setenv('default')
64
65         _check_python_headers(conf, mandatory)
66         conf.env["python_headers_checked"] = "yes"
67
68         if conf.env['EXTRA_PYTHON']:
69             extraversion = conf.all_envs['extrapython']['PYTHON_VERSION']
70             if extraversion == conf.env['PYTHON_VERSION']:
71                 raise Errors.WafError("extrapython %s is same as main python %s" % (
72                     extraversion, conf.env['PYTHON_VERSION']))
73     else:
74         conf.msg("python headers", "using cache")
75
76     # we don't want PYTHONDIR in config.h, as otherwise changing
77     # --prefix causes a complete rebuild
78     conf.env.DEFINES = [x for x in conf.env.DEFINES
79         if not x.startswith('PYTHONDIR=')
80         and not x.startswith('PYTHONARCHDIR=')]
81
82 def _check_python_headers(conf, mandatory):
83     try:
84         conf.errors.ConfigurationError
85         conf.check_python_headers()
86     except conf.errors.ConfigurationError:
87         if mandatory:
88              raise
89
90     if conf.env['PYTHON_VERSION'] > '3':
91         abi_pattern = os.path.splitext(conf.env['pyext_PATTERN'])[0]
92         conf.env['PYTHON_SO_ABI_FLAG'] = abi_pattern % ''
93     else:
94         conf.env['PYTHON_SO_ABI_FLAG'] = ''
95     conf.env['PYTHON_LIBNAME_SO_ABI_FLAG'] = (
96         conf.env['PYTHON_SO_ABI_FLAG'].replace('_', '-'))
97
98     for lib in conf.env['LINKFLAGS_PYEMBED']:
99         if lib.startswith('-L'):
100             conf.env.append_unique('LIBPATH_PYEMBED', lib[2:]) # strip '-L'
101             conf.env['LINKFLAGS_PYEMBED'].remove(lib)
102
103     # same as in waf 1.5, keep only '-fno-strict-aliasing'
104     # and ignore defines such as NDEBUG _FORTIFY_SOURCE=2
105     conf.env.DEFINES_PYEXT = []
106     conf.env.CFLAGS_PYEXT = ['-fno-strict-aliasing']
107
108     return
109
110 def PYTHON_BUILD_IS_ENABLED(self):
111     return self.CONFIG_SET('HAVE_PYTHON_H')
112
113 Build.BuildContext.PYTHON_BUILD_IS_ENABLED = PYTHON_BUILD_IS_ENABLED
114
115
116 def SAMBA_PYTHON(bld, name,
117                  source='',
118                  deps='',
119                  public_deps='',
120                  realname=None,
121                  cflags='',
122                  cflags_end=None,
123                  includes='',
124                  init_function_sentinel=None,
125                  local_include=True,
126                  vars=None,
127                  install=True,
128                  enabled=True):
129     '''build a python extension for Samba'''
130
131     # force-disable when we can't build python modules, so
132     # every single call doesn't need to pass this in.
133     if not bld.PYTHON_BUILD_IS_ENABLED():
134         enabled = False
135
136     if bld.env['IS_EXTRA_PYTHON']:
137         name = 'extra-' + name
138
139     # when we support static python modules we'll need to gather
140     # the list from all the SAMBA_PYTHON() targets
141     if init_function_sentinel is not None:
142         cflags += ' -DSTATIC_LIBPYTHON_MODULES=%s' % init_function_sentinel
143
144     # From https://docs.python.org/2/c-api/arg.html:
145     # Starting with Python 2.5 the type of the length argument to
146     # PyArg_ParseTuple(), PyArg_ParseTupleAndKeywords() and PyArg_Parse()
147     # can be controlled by defining the macro PY_SSIZE_T_CLEAN before
148     # including Python.h. If the macro is defined, length is a Py_ssize_t
149     # rather than an int.
150
151     # Because <Python.h> if often included before includes.h/config.h
152     # This must be in the -D compiler options
153     cflags += ' -DPY_SSIZE_T_CLEAN=1'
154
155     source = bld.EXPAND_VARIABLES(source, vars=vars)
156
157     if realname is not None:
158         link_name = 'python/%s' % realname
159     else:
160         link_name = None
161
162     bld.SAMBA_LIBRARY(name,
163                       source=source,
164                       deps=deps,
165                       public_deps=public_deps,
166                       includes=includes,
167                       cflags=cflags,
168                       cflags_end=cflags_end,
169                       local_include=local_include,
170                       vars=vars,
171                       realname=realname,
172                       link_name=link_name,
173                       pyext=True,
174                       target_type='PYTHON',
175                       install_path='${PYTHONARCHDIR}',
176                       allow_undefined_symbols=True,
177                       install=install,
178                       enabled=enabled)
179
180 Build.BuildContext.SAMBA_PYTHON = SAMBA_PYTHON
181
182
183 def pyembed_libname(bld, name, extrapython=False):
184     if bld.env['PYTHON_SO_ABI_FLAG']:
185         return name + bld.env['PYTHON_SO_ABI_FLAG']
186     else:
187         return name
188
189 Build.BuildContext.pyembed_libname = pyembed_libname
190
191
192 def gen_python_environments(bld, extra_env_vars=()):
193     """Generate all Python environments
194
195     To be used in a for loop. Normally, the loop body will be executed once.
196
197     When --extra-python is used, the body will additionaly be executed
198     with the extra-python environment active.
199     """
200     yield
201
202     if bld.env['EXTRA_PYTHON']:
203         copied = ('GLOBAL_DEPENDENCIES', 'TARGET_TYPE') + tuple(extra_env_vars)
204         for name in copied:
205             bld.all_envs['extrapython'][name] = bld.all_envs['default'][name]
206         default_env = bld.all_envs['default']
207         bld.all_envs['default'] = bld.all_envs['extrapython']
208         yield
209         bld.all_envs['default'] = default_env
210
211 Build.BuildContext.gen_python_environments = gen_python_environments