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