1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
|
# -*- coding: utf-8; mode: python; -*-
#
# GStreamer Development Utilities
#
# Copyright (C) 2007 René Stadler <mail@renestadler.de>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, see <http://www.gnu.org/licenses/>.
"""GStreamer Development Utilities Common utils module."""
import os
import logging
import subprocess as _subprocess
class SingletonMeta (type):
def __init__ (cls, name, bases, dict_):
from weakref import WeakValueDictionary
super (SingletonMeta, cls).__init__ (name, bases, dict_)
cls._singleton_instances = WeakValueDictionary ()
def __call__ (cls, *a, **kw):
kw_key = tuple (sorted (kw.iteritems ()))
try:
obj = cls._singleton_instances[a + kw_key]
except KeyError:
obj = super (SingletonMeta, cls).__call__ (*a, **kw)
cls._singleton_instances[a + kw_key] = obj
return obj
def gettext_cache ():
"""Return a callable object that operates like gettext.gettext, but is much
faster when a string is looked up more than once. This is very useful in
loops, where calling gettext.gettext can quickly become a major performance
bottleneck."""
from gettext import gettext
d = {}
def gettext_cache_access (s):
if not s in d:
d[s] = gettext (s)
return d[s]
return gettext_cache_access
class ClassProperty (property):
"Like the property class, but also invokes the getter for class access."
def __init__ (self, fget = None, fset = None, fdel = None, doc = None):
property.__init__ (self, fget, fset, fdel, doc)
self.__fget = fget
def __get__ (self, obj, obj_class = None):
ret = property.__get__ (self, obj, obj_class)
if ret == self:
return self.__fget (None)
else:
return ret
class _XDGClass (object):
"""Partial implementation of the XDG Base Directory specification v0.6.
http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html"""
def __init__ (self):
self._add_base_dir ("DATA_HOME", "~/.local/share")
self._add_base_dir ("CONFIG_HOME", "~/.config")
self._add_base_dir ("CACHE_HOME", "~/.cache")
def _add_base_dir (self, name, default):
dir = os.environ.get ("XDG_%s" % (name,))
if not dir:
dir = os.path.expanduser (os.path.join (*default.split ("/")))
setattr (self, name, dir)
XDG = _XDGClass ()
class SaveWriteFile (object):
def __init__ (self, filename, mode = "wt"):
from tempfile import mkstemp
self.logger = logging.getLogger ("tempfile")
dir = os.path.dirname (filename)
base_name = os.path.basename (filename)
temp_prefix = "%s-tmp" % (base_name,)
if dir:
# Destination dir differs from current directory, ensure that it
# exists:
try:
os.makedirs (dir)
except OSError:
pass
self.clean_stale (dir, temp_prefix)
fd, temp_name = mkstemp (dir = dir, prefix = temp_prefix)
self.target_name = filename
self.temp_name = temp_name
self.real_file = os.fdopen (fd, mode)
def __enter__ (self):
return self
def __exit__ (self, *exc_args):
if exc_args == (None, None, None,):
self.close ()
else:
self.discard ()
def __del__ (self):
try:
self.discard ()
except AttributeError:
# If __init__ failed, self has no real_file attribute.
pass
def __close_real (self):
if self.real_file:
self.real_file.close ()
self.real_file = None
def clean_stale (self, dir, temp_prefix):
from time import time
from glob import glob
now = time ()
pattern = os.path.join (dir, "%s*" % (temp_prefix,))
for temp_filename in glob (pattern):
mtime = os.stat (temp_filename).st_mtime
if now - mtime > 3600:
self.logger.info ("deleting stale temporary file %s",
temp_filename)
try:
os.unlink (temp_filename)
except EnvironmentError as exc:
self.logger.warning ("deleting stale temporary file "
"failed: %s", exc)
def tell (self, *a, **kw):
return self.real_file.tell (*a, **kw)
def write (self, *a, **kw):
return self.real_file.write (*a, **kw)
def close (self):
self.__close_real ()
if self.temp_name:
try:
os.rename (self.temp_name, self.target_name)
except OSError as exc:
import errno
if exc.errno == errno.EEXIST:
# We are probably on windows.
os.unlink (self.target_name)
os.rename (self.temp_name, self.target_name)
self.temp_name = None
def discard (self):
self.__close_real ()
if self.temp_name:
try:
os.unlink (self.temp_name)
except EnvironmentError as exc:
self.logger.warning ("deleting temporary file failed: %s", exc)
self.temp_name = None
class TeeWriteFile (object):
# TODO Py2.5: Add context manager methods.
def __init__ (self, *file_objects):
self.files = list (file_objects)
def close (self):
for file in self.files:
file.close ()
def flush (self):
for file in self.files:
file.flush ()
def write (self, string):
for file in self.files:
file.write (string)
def writelines (self, lines):
for file in self.files:
file.writelines (lines)
class FixedPopen (_subprocess.Popen):
def __init__ (self, args, **kw):
# Unconditionally specify all descriptors as redirected, to
# work around Python bug #1358527 (which is triggered for
# console-less applications on Windows).
close = []
for name in ("stdin", "stdout", "stderr",):
target = kw.get (name)
if not target:
kw[name] = _subprocess.PIPE
close.append (name)
_subprocess.Popen.__init__ (self, args, **kw)
for name in close:
fp = getattr (self, name)
fp.close ()
setattr (self, name, None)
class DevhelpError (EnvironmentError):
pass
class DevhelpUnavailableError (DevhelpError):
pass
class DevhelpClient (object):
def available (self):
try:
self.version ()
except DevhelpUnavailableError:
return False
else:
return True
def version (self):
return self._invoke ("--version")
def search (self, entry):
self._invoke_no_interact ("-s", entry)
def _check_os_error (self, exc):
import errno
if exc.errno == errno.ENOENT:
raise DevhelpUnavailableError ()
def _invoke (self, *args):
from subprocess import PIPE
try:
proc = FixedPopen (("devhelp",) + args,
stdout = PIPE)
except OSError as exc:
self._check_os_error (exc)
raise
out, err = proc.communicate ()
if proc.returncode is not None and proc.returncode != 0:
raise DevhelpError ("devhelp exited with status %i"
% (proc.returncode,))
return out
def _invoke_no_interact (self, *args):
from subprocess import PIPE
try:
proc = FixedPopen (("devhelp",) + args)
except OSError as exc:
self._check_os_error (exc)
raise
|