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