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