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