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