gst-uninstalled.py: Look for both 'build' and '_build' for builddir
[platform/upstream/gstreamer.git] / gst-uninstalled.py
1 #!/usr/bin/env python3
2
3 import argparse
4 import json
5 import os
6 import platform
7 import re
8 import site
9 import shutil
10 import subprocess
11 import sys
12 import tempfile
13
14 from distutils.sysconfig import get_python_lib
15
16 from common import get_meson
17
18 SCRIPTDIR = os.path.dirname(os.path.realpath(__file__))
19 PREFIX_DIR = os.path.join(SCRIPTDIR, 'prefix')
20 # Use '_build' as the builddir instead of 'build'
21 DEFAULT_BUILDDIR = os.path.join(SCRIPTDIR, 'build')
22 if not os.path.exists(DEFAULT_BUILDDIR):
23     DEFAULT_BUILDDIR = os.path.join(SCRIPTDIR, '_build')
24
25
26 def prepend_env_var(env, var, value):
27     env[var] = os.pathsep + value + os.pathsep + env.get(var, "")
28     env[var] = env[var].replace(os.pathsep + os.pathsep, os.pathsep).strip(os.pathsep)
29
30
31 def get_subprocess_env(options):
32     env = os.environ.copy()
33
34     env["CURRENT_GST"] = os.path.normpath(SCRIPTDIR)
35     env["GST_VALIDATE_SCENARIOS_PATH"] = os.path.normpath(
36         "%s/subprojects/gst-devtools/validate/data/scenarios" % SCRIPTDIR)
37     env["GST_VALIDATE_PLUGIN_PATH"] = os.path.normpath(
38         "%s/subprojects/gst-devtools/validate/plugins" % options.builddir)
39     env["GST_VALIDATE_APPS_DIR"] = os.path.normpath(
40         "%s/subprojects/gst-editing-services/tests/validate" % SCRIPTDIR)
41     prepend_env_var(env, "PATH", os.path.normpath(
42         "%s/subprojects/gst-devtools/validate/tools" % options.builddir))
43     prepend_env_var(env, "PATH", os.path.join(SCRIPTDIR, 'meson'))
44     env["GST_VERSION"] = options.gst_version
45     env["GST_ENV"] = 'gst-' + options.gst_version
46     env["GST_PLUGIN_SYSTEM_PATH"] = ""
47     env["GST_PLUGIN_SCANNER"] = os.path.normpath(
48         "%s/subprojects/gstreamer/libs/gst/helpers/gst-plugin-scanner" % options.builddir)
49     env["GST_PTP_HELPER"] = os.path.normpath(
50         "%s/subprojects/gstreamer/libs/gst/helpers/gst-ptp-helper" % options.builddir)
51     env["GST_REGISTRY"] = os.path.normpath(options.builddir + "/registry.dat")
52
53     sharedlib_reg = re.compile(r'\.so|\.dylib|\.dll')
54     typelib_reg = re.compile(r'.*\.typelib$')
55     pluginpath_reg = re.compile(r'lib.*' + re.escape(os.path.normpath('/gstreamer-1.0/')))
56
57     if os.name is 'nt':
58         lib_path_envvar = 'PATH'
59     elif platform.system() == 'Darwin':
60         lib_path_envvar = 'DYLD_LIBRARY_PATH'
61     else:
62         lib_path_envvar = 'LD_LIBRARY_PATH'
63
64     prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(SCRIPTDIR, 'subprojects',
65                                                         'gst-python', 'plugin'))
66     prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(PREFIX_DIR, 'lib',
67                                                         'gstreamer-1.0'))
68     prepend_env_var(env, "PATH", os.path.join(PREFIX_DIR, 'bin'))
69     prepend_env_var(env, lib_path_envvar, os.path.join(PREFIX_DIR, 'lib'))
70     prepend_env_var(env, "GST_VALIDATE_SCENARIOS_PATH", os.path.join(
71         PREFIX_DIR, 'share', 'gstreamer-1.0', 'validate', 'scenarios'))
72     prepend_env_var(env, "GI_TYPELIB_PATH", os.path.join(PREFIX_DIR, 'lib',
73                                                          'lib', 'girepository-1.0'))
74
75     meson = get_meson()
76     targets_s = subprocess.check_output([sys.executable, meson, 'introspect', options.builddir, '--targets'])
77     targets = json.loads(targets_s.decode())
78     paths = set()
79     mono_paths = set()
80     for target in targets:
81         filename = target['filename']
82         root = os.path.dirname(filename)
83         if filename.endswith('.dll'):
84             mono_paths.add(os.path.join(options.builddir, root))
85         if typelib_reg.search(filename):
86             prepend_env_var(env, "GI_TYPELIB_PATH",
87                             os.path.join(options.builddir, root))
88         elif sharedlib_reg.search(filename):
89             if target.get('type') != "shared library":
90                 continue
91
92             if target.get('installed') and pluginpath_reg.search(os.path.normpath(target.get('install_filename'))):
93                 prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(options.builddir, root))
94                 continue
95
96             prepend_env_var(env, lib_path_envvar,
97                             os.path.join(options.builddir, root))
98         elif target.get('type') == 'executable' and target.get('installed'):
99             paths.add(os.path.join(options.builddir, root))
100
101     for p in paths:
102         prepend_env_var(env, 'PATH', p)
103
104     if os.name != 'nt':
105         for p in mono_paths:
106             prepend_env_var(env, "MONO_PATH", p)
107
108     presets = set()
109     encoding_targets = set()
110     pkg_dirs = set()
111     if '--installed' in subprocess.check_output([sys.executable, meson, 'introspect', '-h']).decode():
112         installed_s = subprocess.check_output([sys.executable, meson, 'introspect',
113                                                options.builddir, '--installed'])
114         for path, installpath in json.loads(installed_s.decode()).items():
115             if path.endswith('.prs'):
116                 presets.add(os.path.dirname(path))
117             elif path.endswith('.gep'):
118                 encoding_targets.add(
119                     os.path.abspath(os.path.join(os.path.dirname(path), '..')))
120             elif path.endswith('.pc'):
121                 # Is there a -uninstalled pc file for this file?
122                 uninstalled = "{0}-uninstalled.pc".format(path[:-3])
123                 if os.path.exists(uninstalled):
124                     pkg_dirs.add(os.path.dirname(path))
125
126         for p in presets:
127             prepend_env_var(env, 'GST_PRESET_PATH', p)
128
129         for t in encoding_targets:
130             prepend_env_var(env, 'GST_ENCODING_TARGET_PATH', t)
131
132         for pkg_dir in pkg_dirs:
133             prepend_env_var(env, "PKG_CONFIG_PATH", pkg_dir)
134     prepend_env_var(env, "PKG_CONFIG_PATH", os.path.join(options.builddir,
135                                                          'subprojects',
136                                                          'gst-plugins-good',
137                                                          'pkgconfig'))
138
139     mesonpath = os.path.join(SCRIPTDIR, "meson")
140     if os.path.join(mesonpath):
141         # Add meson/ into PYTHONPATH if we are using a local meson
142         prepend_env_var(env, 'PYTHONPATH', mesonpath)
143
144     return env
145
146 # https://stackoverflow.com/questions/1871549/determine-if-python-is-running-inside-virtualenv
147 def in_venv():
148     return (hasattr(sys, 'real_prefix') or
149             (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))
150
151 def python_env(options, unset_env=False):
152     """
153     Setup our overrides_hack.py as sitecustomize.py script in user
154     site-packages if unset_env=False, else unset, previously set
155     env.
156     """
157     subprojects_path = os.path.join(options.builddir, "subprojects")
158     gst_python_path = os.path.join(SCRIPTDIR, "subprojects", "gst-python")
159     if not os.path.exists(os.path.join(subprojects_path, "gst-python")) or \
160             not os.path.exists(gst_python_path):
161         return False
162
163     if in_venv ():
164         sitepackages = get_python_lib()
165     else:
166         sitepackages = site.getusersitepackages()
167
168     if not sitepackages:
169         return False
170
171     sitecustomize = os.path.join(sitepackages, "sitecustomize.py")
172     overrides_hack = os.path.join(gst_python_path, "testsuite", "overrides_hack.py")
173     mesonconfig = os.path.join(gst_python_path, "testsuite", "mesonconfig.py")
174     mesonconfig_link = os.path.join(sitepackages, "mesonconfig.py")
175
176     if not unset_env:
177         if os.path.exists(sitecustomize):
178             if os.path.realpath(sitecustomize) == overrides_hack:
179                 print("Customize user site script already linked to the GStreamer one")
180                 return False
181
182             old_sitecustomize = os.path.join(sitepackages,
183                                             "old.sitecustomize.gstuninstalled.py")
184             shutil.move(sitecustomize, old_sitecustomize)
185         elif not os.path.exists(sitepackages):
186             os.makedirs(sitepackages)
187
188         os.symlink(overrides_hack, sitecustomize)
189         os.symlink(mesonconfig, mesonconfig_link)
190         return os.path.realpath(sitecustomize) == overrides_hack
191     else:
192         if not os.path.realpath(sitecustomize) == overrides_hack:
193             return False
194
195         os.remove(sitecustomize)
196         os.remove (mesonconfig_link)
197         old_sitecustomize = os.path.join(sitepackages,
198                                             "old.sitecustomize.gstuninstalled.py")
199
200         if os.path.exists(old_sitecustomize):
201             shutil.move(old_sitecustomize, sitecustomize)
202
203         return True
204
205
206 if __name__ == "__main__":
207     parser = argparse.ArgumentParser(prog="gstreamer-uninstalled")
208
209     parser.add_argument("--builddir",
210                         default=DEFAULT_BUILDDIR,
211                         help="The meson build directory")
212     parser.add_argument("--srcdir",
213                         default=SCRIPTDIR,
214                         help="The top level source directory")
215     parser.add_argument("--gst-version", default="master",
216                         help="The GStreamer major version")
217     options, args = parser.parse_known_args()
218
219     if not os.path.exists(options.builddir):
220         print("GStreamer not built in %s\n\nBuild it and try again" %
221               options.builddir)
222         exit(1)
223     options.builddir = os.path.abspath(options.builddir)
224
225     if not os.path.exists(options.srcdir):
226         print("The specified source dir does not exist" %
227               options.srcdir)
228         exit(1)
229
230     if not args:
231         if os.name is 'nt':
232             args = [os.environ.get("COMSPEC", r"C:\WINDOWS\system32\cmd.exe")]
233         else:
234             args = [os.environ.get("SHELL", os.path.realpath("/bin/sh"))]
235         if "bash" in args[0]:
236             bashrc = os.path.expanduser('~/.bashrc')
237             if os.path.exists(bashrc):
238                 tmprc = tempfile.NamedTemporaryFile(mode='w')
239                 with open(bashrc, 'r') as src:
240                     shutil.copyfileobj(src, tmprc)
241                 tmprc.write('\nexport PS1="[gst-%s] $PS1"' % options.gst_version)
242                 tmprc.flush()
243                 # Let the GC remove the tmp file
244                 args.append("--rcfile")
245                 args.append(tmprc.name)
246     python_set = python_env(options)
247     try:
248         exit(subprocess.call(args, cwd=options.srcdir, close_fds=False,
249                              env=get_subprocess_env(options)))
250     except subprocess.CalledProcessError as e:
251         exit(e.returncode)
252     finally:
253         if python_set:
254             python_env(options, unset_env=True)