uninstalled: Set PKG_CONFIG_PATH to point to prefix/lib/pkgconfig
[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     prepend_env_var(env, "PKG_CONFIG_PATH", os.path.join(PREFIX_DIR, 'lib', 'pkgconfig'))
75
76     meson = get_meson()
77     targets_s = subprocess.check_output([sys.executable, meson, 'introspect', options.builddir, '--targets'])
78     targets = json.loads(targets_s.decode())
79     paths = set()
80     mono_paths = set()
81     for target in targets:
82         filename = target['filename']
83         root = os.path.dirname(filename)
84         if filename.endswith('.dll'):
85             mono_paths.add(os.path.join(options.builddir, root))
86         if typelib_reg.search(filename):
87             prepend_env_var(env, "GI_TYPELIB_PATH",
88                             os.path.join(options.builddir, root))
89         elif sharedlib_reg.search(filename):
90             if target.get('type') != "shared library":
91                 continue
92
93             if target.get('installed') and pluginpath_reg.search(os.path.normpath(target.get('install_filename'))):
94                 prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(options.builddir, root))
95                 continue
96
97             prepend_env_var(env, lib_path_envvar,
98                             os.path.join(options.builddir, root))
99         elif target.get('type') == 'executable' and target.get('installed'):
100             paths.add(os.path.join(options.builddir, root))
101
102     for p in paths:
103         prepend_env_var(env, 'PATH', p)
104
105     if os.name != 'nt':
106         for p in mono_paths:
107             prepend_env_var(env, "MONO_PATH", p)
108
109     presets = set()
110     encoding_targets = set()
111     pkg_dirs = set()
112     if '--installed' in subprocess.check_output([sys.executable, meson, 'introspect', '-h']).decode():
113         installed_s = subprocess.check_output([sys.executable, meson, 'introspect',
114                                                options.builddir, '--installed'])
115         for path, installpath in json.loads(installed_s.decode()).items():
116             if path.endswith('.prs'):
117                 presets.add(os.path.dirname(path))
118             elif path.endswith('.gep'):
119                 encoding_targets.add(
120                     os.path.abspath(os.path.join(os.path.dirname(path), '..')))
121             elif path.endswith('.pc'):
122                 # Is there a -uninstalled pc file for this file?
123                 uninstalled = "{0}-uninstalled.pc".format(path[:-3])
124                 if os.path.exists(uninstalled):
125                     pkg_dirs.add(os.path.dirname(path))
126
127         for p in presets:
128             prepend_env_var(env, 'GST_PRESET_PATH', p)
129
130         for t in encoding_targets:
131             prepend_env_var(env, 'GST_ENCODING_TARGET_PATH', t)
132
133         for pkg_dir in pkg_dirs:
134             prepend_env_var(env, "PKG_CONFIG_PATH", pkg_dir)
135     prepend_env_var(env, "PKG_CONFIG_PATH", os.path.join(options.builddir,
136                                                          'subprojects',
137                                                          'gst-plugins-good',
138                                                          'pkgconfig'))
139
140     mesonpath = os.path.join(SCRIPTDIR, "meson")
141     if os.path.join(mesonpath):
142         # Add meson/ into PYTHONPATH if we are using a local meson
143         prepend_env_var(env, 'PYTHONPATH', mesonpath)
144
145     return env
146
147 # https://stackoverflow.com/questions/1871549/determine-if-python-is-running-inside-virtualenv
148 def in_venv():
149     return (hasattr(sys, 'real_prefix') or
150             (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))
151
152 def python_env(options, unset_env=False):
153     """
154     Setup our overrides_hack.py as sitecustomize.py script in user
155     site-packages if unset_env=False, else unset, previously set
156     env.
157     """
158     subprojects_path = os.path.join(options.builddir, "subprojects")
159     gst_python_path = os.path.join(SCRIPTDIR, "subprojects", "gst-python")
160     if not os.path.exists(os.path.join(subprojects_path, "gst-python")) or \
161             not os.path.exists(gst_python_path):
162         return False
163
164     if in_venv ():
165         sitepackages = get_python_lib()
166     else:
167         sitepackages = site.getusersitepackages()
168
169     if not sitepackages:
170         return False
171
172     sitecustomize = os.path.join(sitepackages, "sitecustomize.py")
173     overrides_hack = os.path.join(gst_python_path, "testsuite", "overrides_hack.py")
174     mesonconfig = os.path.join(gst_python_path, "testsuite", "mesonconfig.py")
175     mesonconfig_link = os.path.join(sitepackages, "mesonconfig.py")
176
177     if not unset_env:
178         if os.path.exists(sitecustomize):
179             if os.path.realpath(sitecustomize) == overrides_hack:
180                 print("Customize user site script already linked to the GStreamer one")
181                 return False
182
183             old_sitecustomize = os.path.join(sitepackages,
184                                             "old.sitecustomize.gstuninstalled.py")
185             shutil.move(sitecustomize, old_sitecustomize)
186         elif not os.path.exists(sitepackages):
187             os.makedirs(sitepackages)
188
189         os.symlink(overrides_hack, sitecustomize)
190         os.symlink(mesonconfig, mesonconfig_link)
191         return os.path.realpath(sitecustomize) == overrides_hack
192     else:
193         if not os.path.realpath(sitecustomize) == overrides_hack:
194             return False
195
196         os.remove(sitecustomize)
197         os.remove (mesonconfig_link)
198         old_sitecustomize = os.path.join(sitepackages,
199                                             "old.sitecustomize.gstuninstalled.py")
200
201         if os.path.exists(old_sitecustomize):
202             shutil.move(old_sitecustomize, sitecustomize)
203
204         return True
205
206
207 if __name__ == "__main__":
208     parser = argparse.ArgumentParser(prog="gstreamer-uninstalled")
209
210     parser.add_argument("--builddir",
211                         default=DEFAULT_BUILDDIR,
212                         help="The meson build directory")
213     parser.add_argument("--srcdir",
214                         default=SCRIPTDIR,
215                         help="The top level source directory")
216     parser.add_argument("--gst-version", default="master",
217                         help="The GStreamer major version")
218     options, args = parser.parse_known_args()
219
220     if not os.path.exists(options.builddir):
221         print("GStreamer not built in %s\n\nBuild it and try again" %
222               options.builddir)
223         exit(1)
224     options.builddir = os.path.abspath(options.builddir)
225
226     if not os.path.exists(options.srcdir):
227         print("The specified source dir does not exist" %
228               options.srcdir)
229         exit(1)
230
231     if not args:
232         if os.name is 'nt':
233             args = [os.environ.get("COMSPEC", r"C:\WINDOWS\system32\cmd.exe")]
234         else:
235             args = [os.environ.get("SHELL", os.path.realpath("/bin/sh"))]
236         if "bash" in args[0]:
237             bashrc = os.path.expanduser('~/.bashrc')
238             if os.path.exists(bashrc):
239                 tmprc = tempfile.NamedTemporaryFile(mode='w')
240                 with open(bashrc, 'r') as src:
241                     shutil.copyfileobj(src, tmprc)
242                 tmprc.write('\nexport PS1="[gst-%s] $PS1"' % options.gst_version)
243                 tmprc.flush()
244                 # Let the GC remove the tmp file
245                 args.append("--rcfile")
246                 args.append(tmprc.name)
247     python_set = python_env(options)
248     try:
249         exit(subprocess.call(args, cwd=options.srcdir, close_fds=False,
250                              env=get_subprocess_env(options)))
251     except subprocess.CalledProcessError as e:
252         exit(e.returncode)
253     finally:
254         if python_set:
255             python_env(options, unset_env=True)