06f04ae0d550d39e35c31ae6ca02cb26086c2778
[platform/upstream/gstreamer.git] / gst-env.py
1 #!/usr/bin/env python3
2
3 import argparse
4 import contextlib
5 import json
6 import os
7 import platform
8 import re
9 import site
10 import shutil
11 import subprocess
12 import sys
13 import tempfile
14 import pathlib
15
16 from distutils.sysconfig import get_python_lib
17 from distutils.util import strtobool
18
19 from scripts.common import get_meson
20 from scripts.common import git
21 from scripts.common import win32_get_short_path_name
22 from scripts.common import get_wine_shortpath
23
24 SCRIPTDIR = os.path.dirname(os.path.realpath(__file__))
25 PREFIX_DIR = os.path.join(SCRIPTDIR, 'prefix')
26 # Use '_build' as the builddir instead of 'build'
27 DEFAULT_BUILDDIR = os.path.join(SCRIPTDIR, 'build')
28 if not os.path.exists(DEFAULT_BUILDDIR):
29     DEFAULT_BUILDDIR = os.path.join(SCRIPTDIR, '_build')
30
31 TYPELIB_REG = re.compile(r'.*\.typelib$')
32 SHAREDLIB_REG = re.compile(r'\.so|\.dylib|\.dll')
33 GSTPLUGIN_FILEPATH_REG = re.compile(r'.*/lib[^/]*/gstreamer-1.0/[^/]+$')
34
35
36 def listify(o):
37     if isinstance(o, str):
38         return [o]
39     if isinstance(o, list):
40         return o
41     raise AssertionError('Object {!r} must be a string or a list'.format(o))
42
43 def stringify(o):
44     if isinstance(o, str):
45         return o
46     if isinstance(o, list):
47         if len(o) == 1:
48             return o[0]
49         raise AssertionError('Did not expect object {!r} to have more than one element'.format(o))
50     raise AssertionError('Object {!r} must be a string or a list'.format(o))
51
52 def prepend_env_var(env, var, value, sysroot):
53     if value.startswith(sysroot):
54         value = value[len(sysroot):]
55     # Try not to exceed maximum length limits for env vars on Windows
56     if os.name is 'nt':
57         value = win32_get_short_path_name(value)
58     env_val = env.get(var, '')
59     val = os.pathsep + value + os.pathsep
60     # Don't add the same value twice
61     if val in env_val or env_val.startswith(value + os.pathsep):
62         return
63     env[var] = val + env_val
64     env[var] = env[var].replace(os.pathsep + os.pathsep, os.pathsep).strip(os.pathsep)
65
66 def is_library_target_and_not_plugin(target, filename):
67     '''
68     Don't add plugins to PATH/LD_LIBRARY_PATH because:
69     1. We don't need to
70     2. It causes us to exceed the PATH length limit on Windows and Wine
71     '''
72     if not target['type'].startswith('shared'):
73         return False
74     if not target['installed']:
75         return False
76     # Check if this output of that target is a shared library
77     if not SHAREDLIB_REG.search(filename):
78         return False
79     # Check if it's installed to the gstreamer plugin location
80     for install_filename in target['install_filename']:
81         if install_filename.endswith(os.path.basename(filename)):
82             break
83     else:
84         # None of the installed files in the target correspond to the built
85         # filename, so skip
86         return False
87     if GSTPLUGIN_FILEPATH_REG.search(install_filename.replace('\\', '/')):
88         return False
89     return True
90
91
92 def get_wine_subprocess_env(options, env):
93     with open(os.path.join(options.builddir, 'meson-info', 'intro-buildoptions.json')) as f:
94         buildoptions = json.load(f)
95
96     prefix, = [o for o in buildoptions if o['name'] == 'prefix']
97     path = os.path.normpath(os.path.join(prefix['value'], 'bin'))
98     prepend_env_var(env, "PATH", path, options.sysroot)
99     wine_path = get_wine_shortpath(
100         options.wine.split(' '),
101         [path] + env.get('WINEPATH', '').split(';')
102     )
103     if options.winepath:
104         wine_path += ';' + options.winepath
105     env['WINEPATH'] = wine_path
106     env['WINEDEBUG'] = 'fixme-all'
107
108     return env
109
110
111 def get_subprocess_env(options, gst_version):
112     env = os.environ.copy()
113
114     env["CURRENT_GST"] = os.path.normpath(SCRIPTDIR)
115     env["GST_VERSION"] = gst_version
116     env["GST_VALIDATE_SCENARIOS_PATH"] = os.path.normpath(
117         "%s/subprojects/gst-devtools/validate/data/scenarios" % SCRIPTDIR)
118     env["GST_VALIDATE_PLUGIN_PATH"] = os.path.normpath(
119         "%s/subprojects/gst-devtools/validate/plugins" % options.builddir)
120     env["GST_VALIDATE_APPS_DIR"] = os.path.normpath(
121         "%s/subprojects/gst-editing-services/tests/validate" % SCRIPTDIR)
122     env["GST_ENV"] = 'gst-' + gst_version
123     env["GST_REGISTRY"] = os.path.normpath(options.builddir + "/registry.dat")
124     prepend_env_var(env, "PATH", os.path.normpath(
125         "%s/subprojects/gst-devtools/validate/tools" % options.builddir),
126         options.sysroot)
127
128     if options.wine:
129         return get_wine_subprocess_env(options, env)
130
131     prepend_env_var(env, "PATH", os.path.join(SCRIPTDIR, 'meson'),
132         options.sysroot)
133
134     env["GST_PLUGIN_SYSTEM_PATH"] = ""
135     env["GST_PLUGIN_SCANNER"] = os.path.normpath(
136         "%s/subprojects/gstreamer/libs/gst/helpers/gst-plugin-scanner" % options.builddir)
137     env["GST_PTP_HELPER"] = os.path.normpath(
138         "%s/subprojects/gstreamer/libs/gst/helpers/gst-ptp-helper" % options.builddir)
139
140     if os.name is 'nt':
141         lib_path_envvar = 'PATH'
142     elif platform.system() == 'Darwin':
143         lib_path_envvar = 'DYLD_LIBRARY_PATH'
144     else:
145         lib_path_envvar = 'LD_LIBRARY_PATH'
146
147     prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(SCRIPTDIR, 'subprojects',
148                                                         'gst-python', 'plugin'),
149                     options.sysroot)
150     prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(PREFIX_DIR, 'lib',
151                                                         'gstreamer-1.0'),
152                     options.sysroot)
153     prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(options.builddir, 'subprojects',
154                                                          'libnice', 'gst'),
155                     options.sysroot)
156     prepend_env_var(env, "GST_VALIDATE_SCENARIOS_PATH",
157                     os.path.join(PREFIX_DIR, 'share', 'gstreamer-1.0',
158                                  'validate', 'scenarios'),
159                     options.sysroot)
160     prepend_env_var(env, "GI_TYPELIB_PATH", os.path.join(PREFIX_DIR, 'lib',
161                                                          'lib', 'girepository-1.0'),
162                     options.sysroot)
163     prepend_env_var(env, "PKG_CONFIG_PATH", os.path.join(PREFIX_DIR, 'lib', 'pkgconfig'),
164                     options.sysroot)
165
166     # gst-indent
167     prepend_env_var(env, "PATH", os.path.join(SCRIPTDIR, 'gstreamer', 'tools'),
168                     options.sysroot)
169
170     # Library and binary search paths
171     prepend_env_var(env, "PATH", os.path.join(PREFIX_DIR, 'bin'),
172                     options.sysroot)
173     if lib_path_envvar != 'PATH':
174         prepend_env_var(env, lib_path_envvar, os.path.join(PREFIX_DIR, 'lib'),
175                         options.sysroot)
176         prepend_env_var(env, lib_path_envvar, os.path.join(PREFIX_DIR, 'lib64'),
177                         options.sysroot)
178     elif 'QMAKE' in os.environ:
179         # There's no RPATH on Windows, so we need to set PATH for the qt5 DLLs
180         prepend_env_var(env, 'PATH', os.path.dirname(os.environ['QMAKE']),
181                         options.sysroot)
182
183     meson = get_meson()
184     targets_s = subprocess.check_output(meson + ['introspect', options.builddir, '--targets'])
185     targets = json.loads(targets_s.decode())
186     paths = set()
187     mono_paths = set()
188     srcdir_path = pathlib.Path(options.srcdir)
189     for target in targets:
190         filenames = listify(target['filename'])
191         for filename in filenames:
192             root = os.path.dirname(filename)
193             if srcdir_path / "subprojects/gst-devtools/validate/plugins" in (srcdir_path / root).parents:
194                 continue
195             if filename.endswith('.dll'):
196                 mono_paths.add(os.path.join(options.builddir, root))
197             if TYPELIB_REG.search(filename):
198                 prepend_env_var(env, "GI_TYPELIB_PATH",
199                                 os.path.join(options.builddir, root),
200                                 options.sysroot)
201             elif is_library_target_and_not_plugin(target, filename):
202                 prepend_env_var(env, lib_path_envvar,
203                                 os.path.join(options.builddir, root),
204                                 options.sysroot)
205             elif target['type'] == 'executable' and target['installed']:
206                 paths.add(os.path.join(options.builddir, root))
207
208     with open(os.path.join(options.builddir, 'GstPluginsPath.json')) as f:
209         for plugin_path in json.load(f):
210             prepend_env_var(env, 'GST_PLUGIN_PATH', plugin_path,
211                             options.sysroot)
212
213     for p in paths:
214         prepend_env_var(env, 'PATH', p, options.sysroot)
215
216     if os.name != 'nt':
217         for p in mono_paths:
218             prepend_env_var(env, "MONO_PATH", p, options.sysroot)
219
220     presets = set()
221     encoding_targets = set()
222     pkg_dirs = set()
223     python_dirs = set(["%s/subprojects/gstreamer/libs/gst/helpers/" % options.srcdir])
224     if '--installed' in subprocess.check_output(meson + ['introspect', '-h']).decode():
225         installed_s = subprocess.check_output(meson + ['introspect', options.builddir, '--installed'])
226         for path, installpath in json.loads(installed_s.decode()).items():
227             installpath_parts = pathlib.Path(installpath).parts
228             path_parts = pathlib.Path(path).parts
229
230             # We want to add all python modules to the PYTHONPATH
231             # in a manner consistent with the way they would be imported:
232             # For example if the source path /home/meh/foo/bar.py
233             # is to be installed in /usr/lib/python/site-packages/foo/bar.py,
234             # we want to add /home/meh to the PYTHONPATH.
235             # This will only work for projects where the paths to be installed
236             # mirror the installed directory layout, for example if the path
237             # is /home/meh/baz/bar.py and the install path is
238             # /usr/lib/site-packages/foo/bar.py , we will not add anything
239             # to PYTHONPATH, but the current approach works with pygobject
240             # and gst-python at least.
241             if 'site-packages' in installpath_parts:
242                 install_subpath = os.path.join(*installpath_parts[installpath_parts.index('site-packages') + 1:])
243                 if path.endswith(install_subpath):
244                     python_dirs.add(path[:len (install_subpath) * -1])
245
246             if path.endswith('.prs'):
247                 presets.add(os.path.dirname(path))
248             elif path.endswith('.gep'):
249                 encoding_targets.add(
250                     os.path.abspath(os.path.join(os.path.dirname(path), '..')))
251             elif path.endswith('.pc'):
252                 # Is there a -uninstalled pc file for this file?
253                 uninstalled = "{0}-uninstalled.pc".format(path[:-3])
254                 if os.path.exists(uninstalled):
255                     pkg_dirs.add(os.path.dirname(path))
256
257             if path.endswith('gstomx.conf'):
258                 prepend_env_var(env, 'GST_OMX_CONFIG_DIR', os.path.dirname(path),
259                                 options.sysroot)
260
261         for p in presets:
262             prepend_env_var(env, 'GST_PRESET_PATH', p, options.sysroot)
263
264         for t in encoding_targets:
265             prepend_env_var(env, 'GST_ENCODING_TARGET_PATH', t, options.sysroot)
266
267         for pkg_dir in pkg_dirs:
268             prepend_env_var(env, "PKG_CONFIG_PATH", pkg_dir, options.sysroot)
269     prepend_env_var(env, "PKG_CONFIG_PATH", os.path.join(options.builddir,
270                                                          'subprojects',
271                                                          'gst-plugins-good',
272                                                          'pkgconfig'),
273                     options.sysroot)
274
275     for python_dir in python_dirs:
276         prepend_env_var(env, 'PYTHONPATH', python_dir, options.sysroot)
277
278     mesonpath = os.path.join(SCRIPTDIR, "meson")
279     if os.path.join(mesonpath):
280         # Add meson/ into PYTHONPATH if we are using a local meson
281         prepend_env_var(env, 'PYTHONPATH', mesonpath, options.sysroot)
282
283     # For devhelp books
284     if not 'XDG_DATA_DIRS' in env or not env['XDG_DATA_DIRS']:
285         # Preserve default paths when empty
286         prepend_env_var(env, 'XDG_DATA_DIRS', '/usr/local/share/:/usr/share/', '')
287
288     prepend_env_var (env, 'XDG_DATA_DIRS', os.path.join(options.builddir,
289                                                         'subprojects',
290                                                         'gst-docs',
291                                                         'GStreamer-doc'),
292                      options.sysroot)
293
294     return env
295
296 def get_windows_shell():
297     command = ['powershell.exe' ,'-noprofile', '-executionpolicy', 'bypass', '-file', 'cmd_or_ps.ps1']
298     result = subprocess.check_output(command)
299     return result.decode().strip()
300
301 if __name__ == "__main__":
302     parser = argparse.ArgumentParser(prog="gstreamer-uninstalled")
303
304     parser.add_argument("--builddir",
305                         default=DEFAULT_BUILDDIR,
306                         help="The meson build directory")
307     parser.add_argument("--srcdir",
308                         default=SCRIPTDIR,
309                         help="The top level source directory")
310     parser.add_argument("--sysroot",
311                         default='',
312                         help="The sysroot path used during cross-compilation")
313     parser.add_argument("--wine",
314                         default='',
315                         help="Build a wine env based on specified wine command")
316     parser.add_argument("--winepath",
317                         default='',
318                         help="Exra path to set to WINEPATH.")
319     options, args = parser.parse_known_args()
320
321     if not os.path.exists(options.builddir):
322         print("GStreamer not built in %s\n\nBuild it and try again" %
323               options.builddir)
324         exit(1)
325     options.builddir = os.path.abspath(options.builddir)
326
327     if not os.path.exists(options.srcdir):
328         print("The specified source dir does not exist" %
329               options.srcdir)
330         exit(1)
331
332     # The following incantation will retrieve the current branch name.
333     gst_version = git("rev-parse", "--symbolic-full-name", "--abbrev-ref", "HEAD",
334                       repository_path=options.srcdir).strip('\n')
335
336     if options.wine:
337         gst_version += '-' + os.path.basename(options.wine)
338
339     if not args:
340         if os.name is 'nt':
341             shell = get_windows_shell()
342             if shell == 'powershell.exe':
343                 args = ['powershell.exe']
344                 args += ['-NoLogo', '-NoExit']
345                 prompt = 'function global:prompt {  "[gst-' + gst_version + '"+"] PS " + $PWD + "> "}'
346                 args += ['-Command', prompt]
347             else:
348                 args = [os.environ.get("COMSPEC", r"C:\WINDOWS\system32\cmd.exe")]
349                 args += ['/k', 'prompt [gst-{}] $P$G'.format(gst_version)]
350         else:
351             args = [os.environ.get("SHELL", os.path.realpath("/bin/sh"))]
352         if "bash" in args[0] and not strtobool(os.environ.get("GST_BUILD_DISABLE_PS1_OVERRIDE", r"FALSE")):
353             tmprc = tempfile.NamedTemporaryFile(mode='w')
354             bashrc = os.path.expanduser('~/.bashrc')
355             if os.path.exists(bashrc):
356                 with open(bashrc, 'r') as src:
357                     shutil.copyfileobj(src, tmprc)
358             tmprc.write('\nexport PS1="[gst-%s] $PS1"' % gst_version)
359             tmprc.flush()
360             # Let the GC remove the tmp file
361             args.append("--rcfile")
362             args.append(tmprc.name)
363     try:
364         exit(subprocess.call(args, close_fds=False,
365                              env=get_subprocess_env(options, gst_version)))
366     except subprocess.CalledProcessError as e:
367         exit(e.returncode)