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