gst-uninstalled: Don't add validate plugins to GST_PLUGIN_PATH
[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
18 from common import get_meson
19 from common import git
20
21 SCRIPTDIR = os.path.dirname(os.path.realpath(__file__))
22 PREFIX_DIR = os.path.join(SCRIPTDIR, 'prefix')
23 # Use '_build' as the builddir instead of 'build'
24 DEFAULT_BUILDDIR = os.path.join(SCRIPTDIR, 'build')
25 if not os.path.exists(DEFAULT_BUILDDIR):
26     DEFAULT_BUILDDIR = os.path.join(SCRIPTDIR, '_build')
27
28
29 def prepend_env_var(env, var, value):
30     env[var] = os.pathsep + value + os.pathsep + env.get(var, "")
31     env[var] = env[var].replace(os.pathsep + os.pathsep, os.pathsep).strip(os.pathsep)
32
33
34 def get_subprocess_env(options, gst_version):
35     env = os.environ.copy()
36
37     env["CURRENT_GST"] = os.path.normpath(SCRIPTDIR)
38     env["GST_VALIDATE_SCENARIOS_PATH"] = os.path.normpath(
39         "%s/subprojects/gst-devtools/validate/data/scenarios" % SCRIPTDIR)
40     env["GST_VALIDATE_PLUGIN_PATH"] = os.path.normpath(
41         "%s/subprojects/gst-devtools/validate/plugins" % options.builddir)
42     env["GST_VALIDATE_APPS_DIR"] = os.path.normpath(
43         "%s/subprojects/gst-editing-services/tests/validate" % SCRIPTDIR)
44     prepend_env_var(env, "PATH", os.path.normpath(
45         "%s/subprojects/gst-devtools/validate/tools" % options.builddir))
46     prepend_env_var(env, "PATH", os.path.join(SCRIPTDIR, 'meson'))
47     env["GST_VERSION"] = gst_version
48     env["GST_ENV"] = 'gst-' + gst_version
49     env["GST_PLUGIN_SYSTEM_PATH"] = ""
50     env["GST_PLUGIN_SCANNER"] = os.path.normpath(
51         "%s/subprojects/gstreamer/libs/gst/helpers/gst-plugin-scanner" % options.builddir)
52     env["GST_PTP_HELPER"] = os.path.normpath(
53         "%s/subprojects/gstreamer/libs/gst/helpers/gst-ptp-helper" % options.builddir)
54     env["GST_REGISTRY"] = os.path.normpath(options.builddir + "/registry.dat")
55
56     sharedlib_reg = re.compile(r'\.so|\.dylib|\.dll')
57     typelib_reg = re.compile(r'.*\.typelib$')
58     pluginpath_reg = re.compile(r'lib.*' + re.escape(os.path.normpath('/gstreamer-1.0/')))
59
60     if os.name is 'nt':
61         lib_path_envvar = 'PATH'
62     elif platform.system() == 'Darwin':
63         lib_path_envvar = 'DYLD_LIBRARY_PATH'
64     else:
65         lib_path_envvar = 'LD_LIBRARY_PATH'
66
67     prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(SCRIPTDIR, 'subprojects',
68                                                         'gst-python', 'plugin'))
69     prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(PREFIX_DIR, 'lib',
70                                                         'gstreamer-1.0'))
71     prepend_env_var(env, "PATH", os.path.join(PREFIX_DIR, 'bin'))
72     prepend_env_var(env, lib_path_envvar, os.path.join(PREFIX_DIR, 'lib'))
73     prepend_env_var(env, "GST_VALIDATE_SCENARIOS_PATH", os.path.join(
74         PREFIX_DIR, 'share', 'gstreamer-1.0', 'validate', 'scenarios'))
75     prepend_env_var(env, "GI_TYPELIB_PATH", os.path.join(PREFIX_DIR, 'lib',
76                                                          'lib', 'girepository-1.0'))
77     prepend_env_var(env, "PKG_CONFIG_PATH", os.path.join(PREFIX_DIR, 'lib', 'pkgconfig'))
78
79     meson = get_meson()
80     targets_s = subprocess.check_output(meson + ['introspect', options.builddir, '--targets'])
81     targets = json.loads(targets_s.decode())
82     paths = set()
83     mono_paths = set()
84     srcdir_path = pathlib.Path(options.srcdir)
85     for target in targets:
86         filename = target['filename']
87         root = os.path.dirname(filename)
88         if srcdir_path / "subprojects/gst-devtools/validate/plugins" in (srcdir_path / root).parents:
89             continue
90         if filename.endswith('.dll'):
91             mono_paths.add(os.path.join(options.builddir, root))
92         if typelib_reg.search(filename):
93             prepend_env_var(env, "GI_TYPELIB_PATH",
94                             os.path.join(options.builddir, root))
95         elif sharedlib_reg.search(filename):
96             if target.get('type') != "shared library":
97                 continue
98
99             if target.get('installed') and pluginpath_reg.search(os.path.normpath(target.get('install_filename'))):
100                 prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(options.builddir, root))
101                 continue
102
103             prepend_env_var(env, lib_path_envvar,
104                             os.path.join(options.builddir, root))
105         elif target.get('type') == 'executable' and target.get('installed'):
106             paths.add(os.path.join(options.builddir, root))
107
108     for p in paths:
109         prepend_env_var(env, 'PATH', p)
110
111     if os.name != 'nt':
112         for p in mono_paths:
113             prepend_env_var(env, "MONO_PATH", p)
114
115     presets = set()
116     encoding_targets = set()
117     pkg_dirs = set()
118     python_dirs = set(["%s/subprojects/gstreamer/libs/gst/helpers/" % options.srcdir])
119     if '--installed' in subprocess.check_output(meson + ['introspect', '-h']).decode():
120         installed_s = subprocess.check_output(meson + ['introspect', options.builddir, '--installed'])
121         for path, installpath in json.loads(installed_s.decode()).items():
122             installpath_parts = pathlib.Path(installpath).parts
123             path_parts = pathlib.Path(path).parts
124
125             # We want to add all python modules to the PYTHONPATH
126             # in a manner consistent with the way they would be imported:
127             # For example if the source path /home/meh/foo/bar.py
128             # is to be installed in /usr/lib/python/site-packages/foo/bar.py,
129             # we want to add /home/meh to the PYTHONPATH.
130             # This will only work for projects where the paths to be installed
131             # mirror the installed directory layout, for example if the path
132             # is /home/meh/baz/bar.py and the install path is
133             # /usr/lib/site-packages/foo/bar.py , we will not add anything
134             # to PYTHONPATH, but the current approach works with pygobject
135             # and gst-python at least.
136             if 'site-packages' in installpath_parts:
137                 install_subpath = os.path.join(*installpath_parts[installpath_parts.index('site-packages') + 1:])
138                 if path.endswith(install_subpath):
139                     python_dirs.add(path[:len (install_subpath) * -1])
140
141             if path.endswith('.prs'):
142                 presets.add(os.path.dirname(path))
143             elif path.endswith('.gep'):
144                 encoding_targets.add(
145                     os.path.abspath(os.path.join(os.path.dirname(path), '..')))
146             elif path.endswith('.pc'):
147                 # Is there a -uninstalled pc file for this file?
148                 uninstalled = "{0}-uninstalled.pc".format(path[:-3])
149                 if os.path.exists(uninstalled):
150                     pkg_dirs.add(os.path.dirname(path))
151
152         for p in presets:
153             prepend_env_var(env, 'GST_PRESET_PATH', p)
154
155         for t in encoding_targets:
156             prepend_env_var(env, 'GST_ENCODING_TARGET_PATH', t)
157
158         for pkg_dir in pkg_dirs:
159             prepend_env_var(env, "PKG_CONFIG_PATH", pkg_dir)
160     prepend_env_var(env, "PKG_CONFIG_PATH", os.path.join(options.builddir,
161                                                          'subprojects',
162                                                          'gst-plugins-good',
163                                                          'pkgconfig'))
164
165     for python_dir in python_dirs:
166         prepend_env_var(env, 'PYTHONPATH', python_dir)
167
168     mesonpath = os.path.join(SCRIPTDIR, "meson")
169     if os.path.join(mesonpath):
170         # Add meson/ into PYTHONPATH if we are using a local meson
171         prepend_env_var(env, 'PYTHONPATH', mesonpath)
172
173     return env
174
175 # https://stackoverflow.com/questions/1871549/determine-if-python-is-running-inside-virtualenv
176 def in_venv():
177     return (hasattr(sys, 'real_prefix') or
178             (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))
179
180 if __name__ == "__main__":
181     parser = argparse.ArgumentParser(prog="gstreamer-uninstalled")
182
183     parser.add_argument("--builddir",
184                         default=DEFAULT_BUILDDIR,
185                         help="The meson build directory")
186     parser.add_argument("--srcdir",
187                         default=SCRIPTDIR,
188                         help="The top level source directory")
189     options, args = parser.parse_known_args()
190
191     if not os.path.exists(options.builddir):
192         print("GStreamer not built in %s\n\nBuild it and try again" %
193               options.builddir)
194         exit(1)
195     options.builddir = os.path.abspath(options.builddir)
196
197     if not os.path.exists(options.srcdir):
198         print("The specified source dir does not exist" %
199               options.srcdir)
200         exit(1)
201
202     # The following incantation will retrieve the current branch name.
203     gst_version = git("rev-parse", "--symbolic-full-name", "--abbrev-ref", "HEAD",
204                       repository_path=options.srcdir).strip('\n')
205
206     if not args:
207         if os.name is 'nt':
208             args = [os.environ.get("COMSPEC", r"C:\WINDOWS\system32\cmd.exe")]
209             args += ['/k', 'prompt [gst-{}] $P$G'.format(gst_version)]
210         else:
211             args = [os.environ.get("SHELL", os.path.realpath("/bin/sh"))]
212         if "bash" in args[0]:
213             bashrc = os.path.expanduser('~/.bashrc')
214             if os.path.exists(bashrc):
215                 tmprc = tempfile.NamedTemporaryFile(mode='w')
216                 with open(bashrc, 'r') as src:
217                     shutil.copyfileobj(src, tmprc)
218                 tmprc.write('\nexport PS1="[gst-%s] $PS1"' % gst_version)
219                 tmprc.flush()
220                 # Let the GC remove the tmp file
221                 args.append("--rcfile")
222                 args.append(tmprc.name)
223     try:
224         exit(subprocess.call(args, cwd=options.srcdir, close_fds=False,
225                              env=get_subprocess_env(options, gst_version)))
226     except subprocess.CalledProcessError as e:
227         exit(e.returncode)