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