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